2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
30 # include "inet/ip_ire.h"
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
37 # if defined(AFS_AIX_ENV)
41 # undef RXDEBUG /* turn off debugging */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
47 # include "afs/sysincludes.h"
48 # include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
54 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
55 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
56 extern afs_int32 afs_termState;
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
83 #include "rx_internal.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
93 #include <afs/rxgen_consts.h>
96 #ifdef AFS_PTHREAD_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
107 /* Local static routines */
108 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
109 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
110 struct rx_call *, struct rx_peer *,
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
114 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
115 void *dummy, int dummy2);
116 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
117 void *dummy, int dummy2);
118 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
119 void *unused, int unused2);
120 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
121 void *unused2, int unused3);
122 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
123 struct rx_packet *packet,
124 int istack, int force);
125 static void rxi_AckAll(struct rx_call *call);
126 static struct rx_connection
127 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
128 u_short serviceId, afs_uint32 cid,
129 afs_uint32 epoch, int type, u_int securityIndex,
130 int *unknownService);
131 static struct rx_packet
132 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
133 int istack, osi_socket socket,
134 afs_uint32 host, u_short port, int *tnop,
135 struct rx_call **newcallp);
136 static struct rx_packet
137 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
139 static struct rx_packet
140 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
141 struct rx_packet *np, int istack);
142 static struct rx_packet
143 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
144 struct rx_packet *np, int istack);
145 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
146 int *tnop, struct rx_call **newcallp);
147 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
148 static void rxi_ClearReceiveQueue(struct rx_call *call);
149 static void rxi_ResetCall(struct rx_call *call, int newcall);
150 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
151 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
152 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
153 static void rxi_KeepAliveOn(struct rx_call *call);
154 static void rxi_GrowMTUOn(struct rx_call *call);
155 static int rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
169 #ifdef RX_ENABLE_LOCKS
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
174 #endif /* RX_ENABLE_LOCKS */
176 /* Constant delay time before sending an acknowledge of the last packet
177 * received. This is to avoid sending an extra acknowledge when the
178 * client is about to make another call, anyway, or the server is
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
184 struct clock rx_lastAckDelay = {0, 400000};
186 /* Constant delay time before sending a soft ack when none was requested.
187 * This is to make sure we send soft acks before the sender times out,
188 * Normally we wait and send a hard ack when the receiver consumes the packet
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
193 struct clock rx_softAckDelay = {0, 100000};
196 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197 * currently allocated within rx. This number is used to allocate the
198 * memory required to return the statistics when queried.
199 * Protected by the rx_rpc_stats mutex.
202 static unsigned int rxi_rpc_peer_stat_cnt;
205 * rxi_rpc_process_stat_cnt counts the total number of local process stat
206 * structures currently allocated within rx. The number is used to allocate
207 * the memory required to return the statistics when queried.
208 * Protected by the rx_rpc_stats mutex.
211 static unsigned int rxi_rpc_process_stat_cnt;
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
224 /* List of free rx_serverQueueEntry structs */
225 struct opr_queue rx_freeServerQueue;
227 #if !defined(offsetof)
228 #include <stddef.h> /* for definition of offsetof() */
231 #ifdef RX_ENABLE_LOCKS
232 afs_kmutex_t rx_atomic_mutex;
233 static afs_kmutex_t freeSQEList_lock;
236 /* Forward prototypes */
237 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
240 putConnection (struct rx_connection *conn) {
241 MUTEX_ENTER(&rx_refcnt_mutex);
243 MUTEX_EXIT(&rx_refcnt_mutex);
246 #ifdef AFS_PTHREAD_ENV
249 * Use procedural initialization of mutexes/condition variables
253 extern afs_kmutex_t rx_quota_mutex;
254 extern afs_kmutex_t rx_pthread_mutex;
255 extern afs_kmutex_t rx_packets_mutex;
256 extern afs_kmutex_t rx_refcnt_mutex;
257 extern afs_kmutex_t des_init_mutex;
258 extern afs_kmutex_t des_random_mutex;
260 extern afs_kmutex_t rx_clock_mutex;
261 extern afs_kmutex_t rxi_connCacheMutex;
262 extern afs_kmutex_t event_handler_mutex;
263 extern afs_kmutex_t listener_mutex;
264 extern afs_kmutex_t rx_if_init_mutex;
265 extern afs_kmutex_t rx_if_mutex;
267 extern afs_kcondvar_t rx_event_handler_cond;
268 extern afs_kcondvar_t rx_listener_cond;
271 static afs_kmutex_t epoch_mutex;
272 static afs_kmutex_t rx_init_mutex;
273 static afs_kmutex_t rx_debug_mutex;
274 static afs_kmutex_t rx_rpc_stats;
277 rxi_InitPthread(void)
279 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
286 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
292 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
293 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
294 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
295 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
298 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
299 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
302 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
303 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
305 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
306 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
307 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
310 #ifdef RX_ENABLE_LOCKS
313 #endif /* RX_LOCKS_DB */
314 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
315 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
317 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
319 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
321 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
323 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
325 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
327 #endif /* RX_ENABLE_LOCKS */
330 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
331 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
333 * The rx_stats_mutex mutex protects the following global variables:
334 * rxi_lowConnRefCount
335 * rxi_lowPeerRefCount
344 * The rx_quota_mutex mutex protects the following global variables:
352 * The rx_freePktQ_lock protects the following global variables:
357 * The rx_packets_mutex mutex protects the following global variables:
365 * The rx_pthread_mutex mutex protects the following global variables:
366 * rxi_fcfs_thread_num
369 #define INIT_PTHREAD_LOCKS
373 /* Variables for handling the minProcs implementation. availProcs gives the
374 * number of threads available in the pool at this moment (not counting dudes
375 * executing right now). totalMin gives the total number of procs required
376 * for handling all minProcs requests. minDeficit is a dynamic variable
377 * tracking the # of procs required to satisfy all of the remaining minProcs
379 * For fine grain locking to work, the quota check and the reservation of
380 * a server thread has to come while rxi_availProcs and rxi_minDeficit
381 * are locked. To this end, the code has been modified under #ifdef
382 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
383 * same time. A new function, ReturnToServerPool() returns the allocation.
385 * A call can be on several queue's (but only one at a time). When
386 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
387 * that no one else is touching the queue. To this end, we store the address
388 * of the queue lock in the call structure (under the call lock) when we
389 * put the call on a queue, and we clear the call_queue_lock when the
390 * call is removed from a queue (once the call lock has been obtained).
391 * This allows rxi_ResetCall to safely synchronize with others wishing
392 * to manipulate the queue.
395 #if defined(RX_ENABLE_LOCKS)
396 static afs_kmutex_t rx_rpc_stats;
399 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
400 ** pretty good that the next packet coming in is from the same connection
401 ** as the last packet, since we're send multiple packets in a transmit window.
403 struct rx_connection *rxLastConn = 0;
405 #ifdef RX_ENABLE_LOCKS
406 /* The locking hierarchy for rx fine grain locking is composed of these
409 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
410 * also protects updates to rx_nextCid
411 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
412 * call->lock - locks call data fields.
413 * These are independent of each other:
414 * rx_freeCallQueue_lock
419 * serverQueueEntry->lock
420 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
422 * peer->lock - locks peer data fields.
423 * conn_data_lock - that more than one thread is not updating a conn data
424 * field at the same time.
435 * Do we need a lock to protect the peer field in the conn structure?
436 * conn->peer was previously a constant for all intents and so has no
437 * lock protecting this field. The multihomed client delta introduced
438 * a RX code change : change the peer field in the connection structure
439 * to that remote interface from which the last packet for this
440 * connection was sent out. This may become an issue if further changes
443 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
444 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
446 /* rxdb_fileID is used to identify the lock location, along with line#. */
447 static int rxdb_fileID = RXDB_FILE_RX;
448 #endif /* RX_LOCKS_DB */
449 #else /* RX_ENABLE_LOCKS */
450 #define SET_CALL_QUEUE_LOCK(C, L)
451 #define CLEAR_CALL_QUEUE_LOCK(C)
452 #endif /* RX_ENABLE_LOCKS */
453 struct rx_serverQueueEntry *rx_waitForPacket = 0;
456 * This mutex serializes calls to our initialization and shutdown routines
457 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
458 * these at any time; all other threads must wait for it to finish running, and
459 * then examine the value of rxi_running afterwards.
461 #ifdef AFS_PTHREAD_ENV
462 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
463 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
465 # define LOCK_RX_INIT
466 # define UNLOCK_RX_INIT
469 /* ------------Exported Interfaces------------- */
471 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
475 return rx_atomic_read(&rxi_running);
478 /* Initialize rx. A port number may be mentioned, in which case this
479 * becomes the default port number for any service installed later.
480 * If 0 is provided for the port number, a random port will be chosen
481 * by the kernel. Whether this will ever overlap anything in
482 * /etc/services is anybody's guess... Returns 0 on success, -1 on
485 rx_InitHost(u_int host, u_int port)
492 char *htable, *ptable;
498 if (rxi_IsRunning()) {
500 return 0; /* already started */
506 if (afs_winsockInit() < 0)
512 * Initialize anything necessary to provide a non-premptive threading
515 rxi_InitializeThreadSupport();
518 /* Allocate and initialize a socket for client and perhaps server
521 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
522 if (rx_socket == OSI_NULLSOCKET) {
525 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
528 #endif /* RX_LOCKS_DB */
529 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
538 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
540 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
542 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
544 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
546 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
547 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
550 #if defined(AFS_HPUX110_ENV)
552 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
553 #endif /* AFS_HPUX110_ENV */
554 #endif /* RX_ENABLE_LOCKS && KERNEL */
557 rx_connDeadTime = 12;
558 rx_tranquil = 0; /* reset flag */
559 rxi_ResetStatistics();
560 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
561 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
562 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
563 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
564 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
565 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
567 /* Malloc up a bunch of packets & buffers */
569 opr_queue_Init(&rx_freePacketQueue);
570 rxi_NeedMorePackets = FALSE;
571 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
572 opr_queue_Init(&rx_mallocedPacketQueue);
574 /* enforce a minimum number of allocated packets */
575 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
576 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
578 /* allocate the initial free packet pool */
579 #ifdef RX_ENABLE_TSFPQ
580 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
581 #else /* RX_ENABLE_TSFPQ */
582 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
583 #endif /* RX_ENABLE_TSFPQ */
590 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
591 tv.tv_sec = clock_now.sec;
592 tv.tv_usec = clock_now.usec;
593 srand((unsigned int)tv.tv_usec);
600 #if defined(KERNEL) && !defined(UKERNEL)
601 /* Really, this should never happen in a real kernel */
604 struct sockaddr_in addr;
606 int addrlen = sizeof(addr);
608 socklen_t addrlen = sizeof(addr);
610 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
611 rxi_Finalize_locked();
612 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
615 rx_port = addr.sin_port;
618 rx_stats.minRtt.sec = 9999999;
619 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
621 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
622 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
624 rx_nextCid &= RX_CIDMASK;
625 MUTEX_ENTER(&rx_quota_mutex);
626 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
627 MUTEX_EXIT(&rx_quota_mutex);
628 /* *Slightly* random start time for the cid. This is just to help
629 * out with the hashing function at the peer */
630 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
631 rx_connHashTable = (struct rx_connection **)htable;
632 rx_peerHashTable = (struct rx_peer **)ptable;
634 rx_hardAckDelay.sec = 0;
635 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
637 rxevent_Init(20, rxi_ReScheduleEvents);
639 /* Initialize various global queues */
640 opr_queue_Init(&rx_idleServerQueue);
641 opr_queue_Init(&rx_freeServerQueue);
642 opr_queue_Init(&rx_incomingCallQueue);
643 opr_queue_Init(&rx_freeCallQueue);
645 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
646 /* Initialize our list of usable IP addresses. */
650 /* Start listener process (exact function is dependent on the
651 * implementation environment--kernel or user space) */
656 rx_atomic_set(&rxi_running, 1);
673 return rx_InitHost(htonl(INADDR_ANY), port);
679 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
680 * maintaing the round trip timer.
685 * Start a new RTT timer for a given call and packet.
687 * There must be no resendEvent already listed for this call, otherwise this
688 * will leak events - intended for internal use within the RTO code only
691 * the RX call to start the timer for
692 * @param[in] lastPacket
693 * a flag indicating whether the last packet has been sent or not
695 * @pre call must be locked before calling this function
699 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
701 struct clock now, retryTime;
703 MUTEX_ASSERT(&call->lock);
707 clock_Add(&retryTime, &call->rto);
709 /* If we're sending the last packet, and we're the client, then the server
710 * may wait for an additional 400ms before returning the ACK, wait for it
711 * rather than hitting a timeout */
712 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
713 clock_Addmsec(&retryTime, 400);
715 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
716 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
721 * Cancel an RTT timer for a given call.
725 * the RX call to cancel the timer for
727 * @pre call must be locked before calling this function
732 rxi_rto_cancel(struct rx_call *call)
734 MUTEX_ASSERT(&call->lock);
735 if (rxevent_Cancel(&call->resendEvent))
736 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
740 * Tell the RTO timer that we have sent a packet.
742 * If the timer isn't already running, then start it. If the timer is running,
746 * the RX call that the packet has been sent on
747 * @param[in] lastPacket
748 * A flag which is true if this is the last packet for the call
750 * @pre The call must be locked before calling this function
755 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
757 if (call->resendEvent)
760 rxi_rto_startTimer(call, lastPacket, istack);
764 * Tell the RTO timer that we have received an new ACK message
766 * This function should be called whenever a call receives an ACK that
767 * acknowledges new packets. Whatever happens, we stop the current timer.
768 * If there are unacked packets in the queue which have been sent, then
769 * we restart the timer from now. Otherwise, we leave it stopped.
772 * the RX call that the ACK has been received on
776 rxi_rto_packet_acked(struct rx_call *call, int istack)
778 struct opr_queue *cursor;
780 rxi_rto_cancel(call);
782 if (opr_queue_IsEmpty(&call->tq))
785 for (opr_queue_Scan(&call->tq, cursor)) {
786 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
787 if (p->header.seq > call->tfirst + call->twind)
790 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
791 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
799 * Set an initial round trip timeout for a peer connection
801 * @param[in] secs The timeout to set in seconds
805 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
806 peer->rtt = secs * 8000;
810 * Set a delayed ack event on the specified call for the given time
812 * @param[in] call - the call on which to set the event
813 * @param[in] offset - the delay from now after which the event fires
816 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
818 struct clock now, when;
820 MUTEX_ASSERT(&call->lock);
823 clock_Add(&when, offset);
825 if (clock_Gt(&call->delayedAckTime, &when) &&
826 rxevent_Cancel(&call->delayedAckEvent)) {
827 /* We successfully cancelled an event too far in the future to install
828 * our new one; we can reuse the reference on the call. */
829 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
832 call->delayedAckTime = when;
833 } else if (call->delayedAckEvent == NULL) {
834 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
835 call->delayedAckEvent = rxevent_Post(&when, &now,
838 call->delayedAckTime = when;
843 rxi_CancelDelayedAckEvent(struct rx_call *call)
845 MUTEX_ASSERT(&call->lock);
846 /* Only drop the ref if we cancelled it before it could run. */
847 if (rxevent_Cancel(&call->delayedAckEvent))
848 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
851 /* called with unincremented nRequestsRunning to see if it is OK to start
852 * a new thread in this service. Could be "no" for two reasons: over the
853 * max quota, or would prevent others from reaching their min quota.
855 #ifdef RX_ENABLE_LOCKS
856 /* This verion of QuotaOK reserves quota if it's ok while the
857 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
860 QuotaOK(struct rx_service *aservice)
862 /* check if over max quota */
863 if (aservice->nRequestsRunning >= aservice->maxProcs) {
867 /* under min quota, we're OK */
868 /* otherwise, can use only if there are enough to allow everyone
869 * to go to their min quota after this guy starts.
872 MUTEX_ENTER(&rx_quota_mutex);
873 if ((aservice->nRequestsRunning < aservice->minProcs)
874 || (rxi_availProcs > rxi_minDeficit)) {
875 aservice->nRequestsRunning++;
876 /* just started call in minProcs pool, need fewer to maintain
878 if (aservice->nRequestsRunning <= aservice->minProcs)
881 MUTEX_EXIT(&rx_quota_mutex);
884 MUTEX_EXIT(&rx_quota_mutex);
890 ReturnToServerPool(struct rx_service *aservice)
892 aservice->nRequestsRunning--;
893 MUTEX_ENTER(&rx_quota_mutex);
894 if (aservice->nRequestsRunning < aservice->minProcs)
897 MUTEX_EXIT(&rx_quota_mutex);
900 #else /* RX_ENABLE_LOCKS */
902 QuotaOK(struct rx_service *aservice)
905 /* under min quota, we're OK */
906 if (aservice->nRequestsRunning < aservice->minProcs)
909 /* check if over max quota */
910 if (aservice->nRequestsRunning >= aservice->maxProcs)
913 /* otherwise, can use only if there are enough to allow everyone
914 * to go to their min quota after this guy starts.
916 MUTEX_ENTER(&rx_quota_mutex);
917 if (rxi_availProcs > rxi_minDeficit)
919 MUTEX_EXIT(&rx_quota_mutex);
922 #endif /* RX_ENABLE_LOCKS */
925 /* Called by rx_StartServer to start up lwp's to service calls.
926 NExistingProcs gives the number of procs already existing, and which
927 therefore needn't be created. */
929 rxi_StartServerProcs(int nExistingProcs)
931 struct rx_service *service;
936 /* For each service, reserve N processes, where N is the "minimum"
937 * number of processes that MUST be able to execute a request in parallel,
938 * at any time, for that process. Also compute the maximum difference
939 * between any service's maximum number of processes that can run
940 * (i.e. the maximum number that ever will be run, and a guarantee
941 * that this number will run if other services aren't running), and its
942 * minimum number. The result is the extra number of processes that
943 * we need in order to provide the latter guarantee */
944 for (i = 0; i < RX_MAX_SERVICES; i++) {
946 service = rx_services[i];
947 if (service == (struct rx_service *)0)
949 nProcs += service->minProcs;
950 diff = service->maxProcs - service->minProcs;
954 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
955 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
956 for (i = 0; i < nProcs; i++) {
957 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
963 /* This routine is only required on Windows */
965 rx_StartClientThread(void)
967 #ifdef AFS_PTHREAD_ENV
969 pid = pthread_self();
970 #endif /* AFS_PTHREAD_ENV */
972 #endif /* AFS_NT40_ENV */
974 /* This routine must be called if any services are exported. If the
975 * donateMe flag is set, the calling process is donated to the server
978 rx_StartServer(int donateMe)
980 struct rx_service *service;
986 /* Start server processes, if necessary (exact function is dependent
987 * on the implementation environment--kernel or user space). DonateMe
988 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
989 * case, one less new proc will be created rx_StartServerProcs.
991 rxi_StartServerProcs(donateMe);
993 /* count up the # of threads in minProcs, and add set the min deficit to
994 * be that value, too.
996 for (i = 0; i < RX_MAX_SERVICES; i++) {
997 service = rx_services[i];
998 if (service == (struct rx_service *)0)
1000 MUTEX_ENTER(&rx_quota_mutex);
1001 rxi_totalMin += service->minProcs;
1002 /* below works even if a thread is running, since minDeficit would
1003 * still have been decremented and later re-incremented.
1005 rxi_minDeficit += service->minProcs;
1006 MUTEX_EXIT(&rx_quota_mutex);
1009 /* Turn on reaping of idle server connections */
1010 rxi_ReapConnections(NULL, NULL, NULL, 0);
1015 #ifndef AFS_NT40_ENV
1019 #ifdef AFS_PTHREAD_ENV
1021 pid = afs_pointer_to_int(pthread_self());
1022 #else /* AFS_PTHREAD_ENV */
1024 LWP_CurrentProcess(&pid);
1025 #endif /* AFS_PTHREAD_ENV */
1027 sprintf(name, "srv_%d", ++nProcs);
1028 if (registerProgram)
1029 (*registerProgram) (pid, name);
1031 #endif /* AFS_NT40_ENV */
1032 rx_ServerProc(NULL); /* Never returns */
1034 #ifdef RX_ENABLE_TSFPQ
1035 /* no use leaving packets around in this thread's local queue if
1036 * it isn't getting donated to the server thread pool.
1038 rxi_FlushLocalPacketsTSFPQ();
1039 #endif /* RX_ENABLE_TSFPQ */
1043 /* Create a new client connection to the specified service, using the
1044 * specified security object to implement the security model for this
1046 struct rx_connection *
1047 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1048 struct rx_securityClass *securityObject,
1049 int serviceSecurityIndex)
1052 struct rx_connection *conn;
1058 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1059 "serviceSecurityIndex %d)\n",
1060 ntohl(shost), ntohs(sport), sservice, securityObject,
1061 serviceSecurityIndex));
1063 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1064 * the case of kmem_alloc? */
1065 conn = rxi_AllocConnection();
1066 #ifdef RX_ENABLE_LOCKS
1067 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1068 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1069 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1072 MUTEX_ENTER(&rx_connHashTable_lock);
1073 conn->type = RX_CLIENT_CONNECTION;
1074 conn->epoch = rx_epoch;
1075 conn->cid = rx_nextCid;
1077 conn->peer = rxi_FindPeer(shost, sport, 1);
1078 conn->serviceId = sservice;
1079 conn->securityObject = securityObject;
1080 conn->securityData = (void *) 0;
1081 conn->securityIndex = serviceSecurityIndex;
1082 rx_SetConnDeadTime(conn, rx_connDeadTime);
1083 rx_SetConnSecondsUntilNatPing(conn, 0);
1084 conn->ackRate = RX_FAST_ACK_RATE;
1085 conn->nSpecific = 0;
1086 conn->specific = NULL;
1087 conn->challengeEvent = NULL;
1088 conn->delayedAbortEvent = NULL;
1089 conn->abortCount = 0;
1091 for (i = 0; i < RX_MAXCALLS; i++) {
1092 conn->twind[i] = rx_initSendWindow;
1093 conn->rwind[i] = rx_initReceiveWindow;
1094 conn->lastBusy[i] = 0;
1097 code = RXS_NewConnection(securityObject, conn);
1099 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1101 conn->refCount++; /* no lock required since only this thread knows... */
1102 conn->next = rx_connHashTable[hashindex];
1103 rx_connHashTable[hashindex] = conn;
1104 if (rx_stats_active)
1105 rx_atomic_inc(&rx_stats.nClientConns);
1106 MUTEX_EXIT(&rx_connHashTable_lock);
1109 rxi_ConnectionError(conn, code);
1115 * Ensure a connection's timeout values are valid.
1117 * @param[in] conn The connection to check
1119 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1120 * unless idleDeadTime and/or hardDeadTime are not set
1124 rxi_CheckConnTimeouts(struct rx_connection *conn)
1126 /* a connection's timeouts must have the relationship
1127 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1128 * total loss of network to a peer may cause an idle timeout instead of a
1129 * dead timeout, simply because the idle timeout gets hit first. Also set
1130 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1131 /* this logic is slightly complicated by the fact that
1132 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1134 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1135 if (conn->idleDeadTime) {
1136 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1138 if (conn->hardDeadTime) {
1139 if (conn->idleDeadTime) {
1140 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1142 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1148 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1150 /* The idea is to set the dead time to a value that allows several
1151 * keepalives to be dropped without timing out the connection. */
1152 conn->secondsUntilDead = seconds;
1153 rxi_CheckConnTimeouts(conn);
1154 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1158 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1160 conn->hardDeadTime = seconds;
1161 rxi_CheckConnTimeouts(conn);
1165 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1167 conn->idleDeadTime = seconds;
1168 rxi_CheckConnTimeouts(conn);
1171 int rxi_lowPeerRefCount = 0;
1172 int rxi_lowConnRefCount = 0;
1175 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1176 * NOTE: must not be called with rx_connHashTable_lock held.
1179 rxi_CleanupConnection(struct rx_connection *conn)
1181 /* Notify the service exporter, if requested, that this connection
1182 * is being destroyed */
1183 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1184 (*conn->service->destroyConnProc) (conn);
1186 /* Notify the security module that this connection is being destroyed */
1187 RXS_DestroyConnection(conn->securityObject, conn);
1189 /* If this is the last connection using the rx_peer struct, set its
1190 * idle time to now. rxi_ReapConnections will reap it if it's still
1191 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1193 MUTEX_ENTER(&rx_peerHashTable_lock);
1194 if (conn->peer->refCount < 2) {
1195 conn->peer->idleWhen = clock_Sec();
1196 if (conn->peer->refCount < 1) {
1197 conn->peer->refCount = 1;
1198 if (rx_stats_active) {
1199 MUTEX_ENTER(&rx_stats_mutex);
1200 rxi_lowPeerRefCount++;
1201 MUTEX_EXIT(&rx_stats_mutex);
1205 conn->peer->refCount--;
1206 MUTEX_EXIT(&rx_peerHashTable_lock);
1208 if (rx_stats_active)
1210 if (conn->type == RX_SERVER_CONNECTION)
1211 rx_atomic_dec(&rx_stats.nServerConns);
1213 rx_atomic_dec(&rx_stats.nClientConns);
1216 if (conn->specific) {
1218 for (i = 0; i < conn->nSpecific; i++) {
1219 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1220 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1221 conn->specific[i] = NULL;
1223 free(conn->specific);
1225 conn->specific = NULL;
1226 conn->nSpecific = 0;
1227 #endif /* !KERNEL */
1229 MUTEX_DESTROY(&conn->conn_call_lock);
1230 MUTEX_DESTROY(&conn->conn_data_lock);
1231 CV_DESTROY(&conn->conn_call_cv);
1233 rxi_FreeConnection(conn);
1236 /* Destroy the specified connection */
1238 rxi_DestroyConnection(struct rx_connection *conn)
1240 MUTEX_ENTER(&rx_connHashTable_lock);
1241 rxi_DestroyConnectionNoLock(conn);
1242 /* conn should be at the head of the cleanup list */
1243 if (conn == rx_connCleanup_list) {
1244 rx_connCleanup_list = rx_connCleanup_list->next;
1245 MUTEX_EXIT(&rx_connHashTable_lock);
1246 rxi_CleanupConnection(conn);
1248 #ifdef RX_ENABLE_LOCKS
1250 MUTEX_EXIT(&rx_connHashTable_lock);
1252 #endif /* RX_ENABLE_LOCKS */
1256 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1258 struct rx_connection **conn_ptr;
1266 MUTEX_ENTER(&conn->conn_data_lock);
1267 MUTEX_ENTER(&rx_refcnt_mutex);
1268 if (conn->refCount > 0)
1271 #ifdef RX_REFCOUNT_CHECK
1272 osi_Assert(conn->refCount == 0);
1274 if (rx_stats_active) {
1275 MUTEX_ENTER(&rx_stats_mutex);
1276 rxi_lowConnRefCount++;
1277 MUTEX_EXIT(&rx_stats_mutex);
1281 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1282 /* Busy; wait till the last guy before proceeding */
1283 MUTEX_EXIT(&rx_refcnt_mutex);
1284 MUTEX_EXIT(&conn->conn_data_lock);
1289 /* If the client previously called rx_NewCall, but it is still
1290 * waiting, treat this as a running call, and wait to destroy the
1291 * connection later when the call completes. */
1292 if ((conn->type == RX_CLIENT_CONNECTION)
1293 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1294 conn->flags |= RX_CONN_DESTROY_ME;
1295 MUTEX_EXIT(&rx_refcnt_mutex);
1296 MUTEX_EXIT(&conn->conn_data_lock);
1300 MUTEX_EXIT(&rx_refcnt_mutex);
1301 MUTEX_EXIT(&conn->conn_data_lock);
1303 /* Check for extant references to this connection */
1304 MUTEX_ENTER(&conn->conn_call_lock);
1305 for (i = 0; i < RX_MAXCALLS; i++) {
1306 struct rx_call *call = conn->call[i];
1309 if (conn->type == RX_CLIENT_CONNECTION) {
1310 MUTEX_ENTER(&call->lock);
1311 if (call->delayedAckEvent) {
1312 /* Push the final acknowledgment out now--there
1313 * won't be a subsequent call to acknowledge the
1314 * last reply packets */
1315 rxi_CancelDelayedAckEvent(call);
1316 if (call->state == RX_STATE_PRECALL
1317 || call->state == RX_STATE_ACTIVE) {
1318 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1323 MUTEX_EXIT(&call->lock);
1327 MUTEX_EXIT(&conn->conn_call_lock);
1329 #ifdef RX_ENABLE_LOCKS
1331 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1332 MUTEX_EXIT(&conn->conn_data_lock);
1334 /* Someone is accessing a packet right now. */
1338 #endif /* RX_ENABLE_LOCKS */
1341 /* Don't destroy the connection if there are any call
1342 * structures still in use */
1343 MUTEX_ENTER(&conn->conn_data_lock);
1344 conn->flags |= RX_CONN_DESTROY_ME;
1345 MUTEX_EXIT(&conn->conn_data_lock);
1350 /* Remove from connection hash table before proceeding */
1352 &rx_connHashTable[CONN_HASH
1353 (peer->host, peer->port, conn->cid, conn->epoch,
1355 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1356 if (*conn_ptr == conn) {
1357 *conn_ptr = conn->next;
1361 /* if the conn that we are destroying was the last connection, then we
1362 * clear rxLastConn as well */
1363 if (rxLastConn == conn)
1366 /* Make sure the connection is completely reset before deleting it. */
1368 * Pending events hold a refcount, so we can't get here if they are
1370 osi_Assert(conn->challengeEvent == NULL);
1371 osi_Assert(conn->delayedAbortEvent == NULL);
1372 osi_Assert(conn->natKeepAliveEvent == NULL);
1373 osi_Assert(conn->checkReachEvent == NULL);
1375 /* Add the connection to the list of destroyed connections that
1376 * need to be cleaned up. This is necessary to avoid deadlocks
1377 * in the routines we call to inform others that this connection is
1378 * being destroyed. */
1379 conn->next = rx_connCleanup_list;
1380 rx_connCleanup_list = conn;
1383 /* Externally available version */
1385 rx_DestroyConnection(struct rx_connection *conn)
1390 rxi_DestroyConnection(conn);
1395 rx_GetConnection(struct rx_connection *conn)
1400 MUTEX_ENTER(&rx_refcnt_mutex);
1402 MUTEX_EXIT(&rx_refcnt_mutex);
1406 #ifdef RX_ENABLE_LOCKS
1407 /* Wait for the transmit queue to no longer be busy.
1408 * requires the call->lock to be held */
1410 rxi_WaitforTQBusy(struct rx_call *call) {
1411 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1412 call->flags |= RX_CALL_TQ_WAIT;
1414 MUTEX_ASSERT(&call->lock);
1415 CV_WAIT(&call->cv_tq, &call->lock);
1417 if (call->tqWaiters == 0) {
1418 call->flags &= ~RX_CALL_TQ_WAIT;
1425 rxi_WakeUpTransmitQueue(struct rx_call *call)
1427 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1428 dpf(("call %p has %d waiters and flags %d\n",
1429 call, call->tqWaiters, call->flags));
1430 #ifdef RX_ENABLE_LOCKS
1431 MUTEX_ASSERT(&call->lock);
1432 CV_BROADCAST(&call->cv_tq);
1433 #else /* RX_ENABLE_LOCKS */
1434 osi_rxWakeup(&call->tq);
1435 #endif /* RX_ENABLE_LOCKS */
1439 /* Start a new rx remote procedure call, on the specified connection.
1440 * If wait is set to 1, wait for a free call channel; otherwise return
1441 * 0. Maxtime gives the maximum number of seconds this call may take,
1442 * after rx_NewCall returns. After this time interval, a call to any
1443 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1444 * For fine grain locking, we hold the conn_call_lock in order to
1445 * to ensure that we don't get signalle after we found a call in an active
1446 * state and before we go to sleep.
1449 rx_NewCall(struct rx_connection *conn)
1451 int i, wait, ignoreBusy = 1;
1452 struct rx_call *call;
1453 struct clock queueTime;
1454 afs_uint32 leastBusy = 0;
1458 dpf(("rx_NewCall(conn %p)\n", conn));
1461 clock_GetTime(&queueTime);
1463 * Check if there are others waiting for a new call.
1464 * If so, let them go first to avoid starving them.
1465 * This is a fairly simple scheme, and might not be
1466 * a complete solution for large numbers of waiters.
1468 * makeCallWaiters keeps track of the number of
1469 * threads waiting to make calls and the
1470 * RX_CONN_MAKECALL_WAITING flag bit is used to
1471 * indicate that there are indeed calls waiting.
1472 * The flag is set when the waiter is incremented.
1473 * It is only cleared when makeCallWaiters is 0.
1474 * This prevents us from accidently destroying the
1475 * connection while it is potentially about to be used.
1477 MUTEX_ENTER(&conn->conn_call_lock);
1478 MUTEX_ENTER(&conn->conn_data_lock);
1479 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1480 conn->flags |= RX_CONN_MAKECALL_WAITING;
1481 conn->makeCallWaiters++;
1482 MUTEX_EXIT(&conn->conn_data_lock);
1484 #ifdef RX_ENABLE_LOCKS
1485 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1489 MUTEX_ENTER(&conn->conn_data_lock);
1490 conn->makeCallWaiters--;
1491 if (conn->makeCallWaiters == 0)
1492 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1495 /* We are now the active thread in rx_NewCall */
1496 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1497 MUTEX_EXIT(&conn->conn_data_lock);
1502 for (i = 0; i < RX_MAXCALLS; i++) {
1503 call = conn->call[i];
1505 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1506 /* we're not ignoring busy call slots; only look at the
1507 * call slot that is the "least" busy */
1511 if (call->state == RX_STATE_DALLY) {
1512 MUTEX_ENTER(&call->lock);
1513 if (call->state == RX_STATE_DALLY) {
1514 if (ignoreBusy && conn->lastBusy[i]) {
1515 /* if we're ignoring busy call slots, skip any ones that
1516 * have lastBusy set */
1517 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1518 leastBusy = conn->lastBusy[i];
1520 MUTEX_EXIT(&call->lock);
1525 * We are setting the state to RX_STATE_RESET to
1526 * ensure that no one else will attempt to use this
1527 * call once we drop the conn->conn_call_lock and
1528 * call->lock. We must drop the conn->conn_call_lock
1529 * before calling rxi_ResetCall because the process
1530 * of clearing the transmit queue can block for an
1531 * extended period of time. If we block while holding
1532 * the conn->conn_call_lock, then all rx_EndCall
1533 * processing will block as well. This has a detrimental
1534 * effect on overall system performance.
1536 call->state = RX_STATE_RESET;
1537 (*call->callNumber)++;
1538 MUTEX_EXIT(&conn->conn_call_lock);
1539 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1540 rxi_ResetCall(call, 0);
1541 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1545 * If we failed to be able to safely obtain the
1546 * conn->conn_call_lock we will have to drop the
1547 * call->lock to avoid a deadlock. When the call->lock
1548 * is released the state of the call can change. If it
1549 * is no longer RX_STATE_RESET then some other thread is
1552 MUTEX_EXIT(&call->lock);
1553 MUTEX_ENTER(&conn->conn_call_lock);
1554 MUTEX_ENTER(&call->lock);
1556 if (call->state == RX_STATE_RESET)
1560 * If we get here it means that after dropping
1561 * the conn->conn_call_lock and call->lock that
1562 * the call is no longer ours. If we can't find
1563 * a free call in the remaining slots we should
1564 * not go immediately to RX_CONN_MAKECALL_WAITING
1565 * because by dropping the conn->conn_call_lock
1566 * we have given up synchronization with rx_EndCall.
1567 * Instead, cycle through one more time to see if
1568 * we can find a call that can call our own.
1570 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1573 MUTEX_EXIT(&call->lock);
1576 if (ignoreBusy && conn->lastBusy[i]) {
1577 /* if we're ignoring busy call slots, skip any ones that
1578 * have lastBusy set */
1579 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1580 leastBusy = conn->lastBusy[i];
1585 /* rxi_NewCall returns with mutex locked */
1586 call = rxi_NewCall(conn, i);
1587 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1591 if (i < RX_MAXCALLS) {
1592 conn->lastBusy[i] = 0;
1597 if (leastBusy && ignoreBusy) {
1598 /* we didn't find a useable call slot, but we did see at least one
1599 * 'busy' slot; look again and only use a slot with the 'least
1605 MUTEX_ENTER(&conn->conn_data_lock);
1606 conn->flags |= RX_CONN_MAKECALL_WAITING;
1607 conn->makeCallWaiters++;
1608 MUTEX_EXIT(&conn->conn_data_lock);
1610 #ifdef RX_ENABLE_LOCKS
1611 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1615 MUTEX_ENTER(&conn->conn_data_lock);
1616 conn->makeCallWaiters--;
1617 if (conn->makeCallWaiters == 0)
1618 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1619 MUTEX_EXIT(&conn->conn_data_lock);
1621 /* Client is initially in send mode */
1622 call->state = RX_STATE_ACTIVE;
1623 call->error = conn->error;
1625 call->app.mode = RX_MODE_ERROR;
1627 call->app.mode = RX_MODE_SENDING;
1629 #ifdef AFS_RXERRQ_ENV
1630 /* remember how many network errors the peer has when we started, so if
1631 * more errors are encountered after the call starts, we know the other endpoint won't be
1632 * responding to us */
1633 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1636 /* remember start time for call in case we have hard dead time limit */
1637 call->queueTime = queueTime;
1638 clock_GetTime(&call->startTime);
1639 call->app.bytesSent = 0;
1640 call->app.bytesRcvd = 0;
1642 /* Turn on busy protocol. */
1643 rxi_KeepAliveOn(call);
1645 /* Attempt MTU discovery */
1646 rxi_GrowMTUOn(call);
1649 * We are no longer the active thread in rx_NewCall
1651 MUTEX_ENTER(&conn->conn_data_lock);
1652 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1653 MUTEX_EXIT(&conn->conn_data_lock);
1656 * Wake up anyone else who might be giving us a chance to
1657 * run (see code above that avoids resource starvation).
1659 #ifdef RX_ENABLE_LOCKS
1660 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1661 osi_Panic("rx_NewCall call about to be used without an empty tq");
1664 CV_BROADCAST(&conn->conn_call_cv);
1668 MUTEX_EXIT(&conn->conn_call_lock);
1669 MUTEX_EXIT(&call->lock);
1672 dpf(("rx_NewCall(call %p)\n", call));
1677 rxi_HasActiveCalls(struct rx_connection *aconn)
1680 struct rx_call *tcall;
1684 for (i = 0; i < RX_MAXCALLS; i++) {
1685 if ((tcall = aconn->call[i])) {
1686 if ((tcall->state == RX_STATE_ACTIVE)
1687 || (tcall->state == RX_STATE_PRECALL)) {
1698 rxi_GetCallNumberVector(struct rx_connection *aconn,
1699 afs_int32 * aint32s)
1702 struct rx_call *tcall;
1706 MUTEX_ENTER(&aconn->conn_call_lock);
1707 for (i = 0; i < RX_MAXCALLS; i++) {
1708 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1709 aint32s[i] = aconn->callNumber[i] + 1;
1711 aint32s[i] = aconn->callNumber[i];
1713 MUTEX_EXIT(&aconn->conn_call_lock);
1719 rxi_SetCallNumberVector(struct rx_connection *aconn,
1720 afs_int32 * aint32s)
1723 struct rx_call *tcall;
1727 MUTEX_ENTER(&aconn->conn_call_lock);
1728 for (i = 0; i < RX_MAXCALLS; i++) {
1729 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1730 aconn->callNumber[i] = aint32s[i] - 1;
1732 aconn->callNumber[i] = aint32s[i];
1734 MUTEX_EXIT(&aconn->conn_call_lock);
1739 /* Advertise a new service. A service is named locally by a UDP port
1740 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1743 char *serviceName; Name for identification purposes (e.g. the
1744 service name might be used for probing for
1747 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1748 char *serviceName, struct rx_securityClass **securityObjects,
1749 int nSecurityObjects,
1750 afs_int32(*serviceProc) (struct rx_call * acall))
1752 osi_socket socket = OSI_NULLSOCKET;
1753 struct rx_service *tservice;
1759 if (serviceId == 0) {
1761 "rx_NewService: service id for service %s is not non-zero.\n",
1768 "rx_NewService: A non-zero port must be specified on this call if a non-zero port was not provided at Rx initialization (service %s).\n",
1776 tservice = rxi_AllocService();
1779 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1781 for (i = 0; i < RX_MAX_SERVICES; i++) {
1782 struct rx_service *service = rx_services[i];
1784 if (port == service->servicePort && host == service->serviceHost) {
1785 if (service->serviceId == serviceId) {
1786 /* The identical service has already been
1787 * installed; if the caller was intending to
1788 * change the security classes used by this
1789 * service, he/she loses. */
1791 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1792 serviceName, serviceId, service->serviceName);
1794 rxi_FreeService(tservice);
1797 /* Different service, same port: re-use the socket
1798 * which is bound to the same port */
1799 socket = service->socket;
1802 if (socket == OSI_NULLSOCKET) {
1803 /* If we don't already have a socket (from another
1804 * service on same port) get a new one */
1805 socket = rxi_GetHostUDPSocket(host, port);
1806 if (socket == OSI_NULLSOCKET) {
1808 rxi_FreeService(tservice);
1813 service->socket = socket;
1814 service->serviceHost = host;
1815 service->servicePort = port;
1816 service->serviceId = serviceId;
1817 service->serviceName = serviceName;
1818 service->nSecurityObjects = nSecurityObjects;
1819 service->securityObjects = securityObjects;
1820 service->minProcs = 0;
1821 service->maxProcs = 1;
1822 service->idleDeadTime = 60;
1823 service->connDeadTime = rx_connDeadTime;
1824 service->executeRequestProc = serviceProc;
1825 service->checkReach = 0;
1826 service->nSpecific = 0;
1827 service->specific = NULL;
1828 rx_services[i] = service; /* not visible until now */
1834 rxi_FreeService(tservice);
1835 (osi_Msg "rx_NewService: cannot support > %d services\n",
1840 /* Set configuration options for all of a service's security objects */
1843 rx_SetSecurityConfiguration(struct rx_service *service,
1844 rx_securityConfigVariables type,
1849 for (i = 0; i<service->nSecurityObjects; i++) {
1850 if (service->securityObjects[i]) {
1851 code = RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1862 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1863 struct rx_securityClass **securityObjects, int nSecurityObjects,
1864 afs_int32(*serviceProc) (struct rx_call * acall))
1866 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1869 /* Generic request processing loop. This routine should be called
1870 * by the implementation dependent rx_ServerProc. If socketp is
1871 * non-null, it will be set to the file descriptor that this thread
1872 * is now listening on. If socketp is null, this routine will never
1875 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1877 struct rx_call *call;
1879 struct rx_service *tservice = NULL;
1886 call = rx_GetCall(threadID, tservice, socketp);
1887 if (socketp && *socketp != OSI_NULLSOCKET) {
1888 /* We are now a listener thread */
1894 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1895 #ifdef RX_ENABLE_LOCKS
1897 #endif /* RX_ENABLE_LOCKS */
1898 afs_termState = AFSOP_STOP_AFS;
1899 afs_osi_Wakeup(&afs_termState);
1900 #ifdef RX_ENABLE_LOCKS
1902 #endif /* RX_ENABLE_LOCKS */
1907 /* if server is restarting( typically smooth shutdown) then do not
1908 * allow any new calls.
1911 if (rx_tranquil && (call != NULL)) {
1915 MUTEX_ENTER(&call->lock);
1917 rxi_CallError(call, RX_RESTARTING);
1918 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1920 MUTEX_EXIT(&call->lock);
1925 tservice = call->conn->service;
1927 if (tservice->beforeProc)
1928 (*tservice->beforeProc) (call);
1930 code = tservice->executeRequestProc(call);
1932 if (tservice->afterProc)
1933 (*tservice->afterProc) (call, code);
1935 rx_EndCall(call, code);
1937 if (tservice->postProc)
1938 (*tservice->postProc) (code);
1940 if (rx_stats_active) {
1941 MUTEX_ENTER(&rx_stats_mutex);
1943 MUTEX_EXIT(&rx_stats_mutex);
1950 rx_WakeupServerProcs(void)
1952 struct rx_serverQueueEntry *np;
1953 struct opr_queue *cursor;
1957 MUTEX_ENTER(&rx_serverPool_lock);
1959 #ifdef RX_ENABLE_LOCKS
1960 if (rx_waitForPacket)
1961 CV_BROADCAST(&rx_waitForPacket->cv);
1962 #else /* RX_ENABLE_LOCKS */
1963 if (rx_waitForPacket)
1964 osi_rxWakeup(rx_waitForPacket);
1965 #endif /* RX_ENABLE_LOCKS */
1966 MUTEX_ENTER(&freeSQEList_lock);
1967 for (opr_queue_Scan(&rx_freeServerQueue, cursor)) {
1968 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1969 #ifdef RX_ENABLE_LOCKS
1970 CV_BROADCAST(&np->cv);
1971 #else /* RX_ENABLE_LOCKS */
1973 #endif /* RX_ENABLE_LOCKS */
1975 MUTEX_EXIT(&freeSQEList_lock);
1976 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1977 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1978 #ifdef RX_ENABLE_LOCKS
1979 CV_BROADCAST(&np->cv);
1980 #else /* RX_ENABLE_LOCKS */
1982 #endif /* RX_ENABLE_LOCKS */
1984 MUTEX_EXIT(&rx_serverPool_lock);
1989 * One thing that seems to happen is that all the server threads get
1990 * tied up on some empty or slow call, and then a whole bunch of calls
1991 * arrive at once, using up the packet pool, so now there are more
1992 * empty calls. The most critical resources here are server threads
1993 * and the free packet pool. The "doreclaim" code seems to help in
1994 * general. I think that eventually we arrive in this state: there
1995 * are lots of pending calls which do have all their packets present,
1996 * so they won't be reclaimed, are multi-packet calls, so they won't
1997 * be scheduled until later, and thus are tying up most of the free
1998 * packet pool for a very long time.
2000 * 1. schedule multi-packet calls if all the packets are present.
2001 * Probably CPU-bound operation, useful to return packets to pool.
2002 * Do what if there is a full window, but the last packet isn't here?
2003 * 3. preserve one thread which *only* runs "best" calls, otherwise
2004 * it sleeps and waits for that type of call.
2005 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2006 * the current dataquota business is badly broken. The quota isn't adjusted
2007 * to reflect how many packets are presently queued for a running call.
2008 * So, when we schedule a queued call with a full window of packets queued
2009 * up for it, that *should* free up a window full of packets for other 2d-class
2010 * calls to be able to use from the packet pool. But it doesn't.
2012 * NB. Most of the time, this code doesn't run -- since idle server threads
2013 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2014 * as a new call arrives.
2016 /* Sleep until a call arrives. Returns a pointer to the call, ready
2017 * for an rx_Read. */
2018 #ifdef RX_ENABLE_LOCKS
2020 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2022 struct rx_serverQueueEntry *sq;
2023 struct rx_call *call = (struct rx_call *)0;
2024 struct rx_service *service = NULL;
2026 MUTEX_ENTER(&freeSQEList_lock);
2028 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2029 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2031 opr_queue_Remove(&sq->entry);
2032 MUTEX_EXIT(&freeSQEList_lock);
2033 } else { /* otherwise allocate a new one and return that */
2034 MUTEX_EXIT(&freeSQEList_lock);
2035 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2036 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2037 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2040 MUTEX_ENTER(&rx_serverPool_lock);
2041 if (cur_service != NULL) {
2042 ReturnToServerPool(cur_service);
2045 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2046 struct rx_call *tcall, *choice2 = NULL;
2047 struct opr_queue *cursor;
2049 /* Scan for eligible incoming calls. A call is not eligible
2050 * if the maximum number of calls for its service type are
2051 * already executing */
2052 /* One thread will process calls FCFS (to prevent starvation),
2053 * while the other threads may run ahead looking for calls which
2054 * have all their input data available immediately. This helps
2055 * keep threads from blocking, waiting for data from the client. */
2056 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2057 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2059 service = tcall->conn->service;
2060 if (!QuotaOK(service)) {
2063 MUTEX_ENTER(&rx_pthread_mutex);
2064 if (tno == rxi_fcfs_thread_num
2065 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2066 MUTEX_EXIT(&rx_pthread_mutex);
2067 /* If we're the fcfs thread , then we'll just use
2068 * this call. If we haven't been able to find an optimal
2069 * choice, and we're at the end of the list, then use a
2070 * 2d choice if one has been identified. Otherwise... */
2071 call = (choice2 ? choice2 : tcall);
2072 service = call->conn->service;
2074 MUTEX_EXIT(&rx_pthread_mutex);
2075 if (!opr_queue_IsEmpty(&tcall->rq)) {
2076 struct rx_packet *rp;
2077 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2079 if (rp->header.seq == 1) {
2081 || (rp->header.flags & RX_LAST_PACKET)) {
2083 } else if (rxi_2dchoice && !choice2
2084 && !(tcall->flags & RX_CALL_CLEARED)
2085 && (tcall->rprev > rxi_HardAckRate)) {
2095 ReturnToServerPool(service);
2101 opr_queue_Remove(&call->entry);
2102 MUTEX_EXIT(&rx_serverPool_lock);
2103 MUTEX_ENTER(&call->lock);
2104 CLEAR_CALL_QUEUE_LOCK(call);
2106 if (call->flags & RX_CALL_WAIT_PROC) {
2107 call->flags &= ~RX_CALL_WAIT_PROC;
2108 rx_atomic_dec(&rx_nWaiting);
2111 if (call->state != RX_STATE_PRECALL || call->error) {
2112 MUTEX_EXIT(&call->lock);
2113 MUTEX_ENTER(&rx_serverPool_lock);
2114 ReturnToServerPool(service);
2119 if (opr_queue_IsEmpty(&call->rq)
2120 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2121 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2125 /* If there are no eligible incoming calls, add this process
2126 * to the idle server queue, to wait for one */
2130 *socketp = OSI_NULLSOCKET;
2132 sq->socketp = socketp;
2133 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2134 #ifndef AFS_AIX41_ENV
2135 rx_waitForPacket = sq;
2136 #endif /* AFS_AIX41_ENV */
2138 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2140 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2144 } while (!(call = sq->newcall)
2145 && !(socketp && *socketp != OSI_NULLSOCKET));
2146 if (opr_queue_IsOnQueue(&sq->entry)) {
2147 opr_queue_Remove(&sq->entry);
2149 MUTEX_EXIT(&rx_serverPool_lock);
2151 MUTEX_ENTER(&call->lock);
2157 MUTEX_ENTER(&freeSQEList_lock);
2158 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2159 MUTEX_EXIT(&freeSQEList_lock);
2162 clock_GetTime(&call->startTime);
2163 call->state = RX_STATE_ACTIVE;
2164 call->app.mode = RX_MODE_RECEIVING;
2165 #ifdef RX_KERNEL_TRACE
2166 if (ICL_SETACTIVE(afs_iclSetp)) {
2167 int glockOwner = ISAFS_GLOCK();
2170 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2171 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2178 rxi_calltrace(RX_CALL_START, call);
2179 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2180 call->conn->service->servicePort, call->conn->service->serviceId,
2183 MUTEX_EXIT(&call->lock);
2184 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2186 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2191 #else /* RX_ENABLE_LOCKS */
2193 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2195 struct rx_serverQueueEntry *sq;
2196 struct rx_call *call = (struct rx_call *)0, *choice2;
2197 struct rx_service *service = NULL;
2201 MUTEX_ENTER(&freeSQEList_lock);
2203 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2204 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2206 opr_queue_Remove(&sq->entry);
2207 MUTEX_EXIT(&freeSQEList_lock);
2208 } else { /* otherwise allocate a new one and return that */
2209 MUTEX_EXIT(&freeSQEList_lock);
2210 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2211 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2212 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2214 MUTEX_ENTER(&sq->lock);
2216 if (cur_service != NULL) {
2217 cur_service->nRequestsRunning--;
2218 MUTEX_ENTER(&rx_quota_mutex);
2219 if (cur_service->nRequestsRunning < cur_service->minProcs)
2222 MUTEX_EXIT(&rx_quota_mutex);
2224 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2225 struct rx_call *tcall;
2226 struct opr_queue *cursor;
2227 /* Scan for eligible incoming calls. A call is not eligible
2228 * if the maximum number of calls for its service type are
2229 * already executing */
2230 /* One thread will process calls FCFS (to prevent starvation),
2231 * while the other threads may run ahead looking for calls which
2232 * have all their input data available immediately. This helps
2233 * keep threads from blocking, waiting for data from the client. */
2234 choice2 = (struct rx_call *)0;
2235 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2236 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2237 service = tcall->conn->service;
2238 if (QuotaOK(service)) {
2239 MUTEX_ENTER(&rx_pthread_mutex);
2240 if (tno == rxi_fcfs_thread_num
2241 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2242 MUTEX_EXIT(&rx_pthread_mutex);
2243 /* If we're the fcfs thread, then we'll just use
2244 * this call. If we haven't been able to find an optimal
2245 * choice, and we're at the end of the list, then use a
2246 * 2d choice if one has been identified. Otherwise... */
2247 call = (choice2 ? choice2 : tcall);
2248 service = call->conn->service;
2250 MUTEX_EXIT(&rx_pthread_mutex);
2251 if (!opr_queue_IsEmpty(&tcall->rq)) {
2252 struct rx_packet *rp;
2253 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2255 if (rp->header.seq == 1
2257 || (rp->header.flags & RX_LAST_PACKET))) {
2259 } else if (rxi_2dchoice && !choice2
2260 && !(tcall->flags & RX_CALL_CLEARED)
2261 && (tcall->rprev > rxi_HardAckRate)) {
2274 opr_queue_Remove(&call->entry);
2275 CLEAR_CALL_QUEUE_LOCK(call);
2276 /* we can't schedule a call if there's no data!!! */
2277 /* send an ack if there's no data, if we're missing the
2278 * first packet, or we're missing something between first
2279 * and last -- there's a "hole" in the incoming data. */
2280 if (opr_queue_IsEmpty(&call->rq)
2281 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2282 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2283 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2285 call->flags &= (~RX_CALL_WAIT_PROC);
2286 service->nRequestsRunning++;
2287 /* just started call in minProcs pool, need fewer to maintain
2289 MUTEX_ENTER(&rx_quota_mutex);
2290 if (service->nRequestsRunning <= service->minProcs)
2293 MUTEX_EXIT(&rx_quota_mutex);
2294 rx_atomic_dec(&rx_nWaiting);
2295 /* MUTEX_EXIT(&call->lock); */
2297 /* If there are no eligible incoming calls, add this process
2298 * to the idle server queue, to wait for one */
2301 *socketp = OSI_NULLSOCKET;
2303 sq->socketp = socketp;
2304 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2308 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2310 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2311 return (struct rx_call *)0;
2314 } while (!(call = sq->newcall)
2315 && !(socketp && *socketp != OSI_NULLSOCKET));
2317 MUTEX_EXIT(&sq->lock);
2319 MUTEX_ENTER(&freeSQEList_lock);
2320 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2321 MUTEX_EXIT(&freeSQEList_lock);
2324 clock_GetTime(&call->startTime);
2325 call->state = RX_STATE_ACTIVE;
2326 call->app.mode = RX_MODE_RECEIVING;
2327 #ifdef RX_KERNEL_TRACE
2328 if (ICL_SETACTIVE(afs_iclSetp)) {
2329 int glockOwner = ISAFS_GLOCK();
2332 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2333 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2340 rxi_calltrace(RX_CALL_START, call);
2341 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2342 call->conn->service->servicePort, call->conn->service->serviceId,
2345 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2352 #endif /* RX_ENABLE_LOCKS */
2356 /* Establish a procedure to be called when a packet arrives for a
2357 * call. This routine will be called at most once after each call,
2358 * and will also be called if there is an error condition on the or
2359 * the call is complete. Used by multi rx to build a selection
2360 * function which determines which of several calls is likely to be a
2361 * good one to read from.
2362 * NOTE: the way this is currently implemented it is probably only a
2363 * good idea to (1) use it immediately after a newcall (clients only)
2364 * and (2) only use it once. Other uses currently void your warranty
2367 rx_SetArrivalProc(struct rx_call *call,
2368 void (*proc) (struct rx_call * call,
2371 void * handle, int arg)
2373 call->arrivalProc = proc;
2374 call->arrivalProcHandle = handle;
2375 call->arrivalProcArg = arg;
2378 /* Call is finished (possibly prematurely). Return rc to the peer, if
2379 * appropriate, and return the final error code from the conversation
2383 rx_EndCall(struct rx_call *call, afs_int32 rc)
2385 struct rx_connection *conn = call->conn;
2389 dpf(("rx_EndCall(call %p rc %d error %d abortCode %d)\n",
2390 call, rc, call->error, call->abortCode));
2393 MUTEX_ENTER(&call->lock);
2395 if (rc == 0 && call->error == 0) {
2396 call->abortCode = 0;
2397 call->abortCount = 0;
2400 call->arrivalProc = NULL;
2401 if (rc && call->error == 0) {
2402 rxi_CallError(call, rc);
2403 call->app.mode = RX_MODE_ERROR;
2404 /* Send an abort message to the peer if this error code has
2405 * only just been set. If it was set previously, assume the
2406 * peer has already been sent the error code or will request it
2408 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2410 if (conn->type == RX_SERVER_CONNECTION) {
2411 /* Make sure reply or at least dummy reply is sent */
2412 if (call->app.mode == RX_MODE_RECEIVING) {
2413 MUTEX_EXIT(&call->lock);
2414 rxi_WriteProc(call, 0, 0);
2415 MUTEX_ENTER(&call->lock);
2417 if (call->app.mode == RX_MODE_SENDING) {
2418 rxi_FlushWriteLocked(call);
2420 rxi_calltrace(RX_CALL_END, call);
2421 /* Call goes to hold state until reply packets are acknowledged */
2422 if (call->tfirst + call->nSoftAcked < call->tnext) {
2423 call->state = RX_STATE_HOLD;
2425 call->state = RX_STATE_DALLY;
2426 rxi_ClearTransmitQueue(call, 0);
2427 rxi_rto_cancel(call);
2428 rxi_CancelKeepAliveEvent(call);
2430 } else { /* Client connection */
2432 /* Make sure server receives input packets, in the case where
2433 * no reply arguments are expected */
2435 if ((call->app.mode == RX_MODE_SENDING)
2436 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2437 MUTEX_EXIT(&call->lock);
2438 (void)rxi_ReadProc(call, &dummy, 1);
2439 MUTEX_ENTER(&call->lock);
2442 /* If we had an outstanding delayed ack, be nice to the server
2443 * and force-send it now.
2445 if (call->delayedAckEvent) {
2446 rxi_CancelDelayedAckEvent(call);
2447 rxi_SendDelayedAck(NULL, call, NULL, 0);
2450 /* We need to release the call lock since it's lower than the
2451 * conn_call_lock and we don't want to hold the conn_call_lock
2452 * over the rx_ReadProc call. The conn_call_lock needs to be held
2453 * here for the case where rx_NewCall is perusing the calls on
2454 * the connection structure. We don't want to signal until
2455 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2456 * have checked this call, found it active and by the time it
2457 * goes to sleep, will have missed the signal.
2459 MUTEX_EXIT(&call->lock);
2460 MUTEX_ENTER(&conn->conn_call_lock);
2461 MUTEX_ENTER(&call->lock);
2464 /* While there are some circumstances where a call with an error is
2465 * obviously not on a "busy" channel, be conservative (clearing
2466 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2467 * The call channel is definitely not busy if we just successfully
2468 * completed a call on it. */
2469 conn->lastBusy[call->channel] = 0;
2471 } else if (call->error == RX_CALL_TIMEOUT) {
2472 /* The call is still probably running on the server side, so try to
2473 * avoid this call channel in the future. */
2474 conn->lastBusy[call->channel] = clock_Sec();
2477 MUTEX_ENTER(&conn->conn_data_lock);
2478 conn->flags |= RX_CONN_BUSY;
2479 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2480 MUTEX_EXIT(&conn->conn_data_lock);
2481 #ifdef RX_ENABLE_LOCKS
2482 CV_BROADCAST(&conn->conn_call_cv);
2487 #ifdef RX_ENABLE_LOCKS
2489 MUTEX_EXIT(&conn->conn_data_lock);
2491 #endif /* RX_ENABLE_LOCKS */
2492 call->state = RX_STATE_DALLY;
2494 error = call->error;
2496 /* currentPacket, nLeft, and NFree must be zeroed here, because
2497 * ResetCall cannot: ResetCall may be called at splnet(), in the
2498 * kernel version, and may interrupt the macros rx_Read or
2499 * rx_Write, which run at normal priority for efficiency. */
2500 if (call->app.currentPacket) {
2501 #ifdef RX_TRACK_PACKETS
2502 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2504 rxi_FreePacket(call->app.currentPacket);
2505 call->app.currentPacket = (struct rx_packet *)0;
2508 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2510 /* Free any packets from the last call to ReadvProc/WritevProc */
2511 #ifdef RXDEBUG_PACKET
2513 #endif /* RXDEBUG_PACKET */
2514 rxi_FreePackets(0, &call->app.iovq);
2515 MUTEX_EXIT(&call->lock);
2517 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2518 if (conn->type == RX_CLIENT_CONNECTION) {
2519 MUTEX_ENTER(&conn->conn_data_lock);
2520 conn->flags &= ~RX_CONN_BUSY;
2521 MUTEX_EXIT(&conn->conn_data_lock);
2522 MUTEX_EXIT(&conn->conn_call_lock);
2526 * Map errors to the local host's errno.h format.
2528 error = ntoh_syserr_conv(error);
2530 /* If the caller said the call failed with some error, we had better
2531 * return an error code. */
2532 osi_Assert(!rc || error);
2536 #if !defined(KERNEL)
2538 /* Call this routine when shutting down a server or client (especially
2539 * clients). This will allow Rx to gracefully garbage collect server
2540 * connections, and reduce the number of retries that a server might
2541 * make to a dead client.
2542 * This is not quite right, since some calls may still be ongoing and
2543 * we can't lock them to destroy them. */
2549 if (!rxi_IsRunning()) {
2551 return; /* Already shutdown. */
2553 rxi_Finalize_locked();
2558 rxi_Finalize_locked(void)
2560 struct rx_connection **conn_ptr, **conn_end;
2561 rx_atomic_set(&rxi_running, 0);
2562 rxi_DeleteCachedConnections();
2563 if (rx_connHashTable) {
2564 MUTEX_ENTER(&rx_connHashTable_lock);
2565 for (conn_ptr = &rx_connHashTable[0], conn_end =
2566 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2568 struct rx_connection *conn, *next;
2569 for (conn = *conn_ptr; conn; conn = next) {
2571 if (conn->type == RX_CLIENT_CONNECTION) {
2572 rx_GetConnection(conn);
2573 #ifdef RX_ENABLE_LOCKS
2574 rxi_DestroyConnectionNoLock(conn);
2575 #else /* RX_ENABLE_LOCKS */
2576 rxi_DestroyConnection(conn);
2577 #endif /* RX_ENABLE_LOCKS */
2581 #ifdef RX_ENABLE_LOCKS
2582 while (rx_connCleanup_list) {
2583 struct rx_connection *conn;
2584 conn = rx_connCleanup_list;
2585 rx_connCleanup_list = rx_connCleanup_list->next;
2586 MUTEX_EXIT(&rx_connHashTable_lock);
2587 rxi_CleanupConnection(conn);
2588 MUTEX_ENTER(&rx_connHashTable_lock);
2590 MUTEX_EXIT(&rx_connHashTable_lock);
2591 #endif /* RX_ENABLE_LOCKS */
2596 afs_winsockCleanup();
2601 /* if we wakeup packet waiter too often, can get in loop with two
2602 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2604 rxi_PacketsUnWait(void)
2606 if (!rx_waitingForPackets) {
2610 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2611 return; /* still over quota */
2614 rx_waitingForPackets = 0;
2615 #ifdef RX_ENABLE_LOCKS
2616 CV_BROADCAST(&rx_waitingForPackets_cv);
2618 osi_rxWakeup(&rx_waitingForPackets);
2624 /* ------------------Internal interfaces------------------------- */
2626 /* Return this process's service structure for the
2627 * specified socket and service */
2628 static struct rx_service *
2629 rxi_FindService(osi_socket socket, u_short serviceId)
2631 struct rx_service **sp;
2632 for (sp = &rx_services[0]; *sp; sp++) {
2633 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2639 #ifdef RXDEBUG_PACKET
2640 #ifdef KDUMP_RX_LOCK
2641 static struct rx_call_rx_lock *rx_allCallsp = 0;
2643 static struct rx_call *rx_allCallsp = 0;
2645 #endif /* RXDEBUG_PACKET */
2647 /* Allocate a call structure, for the indicated channel of the
2648 * supplied connection. The mode and state of the call must be set by
2649 * the caller. Returns the call with mutex locked. */
2650 static struct rx_call *
2651 rxi_NewCall(struct rx_connection *conn, int channel)
2653 struct rx_call *call;
2654 #ifdef RX_ENABLE_LOCKS
2655 struct rx_call *cp; /* Call pointer temp */
2656 struct opr_queue *cursor;
2659 dpf(("rxi_NewCall(conn %p, channel %d)\n", conn, channel));
2661 /* Grab an existing call structure, or allocate a new one.
2662 * Existing call structures are assumed to have been left reset by
2664 MUTEX_ENTER(&rx_freeCallQueue_lock);
2666 #ifdef RX_ENABLE_LOCKS
2668 * EXCEPT that the TQ might not yet be cleared out.
2669 * Skip over those with in-use TQs.
2672 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2673 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2674 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2680 #else /* RX_ENABLE_LOCKS */
2681 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2682 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2683 #endif /* RX_ENABLE_LOCKS */
2684 opr_queue_Remove(&call->entry);
2685 if (rx_stats_active)
2686 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2687 MUTEX_EXIT(&rx_freeCallQueue_lock);
2688 MUTEX_ENTER(&call->lock);
2689 CLEAR_CALL_QUEUE_LOCK(call);
2690 #ifdef RX_ENABLE_LOCKS
2691 /* Now, if TQ wasn't cleared earlier, do it now. */
2692 rxi_WaitforTQBusy(call);
2693 if (call->flags & RX_CALL_TQ_CLEARME) {
2694 rxi_ClearTransmitQueue(call, 1);
2695 /*queue_Init(&call->tq);*/
2697 #endif /* RX_ENABLE_LOCKS */
2698 /* Bind the call to its connection structure */
2700 rxi_ResetCall(call, 1);
2703 call = rxi_Alloc(sizeof(struct rx_call));
2704 #ifdef RXDEBUG_PACKET
2705 call->allNextp = rx_allCallsp;
2706 rx_allCallsp = call;
2708 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2709 #else /* RXDEBUG_PACKET */
2710 rx_atomic_inc(&rx_stats.nCallStructs);
2711 #endif /* RXDEBUG_PACKET */
2713 MUTEX_EXIT(&rx_freeCallQueue_lock);
2714 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2715 MUTEX_ENTER(&call->lock);
2716 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2717 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2718 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2720 /* Initialize once-only items */
2721 opr_queue_Init(&call->tq);
2722 opr_queue_Init(&call->rq);
2723 opr_queue_Init(&call->app.iovq);
2724 #ifdef RXDEBUG_PACKET
2725 call->rqc = call->tqc = call->iovqc = 0;
2726 #endif /* RXDEBUG_PACKET */
2727 /* Bind the call to its connection structure (prereq for reset) */
2729 rxi_ResetCall(call, 1);
2731 call->channel = channel;
2732 call->callNumber = &conn->callNumber[channel];
2733 call->rwind = conn->rwind[channel];
2734 call->twind = conn->twind[channel];
2735 /* Note that the next expected call number is retained (in
2736 * conn->callNumber[i]), even if we reallocate the call structure
2738 conn->call[channel] = call;
2739 /* if the channel's never been used (== 0), we should start at 1, otherwise
2740 * the call number is valid from the last time this channel was used */
2741 if (*call->callNumber == 0)
2742 *call->callNumber = 1;
2747 /* A call has been inactive long enough that so we can throw away
2748 * state, including the call structure, which is placed on the call
2751 * call->lock amd rx_refcnt_mutex are held upon entry.
2752 * haveCTLock is set when called from rxi_ReapConnections.
2754 * return 1 if the call is freed, 0 if not.
2757 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2759 int channel = call->channel;
2760 struct rx_connection *conn = call->conn;
2761 u_char state = call->state;
2764 * We are setting the state to RX_STATE_RESET to
2765 * ensure that no one else will attempt to use this
2766 * call once we drop the refcnt lock. We must drop
2767 * the refcnt lock before calling rxi_ResetCall
2768 * because it cannot be held across acquiring the
2769 * freepktQ lock. NewCall does the same.
2771 call->state = RX_STATE_RESET;
2772 MUTEX_EXIT(&rx_refcnt_mutex);
2773 rxi_ResetCall(call, 0);
2775 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2777 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2778 (*call->callNumber)++;
2780 if (call->conn->call[channel] == call)
2781 call->conn->call[channel] = 0;
2782 MUTEX_EXIT(&conn->conn_call_lock);
2785 * We couldn't obtain the conn_call_lock so we can't
2786 * disconnect the call from the connection. Set the
2787 * call state to dally so that the call can be reused.
2789 MUTEX_ENTER(&rx_refcnt_mutex);
2790 call->state = RX_STATE_DALLY;
2794 MUTEX_ENTER(&rx_freeCallQueue_lock);
2795 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2796 #ifdef RX_ENABLE_LOCKS
2797 /* A call may be free even though its transmit queue is still in use.
2798 * Since we search the call list from head to tail, put busy calls at
2799 * the head of the list, and idle calls at the tail.
2801 if (call->flags & RX_CALL_TQ_BUSY)
2802 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2804 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2805 #else /* RX_ENABLE_LOCKS */
2806 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2807 #endif /* RX_ENABLE_LOCKS */
2808 if (rx_stats_active)
2809 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2810 MUTEX_EXIT(&rx_freeCallQueue_lock);
2812 /* Destroy the connection if it was previously slated for
2813 * destruction, i.e. the Rx client code previously called
2814 * rx_DestroyConnection (client connections), or
2815 * rxi_ReapConnections called the same routine (server
2816 * connections). Only do this, however, if there are no
2817 * outstanding calls. Note that for fine grain locking, there appears
2818 * to be a deadlock in that rxi_FreeCall has a call locked and
2819 * DestroyConnectionNoLock locks each call in the conn. But note a
2820 * few lines up where we have removed this call from the conn.
2821 * If someone else destroys a connection, they either have no
2822 * call lock held or are going through this section of code.
2824 MUTEX_ENTER(&conn->conn_data_lock);
2825 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2826 rx_GetConnection(conn);
2827 MUTEX_EXIT(&conn->conn_data_lock);
2828 #ifdef RX_ENABLE_LOCKS
2830 rxi_DestroyConnectionNoLock(conn);
2832 rxi_DestroyConnection(conn);
2833 #else /* RX_ENABLE_LOCKS */
2834 rxi_DestroyConnection(conn);
2835 #endif /* RX_ENABLE_LOCKS */
2837 MUTEX_EXIT(&conn->conn_data_lock);
2839 MUTEX_ENTER(&rx_refcnt_mutex);
2843 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2844 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2847 rxi_Alloc(size_t size)
2851 if (rx_stats_active) {
2852 rx_atomic_add(&rxi_Allocsize, (int) size);
2853 rx_atomic_inc(&rxi_Alloccnt);
2857 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD_ENV)
2858 afs_osi_Alloc_NoSleep(size);
2863 osi_Panic("rxi_Alloc error");
2869 rxi_Free(void *addr, size_t size)
2874 if (rx_stats_active) {
2875 rx_atomic_sub(&rxi_Allocsize, (int) size);
2876 rx_atomic_dec(&rxi_Alloccnt);
2878 osi_Free(addr, size);
2882 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2884 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2885 struct rx_peer *next = NULL;
2889 MUTEX_ENTER(&rx_peerHashTable_lock);
2891 peer_ptr = &rx_peerHashTable[0];
2892 peer_end = &rx_peerHashTable[rx_hashTableSize];
2895 for ( ; peer_ptr < peer_end; peer_ptr++) {
2898 for ( ; peer; peer = next) {
2900 if (host == peer->host)
2905 hashIndex = PEER_HASH(host, port);
2906 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2907 if ((peer->host == host) && (peer->port == port))
2912 MUTEX_ENTER(&rx_peerHashTable_lock);
2917 MUTEX_EXIT(&rx_peerHashTable_lock);
2919 MUTEX_ENTER(&peer->peer_lock);
2920 /* We don't handle dropping below min, so don't */
2921 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2922 peer->ifMTU=MIN(mtu, peer->ifMTU);
2923 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2924 /* if we tweaked this down, need to tune our peer MTU too */
2925 peer->MTU = MIN(peer->MTU, peer->natMTU);
2926 /* if we discovered a sub-1500 mtu, degrade */
2927 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2928 peer->maxDgramPackets = 1;
2929 /* We no longer have valid peer packet information */
2930 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2931 peer->maxPacketSize = 0;
2932 MUTEX_EXIT(&peer->peer_lock);
2934 MUTEX_ENTER(&rx_peerHashTable_lock);
2936 if (host && !port) {
2938 /* pick up where we left off */
2942 MUTEX_EXIT(&rx_peerHashTable_lock);
2945 #ifdef AFS_RXERRQ_ENV
2947 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2949 int hashIndex = PEER_HASH(host, port);
2950 struct rx_peer *peer;
2952 MUTEX_ENTER(&rx_peerHashTable_lock);
2954 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2955 if (peer->host == host && peer->port == port) {
2961 MUTEX_EXIT(&rx_peerHashTable_lock);
2964 rx_atomic_inc(&peer->neterrs);
2965 MUTEX_ENTER(&peer->peer_lock);
2966 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2967 peer->last_err_type = err->ee_type;
2968 peer->last_err_code = err->ee_code;
2969 MUTEX_EXIT(&peer->peer_lock);
2971 MUTEX_ENTER(&rx_peerHashTable_lock);
2973 MUTEX_EXIT(&rx_peerHashTable_lock);
2978 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2980 # ifdef AFS_ADAPT_PMTU
2981 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2982 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2986 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2987 switch (err->ee_code) {
2988 case ICMP_NET_UNREACH:
2989 case ICMP_HOST_UNREACH:
2990 case ICMP_PORT_UNREACH:
2993 rxi_SetPeerDead(err, addr, port);
3000 rxi_TranslateICMP(int type, int code)
3003 case ICMP_DEST_UNREACH:
3005 case ICMP_NET_UNREACH:
3006 return "Destination Net Unreachable";
3007 case ICMP_HOST_UNREACH:
3008 return "Destination Host Unreachable";
3009 case ICMP_PROT_UNREACH:
3010 return "Destination Protocol Unreachable";
3011 case ICMP_PORT_UNREACH:
3012 return "Destination Port Unreachable";
3014 return "Destination Net Prohibited";
3016 return "Destination Host Prohibited";
3022 #endif /* AFS_RXERRQ_ENV */
3025 * Get the last network error for a connection
3027 * A "network error" here means an error retrieved from ICMP, or some other
3028 * mechanism outside of Rx that informs us of errors in network reachability.
3030 * If a peer associated with the given Rx connection has received a network
3031 * error recently, this function allows the caller to know what error
3032 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3033 * can cause calls to that peer to be quickly aborted. So, this function can
3034 * help see why a call was aborted due to network errors.
3036 * If we have received traffic from a peer since the last network error, we
3037 * treat that peer as if we had not received an network error for it.
3039 * @param[in] conn The Rx connection to examine
3040 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3041 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3042 * @param[out] err_type The type of the last error
3043 * @param[out] err_code The code of the last error
3044 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3046 * @return If we have an error
3047 * @retval -1 No error to get; 'out' params are undefined
3048 * @retval 0 We have an error; 'out' params contain the last error
3051 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3052 int *err_code, const char **msg)
3054 #ifdef AFS_RXERRQ_ENV
3055 struct rx_peer *peer = conn->peer;
3056 if (rx_atomic_read(&peer->neterrs)) {
3057 MUTEX_ENTER(&peer->peer_lock);
3058 *err_origin = peer->last_err_origin;
3059 *err_type = peer->last_err_type;
3060 *err_code = peer->last_err_code;
3061 MUTEX_EXIT(&peer->peer_lock);
3064 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3065 *msg = rxi_TranslateICMP(*err_type, *err_code);
3074 /* Find the peer process represented by the supplied (host,port)
3075 * combination. If there is no appropriate active peer structure, a
3076 * new one will be allocated and initialized
3079 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3083 hashIndex = PEER_HASH(host, port);
3084 MUTEX_ENTER(&rx_peerHashTable_lock);
3085 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3086 if ((pp->host == host) && (pp->port == port))
3091 pp = rxi_AllocPeer(); /* This bzero's *pp */
3092 pp->host = host; /* set here or in InitPeerParams is zero */
3094 #ifdef AFS_RXERRQ_ENV
3095 rx_atomic_set(&pp->neterrs, 0);
3097 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3098 opr_queue_Init(&pp->rpcStats);
3099 pp->next = rx_peerHashTable[hashIndex];
3100 rx_peerHashTable[hashIndex] = pp;
3101 rxi_InitPeerParams(pp);
3102 if (rx_stats_active)
3103 rx_atomic_inc(&rx_stats.nPeerStructs);
3109 MUTEX_EXIT(&rx_peerHashTable_lock);
3114 /* Find the connection at (host, port) started at epoch, and with the
3115 * given connection id. Creates the server connection if necessary.
3116 * The type specifies whether a client connection or a server
3117 * connection is desired. In both cases, (host, port) specify the
3118 * peer's (host, pair) pair. Client connections are not made
3119 * automatically by this routine. The parameter socket gives the
3120 * socket descriptor on which the packet was received. This is used,
3121 * in the case of server connections, to check that *new* connections
3122 * come via a valid (port, serviceId). Finally, the securityIndex
3123 * parameter must match the existing index for the connection. If a
3124 * server connection is created, it will be created using the supplied
3125 * index, if the index is valid for this service */
3126 static struct rx_connection *
3127 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3128 u_short port, u_short serviceId, afs_uint32 cid,
3129 afs_uint32 epoch, int type, u_int securityIndex,
3130 int *unknownService)
3132 int hashindex, flag, i;
3134 struct rx_connection *conn;
3135 *unknownService = 0;
3136 hashindex = CONN_HASH(host, port, cid, epoch, type);
3137 MUTEX_ENTER(&rx_connHashTable_lock);
3138 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3139 rx_connHashTable[hashindex],
3142 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3143 && (epoch == conn->epoch)) {
3144 struct rx_peer *pp = conn->peer;
3145 if (securityIndex != conn->securityIndex) {
3146 /* this isn't supposed to happen, but someone could forge a packet
3147 * like this, and there seems to be some CM bug that makes this
3148 * happen from time to time -- in which case, the fileserver
3150 MUTEX_EXIT(&rx_connHashTable_lock);
3151 return (struct rx_connection *)0;
3153 if (pp->host == host && pp->port == port)
3155 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3157 /* So what happens when it's a callback connection? */
3158 if ( /*type == RX_CLIENT_CONNECTION && */
3159 (conn->epoch & 0x80000000))
3163 /* the connection rxLastConn that was used the last time is not the
3164 ** one we are looking for now. Hence, start searching in the hash */
3166 conn = rx_connHashTable[hashindex];
3171 struct rx_service *service;
3172 if (type == RX_CLIENT_CONNECTION) {
3173 MUTEX_EXIT(&rx_connHashTable_lock);
3174 return (struct rx_connection *)0;
3176 service = rxi_FindService(socket, serviceId);
3177 if (!service || (securityIndex >= service->nSecurityObjects)
3178 || (service->securityObjects[securityIndex] == 0)) {
3179 MUTEX_EXIT(&rx_connHashTable_lock);
3180 *unknownService = 1;
3181 return (struct rx_connection *)0;
3183 conn = rxi_AllocConnection(); /* This bzero's the connection */
3184 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3185 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3186 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3187 conn->next = rx_connHashTable[hashindex];
3188 rx_connHashTable[hashindex] = conn;
3189 conn->peer = rxi_FindPeer(host, port, 1);
3190 conn->type = RX_SERVER_CONNECTION;
3191 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3192 conn->epoch = epoch;
3193 conn->cid = cid & RX_CIDMASK;
3194 conn->ackRate = RX_FAST_ACK_RATE;
3195 conn->service = service;
3196 conn->serviceId = serviceId;
3197 conn->securityIndex = securityIndex;
3198 conn->securityObject = service->securityObjects[securityIndex];
3199 conn->nSpecific = 0;
3200 conn->specific = NULL;
3201 rx_SetConnDeadTime(conn, service->connDeadTime);
3202 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3203 for (i = 0; i < RX_MAXCALLS; i++) {
3204 conn->twind[i] = rx_initSendWindow;
3205 conn->rwind[i] = rx_initReceiveWindow;
3207 /* Notify security object of the new connection */
3208 code = RXS_NewConnection(conn->securityObject, conn);
3209 /* XXXX Connection timeout? */
3210 if (service->newConnProc)
3211 (*service->newConnProc) (conn);
3212 if (rx_stats_active)
3213 rx_atomic_inc(&rx_stats.nServerConns);
3216 rx_GetConnection(conn);
3218 rxLastConn = conn; /* store this connection as the last conn used */
3219 MUTEX_EXIT(&rx_connHashTable_lock);
3221 rxi_ConnectionError(conn, code);
3227 * Abort the call if the server is over the busy threshold. This
3228 * can be used without requiring a call structure be initialised,
3229 * or connected to a particular channel
3232 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3233 struct rx_packet *np)
3237 if ((rx_BusyThreshold > 0) &&
3238 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3239 MUTEX_ENTER(&conn->conn_data_lock);
3240 serial = ++conn->serial;
3241 MUTEX_EXIT(&conn->conn_data_lock);
3242 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3243 serial, rx_BusyError, np, 0);
3244 if (rx_stats_active)
3245 rx_atomic_inc(&rx_stats.nBusies);
3252 static_inline struct rx_call *
3253 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3256 struct rx_call *call;
3258 channel = np->header.cid & RX_CHANNELMASK;
3259 MUTEX_ENTER(&conn->conn_call_lock);
3260 call = conn->call[channel];
3261 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3262 conn->lastBusy[channel] = clock_Sec();
3264 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3265 MUTEX_EXIT(&conn->conn_call_lock);
3266 if (rx_stats_active)
3267 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3271 MUTEX_ENTER(&call->lock);
3272 MUTEX_EXIT(&conn->conn_call_lock);
3274 if ((call->state == RX_STATE_DALLY)
3275 && np->header.type == RX_PACKET_TYPE_ACK) {
3276 if (rx_stats_active)
3277 rx_atomic_inc(&rx_stats.ignorePacketDally);
3278 MUTEX_EXIT(&call->lock);
3285 static_inline struct rx_call *
3286 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3287 struct rx_connection *conn)
3290 struct rx_call *call;
3292 channel = np->header.cid & RX_CHANNELMASK;
3293 MUTEX_ENTER(&conn->conn_call_lock);
3294 call = conn->call[channel];
3297 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3298 MUTEX_EXIT(&conn->conn_call_lock);
3302 call = rxi_NewCall(conn, channel); /* returns locked call */
3303 *call->callNumber = np->header.callNumber;
3304 MUTEX_EXIT(&conn->conn_call_lock);
3306 call->state = RX_STATE_PRECALL;
3307 clock_GetTime(&call->queueTime);
3308 call->app.bytesSent = 0;
3309 call->app.bytesRcvd = 0;
3310 rxi_KeepAliveOn(call);
3315 if (np->header.callNumber == conn->callNumber[channel]) {
3316 MUTEX_ENTER(&call->lock);
3317 MUTEX_EXIT(&conn->conn_call_lock);
3321 if (np->header.callNumber < conn->callNumber[channel]) {
3322 MUTEX_EXIT(&conn->conn_call_lock);
3323 if (rx_stats_active)
3324 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3328 MUTEX_ENTER(&call->lock);
3329 MUTEX_EXIT(&conn->conn_call_lock);
3331 /* Wait until the transmit queue is idle before deciding
3332 * whether to reset the current call. Chances are that the
3333 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3336 #ifdef RX_ENABLE_LOCKS
3337 if (call->state == RX_STATE_ACTIVE && !call->error) {
3338 rxi_WaitforTQBusy(call);
3339 /* If we entered error state while waiting,
3340 * must call rxi_CallError to permit rxi_ResetCall
3341 * to processed when the tqWaiter count hits zero.
3344 rxi_CallError(call, call->error);
3345 MUTEX_EXIT(&call->lock);
3349 #endif /* RX_ENABLE_LOCKS */
3350 /* If the new call cannot be taken right now send a busy and set
3351 * the error condition in this call, so that it terminates as
3352 * quickly as possible */
3353 if (call->state == RX_STATE_ACTIVE) {
3354 rxi_CallError(call, RX_CALL_DEAD);
3355 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3357 MUTEX_EXIT(&call->lock);
3361 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3362 MUTEX_EXIT(&call->lock);
3366 rxi_ResetCall(call, 0);
3367 /* The conn_call_lock is not held but no one else should be
3368 * using this call channel while we are processing this incoming
3369 * packet. This assignment should be safe.
3371 *call->callNumber = np->header.callNumber;
3372 call->state = RX_STATE_PRECALL;
3373 clock_GetTime(&call->queueTime);
3374 call->app.bytesSent = 0;
3375 call->app.bytesRcvd = 0;
3376 rxi_KeepAliveOn(call);
3382 /* There are two packet tracing routines available for testing and monitoring
3383 * Rx. One is called just after every packet is received and the other is
3384 * called just before every packet is sent. Received packets, have had their
3385 * headers decoded, and packets to be sent have not yet had their headers
3386 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3387 * containing the network address. Both can be modified. The return value, if
3388 * non-zero, indicates that the packet should be dropped. */
3390 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3391 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3393 /* A packet has been received off the interface. Np is the packet, socket is
3394 * the socket number it was received from (useful in determining which service
3395 * this packet corresponds to), and (host, port) reflect the host,port of the
3396 * sender. This call returns the packet to the caller if it is finished with
3397 * it, rather than de-allocating it, just as a small performance hack */
3400 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3401 afs_uint32 host, u_short port, int *tnop,
3402 struct rx_call **newcallp)
3404 struct rx_call *call;
3405 struct rx_connection *conn;
3407 int unknownService = 0;
3411 struct rx_packet *tnp;
3414 /* We don't print out the packet until now because (1) the time may not be
3415 * accurate enough until now in the lwp implementation (rx_Listener only gets
3416 * the time after the packet is read) and (2) from a protocol point of view,
3417 * this is the first time the packet has been seen */
3418 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3419 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3420 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %p\n",
3421 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3422 np->header.epoch, np->header.cid, np->header.callNumber,
3423 np->header.seq, np->header.flags, np));
3426 /* Account for connectionless packets */
3427 if (rx_stats_active &&
3428 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3429 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3430 struct rx_peer *peer;
3432 /* Try to look up the peer structure, but don't create one */
3433 peer = rxi_FindPeer(host, port, 0);
3435 /* Since this may not be associated with a connection, it may have
3436 * no refCount, meaning we could race with ReapConnections
3439 if (peer && (peer->refCount > 0)) {
3440 #ifdef AFS_RXERRQ_ENV
3441 if (rx_atomic_read(&peer->neterrs)) {
3442 rx_atomic_set(&peer->neterrs, 0);
3445 MUTEX_ENTER(&peer->peer_lock);
3446 peer->bytesReceived += np->length;
3447 MUTEX_EXIT(&peer->peer_lock);
3451 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3452 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3455 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3456 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3459 /* If an input tracer function is defined, call it with the packet and
3460 * network address. Note this function may modify its arguments. */
3461 if (rx_justReceived) {
3462 struct sockaddr_in addr;
3464 addr.sin_family = AF_INET;
3465 addr.sin_port = port;
3466 addr.sin_addr.s_addr = host;
3467 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3468 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3469 addr.sin_len = sizeof(addr);
3471 drop = (*rx_justReceived) (np, &addr);
3472 /* drop packet if return value is non-zero */
3475 port = addr.sin_port; /* in case fcn changed addr */
3476 host = addr.sin_addr.s_addr;
3480 /* If packet was not sent by the client, then *we* must be the client */
3481 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3482 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3484 /* Find the connection (or fabricate one, if we're the server & if
3485 * necessary) associated with this packet */
3487 rxi_FindConnection(socket, host, port, np->header.serviceId,
3488 np->header.cid, np->header.epoch, type,
3489 np->header.securityIndex, &unknownService);
3491 /* To avoid having 2 connections just abort at each other,
3492 don't abort an abort. */
3494 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3495 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3500 #ifdef AFS_RXERRQ_ENV
3501 if (rx_atomic_read(&conn->peer->neterrs)) {
3502 rx_atomic_set(&conn->peer->neterrs, 0);
3506 /* If we're doing statistics, then account for the incoming packet */
3507 if (rx_stats_active) {
3508 MUTEX_ENTER(&conn->peer->peer_lock);
3509 conn->peer->bytesReceived += np->length;
3510 MUTEX_EXIT(&conn->peer->peer_lock);
3513 /* If the connection is in an error state, send an abort packet and ignore
3514 * the incoming packet */
3516 /* Don't respond to an abort packet--we don't want loops! */
3517 MUTEX_ENTER(&conn->conn_data_lock);
3518 if (np->header.type != RX_PACKET_TYPE_ABORT)
3519 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3520 putConnection(conn);
3521 MUTEX_EXIT(&conn->conn_data_lock);
3525 /* Check for connection-only requests (i.e. not call specific). */
3526 if (np->header.callNumber == 0) {
3527 switch (np->header.type) {
3528 case RX_PACKET_TYPE_ABORT: {
3529 /* What if the supplied error is zero? */
3530 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3531 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3532 rxi_ConnectionError(conn, errcode);
3533 putConnection(conn);
3536 case RX_PACKET_TYPE_CHALLENGE:
3537 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3538 putConnection(conn);
3540 case RX_PACKET_TYPE_RESPONSE:
3541 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3542 putConnection(conn);
3544 case RX_PACKET_TYPE_PARAMS:
3545 case RX_PACKET_TYPE_PARAMS + 1:
3546 case RX_PACKET_TYPE_PARAMS + 2:
3547 /* ignore these packet types for now */
3548 putConnection(conn);
3552 /* Should not reach here, unless the peer is broken: send an
3554 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3555 MUTEX_ENTER(&conn->conn_data_lock);
3556 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3557 putConnection(conn);
3558 MUTEX_EXIT(&conn->conn_data_lock);
3563 if (type == RX_SERVER_CONNECTION)
3564 call = rxi_ReceiveServerCall(socket, np, conn);
3566 call = rxi_ReceiveClientCall(np, conn);
3569 putConnection(conn);
3573 MUTEX_ASSERT(&call->lock);
3574 /* Set remote user defined status from packet */
3575 call->remoteStatus = np->header.userStatus;
3577 /* Now do packet type-specific processing */
3578 switch (np->header.type) {
3579 case RX_PACKET_TYPE_DATA:
3580 /* If we're a client, and receiving a response, then all the packets
3581 * we transmitted packets are implicitly acknowledged. */
3582 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3583 rxi_AckAllInTransmitQueue(call);
3585 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3588 case RX_PACKET_TYPE_ACK:
3589 /* Respond immediately to ack packets requesting acknowledgement
3591 if (np->header.flags & RX_REQUEST_ACK) {
3593 (void)rxi_SendCallAbort(call, 0, 1, 0);
3595 (void)rxi_SendAck(call, 0, np->header.serial,
3596 RX_ACK_PING_RESPONSE, 1);
3598 np = rxi_ReceiveAckPacket(call, np, 1);
3600 case RX_PACKET_TYPE_ABORT: {
3601 /* An abort packet: reset the call, passing the error up to the user. */
3602 /* What if error is zero? */
3603 /* What if the error is -1? the application will treat it as a timeout. */
3604 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3605 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3606 rxi_CallError(call, errdata);
3607 MUTEX_EXIT(&call->lock);
3608 putConnection(conn);
3609 return np; /* xmitting; drop packet */
3611 case RX_PACKET_TYPE_BUSY:
3612 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3613 * so we don't think the endpoint is completely dead, but otherwise
3614 * just act as if we never saw anything. If all we get are BUSY packets
3615 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3616 * connection is configured with idle/hard timeouts. */
3619 case RX_PACKET_TYPE_ACKALL:
3620 /* All packets acknowledged, so we can drop all packets previously
3621 * readied for sending */
3622 rxi_AckAllInTransmitQueue(call);
3625 /* Should not reach here, unless the peer is broken: send an abort
3627 rxi_CallError(call, RX_PROTOCOL_ERROR);
3628 np = rxi_SendCallAbort(call, np, 1, 0);
3631 /* Note when this last legitimate packet was received, for keep-alive
3632 * processing. Note, we delay getting the time until now in the hope that
3633 * the packet will be delivered to the user before any get time is required
3634 * (if not, then the time won't actually be re-evaluated here). */
3635 call->lastReceiveTime = clock_Sec();
3636 MUTEX_EXIT(&call->lock);
3637 putConnection(conn);
3641 /* return true if this is an "interesting" connection from the point of view
3642 of someone trying to debug the system */
3644 rxi_IsConnInteresting(struct rx_connection *aconn)
3647 struct rx_call *tcall;
3649 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3652 for (i = 0; i < RX_MAXCALLS; i++) {
3653 tcall = aconn->call[i];
3655 if ((tcall->state == RX_STATE_PRECALL)
3656 || (tcall->state == RX_STATE_ACTIVE))
3658 if ((tcall->app.mode == RX_MODE_SENDING)
3659 || (tcall->app.mode == RX_MODE_RECEIVING))
3667 /* if this is one of the last few packets AND it wouldn't be used by the
3668 receiving call to immediately satisfy a read request, then drop it on
3669 the floor, since accepting it might prevent a lock-holding thread from
3670 making progress in its reading. If a call has been cleared while in
3671 the precall state then ignore all subsequent packets until the call
3672 is assigned to a thread. */
3675 TooLow(struct rx_packet *ap, struct rx_call *acall)
3679 MUTEX_ENTER(&rx_quota_mutex);
3680 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3681 && (acall->state == RX_STATE_PRECALL))
3682 || ((rx_nFreePackets < rxi_dataQuota + 2)
3683 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3684 && (acall->flags & RX_CALL_READER_WAIT)))) {
3687 MUTEX_EXIT(&rx_quota_mutex);
3693 * Clear the attach wait flag on a connection and proceed.
3695 * Any processing waiting for a connection to be attached should be
3696 * unblocked. We clear the flag and do any other needed tasks.
3699 * the conn to unmark waiting for attach
3701 * @pre conn's conn_data_lock must be locked before calling this function
3705 rxi_ConnClearAttachWait(struct rx_connection *conn)
3707 /* Indicate that rxi_CheckReachEvent is no longer running by
3708 * clearing the flag. Must be atomic under conn_data_lock to
3709 * avoid a new call slipping by: rxi_CheckConnReach holds
3710 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3712 conn->flags &= ~RX_CONN_ATTACHWAIT;
3713 if (conn->flags & RX_CONN_NAT_PING) {
3714 conn->flags &= ~RX_CONN_NAT_PING;
3715 rxi_ScheduleNatKeepAliveEvent(conn);
3720 * Event handler function for connection-specific events for checking
3721 * reachability. Also called directly from main code with |event| == NULL
3722 * in order to trigger the initial reachability check.
3724 * When |event| == NULL, must be called with the connection data lock held,
3725 * but returns with the lock unlocked.
3728 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3730 struct rx_connection *conn = arg1;
3731 struct rx_call *acall = arg2;
3732 struct rx_call *call = acall;
3733 struct clock when, now;
3737 MUTEX_ENTER(&conn->conn_data_lock);
3739 MUTEX_ASSERT(&conn->conn_data_lock);
3741 if (event != NULL && event == conn->checkReachEvent)
3742 rxevent_Put(&conn->checkReachEvent);
3743 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3744 MUTEX_EXIT(&conn->conn_data_lock);
3748 MUTEX_ENTER(&conn->conn_call_lock);
3749 MUTEX_ENTER(&conn->conn_data_lock);
3750 for (i = 0; i < RX_MAXCALLS; i++) {
3751 struct rx_call *tc = conn->call[i];
3752 if (tc && tc->state == RX_STATE_PRECALL) {
3758 rxi_ConnClearAttachWait(conn);
3759 MUTEX_EXIT(&conn->conn_data_lock);
3760 MUTEX_EXIT(&conn->conn_call_lock);
3765 MUTEX_ENTER(&call->lock);
3766 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3768 MUTEX_EXIT(&call->lock);
3770 clock_GetTime(&now);
3772 when.sec += RX_CHECKREACH_TIMEOUT;
3773 MUTEX_ENTER(&conn->conn_data_lock);
3774 if (!conn->checkReachEvent) {
3775 rx_GetConnection(conn);
3776 conn->checkReachEvent = rxevent_Post(&when, &now,
3777 rxi_CheckReachEvent, conn,
3780 MUTEX_EXIT(&conn->conn_data_lock);
3783 /* If fired as an event handler, drop our refcount on the connection. */
3785 putConnection(conn);
3789 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3791 struct rx_service *service = conn->service;
3792 struct rx_peer *peer = conn->peer;
3793 afs_uint32 now, lastReach;
3795 if (service->checkReach == 0)
3799 MUTEX_ENTER(&peer->peer_lock);
3800 lastReach = peer->lastReachTime;
3801 MUTEX_EXIT(&peer->peer_lock);
3802 if (now - lastReach < RX_CHECKREACH_TTL)
3805 MUTEX_ENTER(&conn->conn_data_lock);
3806 if (conn->flags & RX_CONN_ATTACHWAIT) {
3807 MUTEX_EXIT(&conn->conn_data_lock);
3810 conn->flags |= RX_CONN_ATTACHWAIT;
3811 if (conn->checkReachEvent == NULL) {
3812 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3813 rxi_CheckReachEvent(NULL, conn, call, 0);
3815 MUTEX_EXIT(&conn->conn_data_lock);
3821 /* try to attach call, if authentication is complete */
3823 TryAttach(struct rx_call *acall, osi_socket socket,
3824 int *tnop, struct rx_call **newcallp,
3825 int reachOverride, int istack)
3827 struct rx_connection *conn = acall->conn;
3829 if (conn->type == RX_SERVER_CONNECTION
3830 && acall->state == RX_STATE_PRECALL) {
3831 /* Don't attach until we have any req'd. authentication. */
3832 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3833 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3834 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3835 /* Note: this does not necessarily succeed; there
3836 * may not any proc available
3840 code = rxi_ChallengeOn(acall->conn);
3843 * Ideally we would rxi_ConnectionError here, but doing that is
3844 * difficult, because some callers may have locked 'call',
3845 * _and_ another call on the same conn. So we cannot
3846 * rxi_ConnectionError, since that needs to lock every call on
3847 * the conn. But we can at least abort the call we have.
3849 rxi_CallError(acall, code);
3850 rxi_SendCallAbort(acall, NULL, istack, 0);
3856 /* A data packet has been received off the interface. This packet is
3857 * appropriate to the call (the call is in the right state, etc.). This
3858 * routine can return a packet to the caller, for re-use */
3860 static struct rx_packet *
3861 rxi_ReceiveDataPacket(struct rx_call *call,
3862 struct rx_packet *np, int istack,
3863 osi_socket socket, afs_uint32 host, u_short port,
3864 int *tnop, struct rx_call **newcallp)
3866 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3871 afs_uint32 serial=0, flags=0;
3873 struct rx_packet *tnp;
3874 if (rx_stats_active)
3875 rx_atomic_inc(&rx_stats.dataPacketsRead);
3878 /* If there are no packet buffers, drop this new packet, unless we can find
3879 * packet buffers from inactive calls */
3881 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3882 MUTEX_ENTER(&rx_freePktQ_lock);
3883 rxi_NeedMorePackets = TRUE;
3884 MUTEX_EXIT(&rx_freePktQ_lock);
3885 if (rx_stats_active)
3886 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3887 rxi_calltrace(RX_TRACE_DROP, call);
3888 dpf(("packet %p dropped on receipt - quota problems\n", np));
3889 /* We used to clear the receive queue here, in an attempt to free
3890 * packets. However this is unsafe if the queue has received a
3891 * soft ACK for the final packet */
3892 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3898 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3899 * packet is one of several packets transmitted as a single
3900 * datagram. Do not send any soft or hard acks until all packets
3901 * in a jumbogram have been processed. Send negative acks right away.
3903 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3904 /* tnp is non-null when there are more packets in the
3905 * current jumbo gram */
3912 seq = np->header.seq;
3913 serial = np->header.serial;
3914 flags = np->header.flags;
3916 /* If the call is in an error state, send an abort message */
3918 return rxi_SendCallAbort(call, np, istack, 0);
3920 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3921 * AFS 3.5 jumbogram. */
3922 if (flags & RX_JUMBO_PACKET) {
3923 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3928 if (np->header.spare != 0) {
3929 MUTEX_ENTER(&call->conn->conn_data_lock);
3930 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3931 MUTEX_EXIT(&call->conn->conn_data_lock);
3934 /* The usual case is that this is the expected next packet */
3935 if (seq == call->rnext) {
3937 /* Check to make sure it is not a duplicate of one already queued */
3938 if (!opr_queue_IsEmpty(&call->rq)
3939 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3940 if (rx_stats_active)
3941 rx_atomic_inc(&rx_stats.dupPacketsRead);
3942 dpf(("packet %p dropped on receipt - duplicate\n", np));
3943 rxi_CancelDelayedAckEvent(call);
3944 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3950 /* It's the next packet. Stick it on the receive queue
3951 * for this call. Set newPackets to make sure we wake
3952 * the reader once all packets have been processed */
3953 #ifdef RX_TRACK_PACKETS
3954 np->flags |= RX_PKTFLAG_RQ;
3956 opr_queue_Prepend(&call->rq, &np->entry);
3957 #ifdef RXDEBUG_PACKET
3959 #endif /* RXDEBUG_PACKET */
3961 np = NULL; /* We can't use this anymore */
3964 /* If an ack is requested then set a flag to make sure we
3965 * send an acknowledgement for this packet */
3966 if (flags & RX_REQUEST_ACK) {
3967 ackNeeded = RX_ACK_REQUESTED;
3970 /* Keep track of whether we have received the last packet */
3971 if (flags & RX_LAST_PACKET) {
3972 call->flags |= RX_CALL_HAVE_LAST;
3976 /* Check whether we have all of the packets for this call */
3977 if (call->flags & RX_CALL_HAVE_LAST) {
3978 afs_uint32 tseq; /* temporary sequence number */
3979 struct opr_queue *cursor;
3981 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3982 struct rx_packet *tp;
3984 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3985 if (tseq != tp->header.seq)
3987 if (tp->header.flags & RX_LAST_PACKET) {
3988 call->flags |= RX_CALL_RECEIVE_DONE;
3995 /* Provide asynchronous notification for those who want it
3996 * (e.g. multi rx) */
3997 if (call->arrivalProc) {
3998 (*call->arrivalProc) (call, call->arrivalProcHandle,
3999 call->arrivalProcArg);
4000 call->arrivalProc = NULL;
4003 /* Update last packet received */
4006 /* If there is no server process serving this call, grab
4007 * one, if available. We only need to do this once. If a
4008 * server thread is available, this thread becomes a server
4009 * thread and the server thread becomes a listener thread. */
4011 TryAttach(call, socket, tnop, newcallp, 0, istack);
4014 /* This is not the expected next packet. */
4016 /* Determine whether this is a new or old packet, and if it's
4017 * a new one, whether it fits into the current receive window.
4018 * Also figure out whether the packet was delivered in sequence.
4019 * We use the prev variable to determine whether the new packet
4020 * is the successor of its immediate predecessor in the
4021 * receive queue, and the missing flag to determine whether
4022 * any of this packets predecessors are missing. */
4024 afs_uint32 prev; /* "Previous packet" sequence number */
4025 struct opr_queue *cursor;
4026 int missing; /* Are any predecessors missing? */
4028 /* If the new packet's sequence number has been sent to the
4029 * application already, then this is a duplicate */
4030 if (seq < call->rnext) {
4031 if (rx_stats_active)
4032 rx_atomic_inc(&rx_stats.dupPacketsRead);
4033 rxi_CancelDelayedAckEvent(call);
4034 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4040 /* If the sequence number is greater than what can be
4041 * accomodated by the current window, then send a negative
4042 * acknowledge and drop the packet */
4043 if ((call->rnext + call->rwind) <= seq) {
4044 rxi_CancelDelayedAckEvent(call);
4045 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4052 /* Look for the packet in the queue of old received packets */
4053 prev = call->rnext - 1;
4055 for (opr_queue_Scan(&call->rq, cursor)) {
4056 struct rx_packet *tp
4057 = opr_queue_Entry(cursor, struct rx_packet, entry);
4059 /*Check for duplicate packet */
4060 if (seq == tp->header.seq) {
4061 if (rx_stats_active)
4062 rx_atomic_inc(&rx_stats.dupPacketsRead);
4063 rxi_CancelDelayedAckEvent(call);
4064 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4070 /* If we find a higher sequence packet, break out and
4071 * insert the new packet here. */
4072 if (seq < tp->header.seq)
4074 /* Check for missing packet */
4075 if (tp->header.seq != prev + 1) {
4079 prev = tp->header.seq;
4082 /* Keep track of whether we have received the last packet. */
4083 if (flags & RX_LAST_PACKET) {
4084 call->flags |= RX_CALL_HAVE_LAST;
4087 /* It's within the window: add it to the the receive queue.
4088 * tp is left by the previous loop either pointing at the
4089 * packet before which to insert the new packet, or at the
4090 * queue head if the queue is empty or the packet should be
4092 #ifdef RX_TRACK_PACKETS
4093 np->flags |= RX_PKTFLAG_RQ;
4095 #ifdef RXDEBUG_PACKET
4097 #endif /* RXDEBUG_PACKET */
4098 opr_queue_InsertBefore(cursor, &np->entry);
4102 /* Check whether we have all of the packets for this call */
4103 if ((call->flags & RX_CALL_HAVE_LAST)
4104 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4105 afs_uint32 tseq; /* temporary sequence number */
4108 for (opr_queue_Scan(&call->rq, cursor)) {
4109 struct rx_packet *tp
4110 = opr_queue_Entry(cursor, struct rx_packet, entry);
4111 if (tseq != tp->header.seq)
4113 if (tp->header.flags & RX_LAST_PACKET) {
4114 call->flags |= RX_CALL_RECEIVE_DONE;
4121 /* We need to send an ack of the packet is out of sequence,
4122 * or if an ack was requested by the peer. */
4123 if (seq != prev + 1 || missing) {
4124 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4125 } else if (flags & RX_REQUEST_ACK) {
4126 ackNeeded = RX_ACK_REQUESTED;
4129 /* Acknowledge the last packet for each call */
4130 if (flags & RX_LAST_PACKET) {
4141 * If the receiver is waiting for an iovec, fill the iovec
4142 * using the data from the receive queue */
4143 if (call->flags & RX_CALL_IOVEC_WAIT) {
4144 didHardAck = rxi_FillReadVec(call, serial);
4145 /* the call may have been aborted */
4154 /* Wakeup the reader if any */
4155 if ((call->flags & RX_CALL_READER_WAIT)
4156 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4157 || (call->iovNext >= call->iovMax)
4158 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4159 call->flags &= ~RX_CALL_READER_WAIT;
4160 #ifdef RX_ENABLE_LOCKS
4161 CV_BROADCAST(&call->cv_rq);
4163 osi_rxWakeup(&call->rq);
4169 * Send an ack when requested by the peer, or once every
4170 * rxi_SoftAckRate packets until the last packet has been
4171 * received. Always send a soft ack for the last packet in
4172 * the server's reply. */
4174 rxi_CancelDelayedAckEvent(call);
4175 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4176 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4177 rxi_CancelDelayedAckEvent(call);
4178 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4179 } else if (call->nSoftAcks) {
4180 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4181 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4183 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4184 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4185 rxi_CancelDelayedAckEvent(call);
4192 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall,
4195 struct rx_peer *peer = conn->peer;
4197 MUTEX_ENTER(&peer->peer_lock);
4198 peer->lastReachTime = clock_Sec();
4199 MUTEX_EXIT(&peer->peer_lock);
4201 MUTEX_ENTER(&conn->conn_data_lock);
4202 if (conn->flags & RX_CONN_ATTACHWAIT) {
4205 rxi_ConnClearAttachWait(conn);
4206 MUTEX_EXIT(&conn->conn_data_lock);
4208 for (i = 0; i < RX_MAXCALLS; i++) {
4209 struct rx_call *call = conn->call[i];
4212 MUTEX_ENTER(&call->lock);
4213 /* tnop can be null if newcallp is null */
4214 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1, istack);
4216 MUTEX_EXIT(&call->lock);
4220 MUTEX_EXIT(&conn->conn_data_lock);
4223 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4225 rx_ack_reason(int reason)
4228 case RX_ACK_REQUESTED:
4230 case RX_ACK_DUPLICATE:
4232 case RX_ACK_OUT_OF_SEQUENCE:
4234 case RX_ACK_EXCEEDS_WINDOW:
4236 case RX_ACK_NOSPACE:
4240 case RX_ACK_PING_RESPONSE:
4253 ack_is_valid(struct rx_call *call, afs_uint32 first, afs_uint32 prev)
4255 if (first < call->tfirst) {
4257 * The peer indicated that the window went backwards. That's not
4258 * allowed; the window can only move forwards.
4263 if (first == call->tfirst && prev < call->tprev) {
4265 * The peer said the last DATA packet it received was seq X, but it
4266 * already told us before that it had received data after X. This is
4267 * probably just an out-of-order ACK, and so we can ignore it.
4269 if (prev >= call->tfirst + call->twind) {
4271 * Some peers (OpenAFS libafs before 1.6.23) mistakenly set the
4272 * previousPacket field to a serial number, not a sequence number.
4273 * The sequence number the peer told us about is further than our
4274 * transmit window, so it cannot possibly be correct; it's probably
4275 * actually a serial number. Don't ignore packets based on this;
4276 * the previousPacket information is not accurate.
4284 /* Otherwise, the ack looks valid. */
4288 /* The real smarts of the whole thing. */
4289 static struct rx_packet *
4290 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4293 struct rx_ackPacket *ap;
4295 struct rx_packet *tp;
4296 struct rx_connection *conn = call->conn;
4297 struct rx_peer *peer = conn->peer;
4298 struct opr_queue *cursor;
4299 struct clock now; /* Current time, for RTT calculations */
4307 int newAckCount = 0;
4308 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4309 int pktsize = 0; /* Set if we need to update the peer mtu */
4310 int conn_data_locked = 0;
4312 if (rx_stats_active)
4313 rx_atomic_inc(&rx_stats.ackPacketsRead);
4314 ap = (struct rx_ackPacket *)rx_DataOf(np);
4315 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4317 return np; /* truncated ack packet */
4319 /* depends on ack packet struct */
4320 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4321 first = ntohl(ap->firstPacket);
4322 prev = ntohl(ap->previousPacket);
4323 serial = ntohl(ap->serial);
4325 if (!ack_is_valid(call, first, prev)) {
4331 if (np->header.flags & RX_SLOW_START_OK) {
4332 call->flags |= RX_CALL_SLOW_START_OK;
4335 if (ap->reason == RX_ACK_PING_RESPONSE)
4336 rxi_UpdatePeerReach(conn, call, istack);
4338 if (conn->lastPacketSizeSeq) {
4339 MUTEX_ENTER(&conn->conn_data_lock);
4340 conn_data_locked = 1;
4341 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4342 pktsize = conn->lastPacketSize;
4343 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4346 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4347 if (!conn_data_locked) {
4348 MUTEX_ENTER(&conn->conn_data_lock);
4349 conn_data_locked = 1;
4351 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4352 /* process mtu ping ack */
4353 pktsize = conn->lastPingSize;
4354 conn->lastPingSizeSer = conn->lastPingSize = 0;
4358 if (conn_data_locked) {
4359 MUTEX_EXIT(&conn->conn_data_lock);
4360 conn_data_locked = 0;
4364 if (rxdebug_active) {
4368 len = _snprintf(msg, sizeof(msg),
4369 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4370 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4371 ntohl(ap->serial), ntohl(ap->previousPacket),
4372 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4373 ap->nAcks, ntohs(ap->bufferSpace) );
4377 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4378 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4382 OutputDebugString(msg);
4384 #else /* AFS_NT40_ENV */
4387 "RACK: reason %x previous %u seq %u serial %u first %u",
4388 ap->reason, ntohl(ap->previousPacket),
4389 (unsigned int)np->header.seq, (unsigned int)serial,
4390 ntohl(ap->firstPacket));
4393 for (offset = 0; offset < nAcks; offset++)
4394 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4399 #endif /* AFS_NT40_ENV */
4402 MUTEX_ENTER(&peer->peer_lock);
4405 * Start somewhere. Can't assume we can send what we can receive,
4406 * but we are clearly receiving.
4408 if (!peer->maxPacketSize)
4409 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4411 if (pktsize > peer->maxPacketSize) {
4412 peer->maxPacketSize = pktsize;
4413 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4414 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4415 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4416 rxi_ScheduleGrowMTUEvent(call, 1);
4421 clock_GetTime(&now);
4423 /* The transmit queue splits into 4 sections.
4425 * The first section is packets which have now been acknowledged
4426 * by a window size change in the ack. These have reached the
4427 * application layer, and may be discarded. These are packets
4428 * with sequence numbers < ap->firstPacket.
4430 * The second section is packets which have sequence numbers in
4431 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4432 * contents of the packet's ack array determines whether these
4433 * packets are acknowledged or not.
4435 * The third section is packets which fall above the range
4436 * addressed in the ack packet. These have not yet been received
4439 * The four section is packets which have not yet been transmitted.
4440 * These packets will have a header.serial of 0.
4443 /* First section - implicitly acknowledged packets that can be
4447 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4448 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4449 struct rx_packet *next;
4451 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4452 call->tfirst = tp->header.seq + 1;
4454 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4456 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4459 #ifdef RX_ENABLE_LOCKS
4460 /* XXX Hack. Because we have to release the global call lock when sending
4461 * packets (rxi_NetSend) we drop all acks while we're traversing the tq
4462 * in rxi_Start sending packets out because packets may move to the
4463 * freePacketQueue as result of being here! So we drop these packets until
4464 * we're safely out of the traversing. Really ugly!
4465 * To make it even uglier, if we're using fine grain locking, we can
4466 * set the ack bits in the packets and have rxi_Start remove the packets
4467 * when it's done transmitting.
4469 if (call->flags & RX_CALL_TQ_BUSY) {
4470 tp->flags |= RX_PKTFLAG_ACKED;
4471 call->flags |= RX_CALL_TQ_SOME_ACKED;
4473 #endif /* RX_ENABLE_LOCKS */
4475 opr_queue_Remove(&tp->entry);
4476 #ifdef RX_TRACK_PACKETS
4477 tp->flags &= ~RX_PKTFLAG_TQ;
4479 #ifdef RXDEBUG_PACKET
4481 #endif /* RXDEBUG_PACKET */
4482 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4487 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4489 /* Second section of the queue - packets for which we are receiving
4492 * Go through the explicit acks/nacks and record the results in
4493 * the waiting packets. These are packets that can't be released
4494 * yet, even with a positive acknowledge. This positive
4495 * acknowledge only means the packet has been received by the
4496 * peer, not that it will be retained long enough to be sent to
4497 * the peer's upper level. In addition, reset the transmit timers
4498 * of any missing packets (those packets that must be missing
4499 * because this packet was out of sequence) */
4501 call->nSoftAcked = 0;
4503 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4504 && tp->header.seq < first + nAcks) {
4505 /* Set the acknowledge flag per packet based on the
4506 * information in the ack packet. An acknowlegded packet can
4507 * be downgraded when the server has discarded a packet it
4508 * soacked previously, or when an ack packet is received
4509 * out of sequence. */
4510 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4511 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4513 tp->flags |= RX_PKTFLAG_ACKED;
4514 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4521 } else /* RX_ACK_TYPE_NACK */ {
4522 tp->flags &= ~RX_PKTFLAG_ACKED;
4526 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4529 /* We don't need to take any action with the 3rd or 4th section in the
4530 * queue - they're not addressed by the contents of this ACK packet.
4533 /* if the ack packet has a receivelen field hanging off it,
4534 * update our state */
4535 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4538 /* If the ack packet has a "recommended" size that is less than
4539 * what I am using now, reduce my size to match */
4540 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4541 (int)sizeof(afs_int32), &tSize);
4542 tSize = (afs_uint32) ntohl(tSize);
4543 if (tSize > RX_MAX_PACKET_SIZE)
4544 tSize = RX_MAX_PACKET_SIZE;
4545 if (tSize < RX_MIN_PACKET_SIZE)
4546 tSize = RX_MIN_PACKET_SIZE;
4547 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4549 /* Get the maximum packet size to send to this peer */
4550 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4552 tSize = (afs_uint32) ntohl(tSize);
4553 if (tSize > RX_MAX_PACKET_SIZE)
4554 tSize = RX_MAX_PACKET_SIZE;
4555 if (tSize < RX_MIN_PACKET_SIZE)
4556 tSize = RX_MIN_PACKET_SIZE;
4557 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4558 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4560 /* sanity check - peer might have restarted with different params.
4561 * If peer says "send less", dammit, send less... Peer should never
4562 * be unable to accept packets of the size that prior AFS versions would
4563 * send without asking. */
4564 if (peer->maxMTU != tSize) {
4565 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4567 peer->maxMTU = tSize;
4568 peer->MTU = MIN(tSize, peer->MTU);
4569 call->MTU = MIN(call->MTU, tSize);
4572 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4575 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4576 (int)sizeof(afs_int32), &tSize);
4577 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4580 if (tSize >= rx_maxSendWindow)
4581 tSize = rx_maxSendWindow;
4582 if (tSize < call->twind) { /* smaller than our send */
4583 call->twind = tSize; /* window, we must send less... */
4584 call->ssthresh = MIN(call->twind, call->ssthresh);
4585 call->conn->twind[call->channel] = call->twind;
4588 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4589 * network MTU confused with the loopback MTU. Calculate the
4590 * maximum MTU here for use in the slow start code below.
4592 /* Did peer restart with older RX version? */
4593 if (peer->maxDgramPackets > 1) {
4594 peer->maxDgramPackets = 1;
4596 } else if (np->length >=
4597 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4600 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4601 sizeof(afs_int32), &tSize);
4602 tSize = (afs_uint32) ntohl(tSize);
4605 if (tSize >= rx_maxSendWindow)
4606 tSize = rx_maxSendWindow;
4608 * As of AFS 3.5 we set the send window to match the receive window.
4610 if (tSize < call->twind) {
4611 call->twind = tSize;
4612 call->conn->twind[call->channel] = call->twind;
4613 call->ssthresh = MIN(call->twind, call->ssthresh);
4614 } else if (tSize > call->twind) {
4615 call->twind = tSize;
4616 call->conn->twind[call->channel] = call->twind;
4620 * As of AFS 3.5, a jumbogram is more than one fixed size
4621 * packet transmitted in a single UDP datagram. If the remote
4622 * MTU is smaller than our local MTU then never send a datagram
4623 * larger than the natural MTU.
4626 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4627 (int)sizeof(afs_int32), &tSize);
4628 maxDgramPackets = (afs_uint32) ntohl(tSize);
4629 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4631 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4632 if (maxDgramPackets > 1) {
4633 peer->maxDgramPackets = maxDgramPackets;
4634 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4636 peer->maxDgramPackets = 1;
4637 call->MTU = peer->natMTU;
4639 } else if (peer->maxDgramPackets > 1) {
4640 /* Restarted with lower version of RX */
4641 peer->maxDgramPackets = 1;
4643 } else if (peer->maxDgramPackets > 1
4644 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4645 /* Restarted with lower version of RX */
4646 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4647 peer->natMTU = OLD_MAX_PACKET_SIZE;
4648 peer->MTU = OLD_MAX_PACKET_SIZE;
4649 peer->maxDgramPackets = 1;
4650 peer->nDgramPackets = 1;
4652 call->MTU = OLD_MAX_PACKET_SIZE;
4655 /* If the window has been extended by this acknowledge packet,
4656 * then wakeup a sender waiting in alloc for window space, or try
4657 * sending packets now, if he's been sitting on packets due to
4658 * lack of window space */
4659 if (call->tnext < (call->tfirst + call->twind)) {
4660 #ifdef RX_ENABLE_LOCKS
4661 CV_SIGNAL(&call->cv_twind);
4663 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4664 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4665 osi_rxWakeup(&call->twind);
4668 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4669 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4675 * Calculate how many datagrams were successfully received after
4676 * the first missing packet and adjust the negative ack counter
4681 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4682 if (call->nNacks < nNacked) {
4683 call->nNacks = nNacked;
4686 call->nAcks += newAckCount;
4690 /* If the packet contained new acknowledgements, rather than just
4691 * being a duplicate of one we have previously seen, then we can restart
4694 if (newAckCount > 0)
4695 rxi_rto_packet_acked(call, istack);
4697 if (call->flags & RX_CALL_FAST_RECOVER) {
4698 if (newAckCount == 0) {
4699 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4701 call->flags &= ~RX_CALL_FAST_RECOVER;
4702 call->cwind = call->nextCwind;
4703 call->nextCwind = 0;
4706 call->nCwindAcks = 0;
4707 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4708 /* Three negative acks in a row trigger congestion recovery */
4709 call->flags |= RX_CALL_FAST_RECOVER;
4710 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4712 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4713 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4714 call->nextCwind = call->ssthresh;
4717 peer->MTU = call->MTU;
4718 peer->cwind = call->nextCwind;
4719 peer->nDgramPackets = call->nDgramPackets;
4721 call->congestSeq = peer->congestSeq;
4723 /* Reset the resend times on the packets that were nacked
4724 * so we will retransmit as soon as the window permits
4728 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4729 struct rx_packet *tp =
4730 opr_queue_Entry(cursor, struct rx_packet, entry);
4732 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4733 tp->flags &= ~RX_PKTFLAG_SENT;
4735 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4740 /* If cwind is smaller than ssthresh, then increase
4741 * the window one packet for each ack we receive (exponential
4743 * If cwind is greater than or equal to ssthresh then increase
4744 * the congestion window by one packet for each cwind acks we
4745 * receive (linear growth). */
4746 if (call->cwind < call->ssthresh) {
4748 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4749 call->nCwindAcks = 0;
4751 call->nCwindAcks += newAckCount;
4752 if (call->nCwindAcks >= call->cwind) {
4753 call->nCwindAcks = 0;
4754 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4758 * If we have received several acknowledgements in a row then
4759 * it is time to increase the size of our datagrams
4761 if ((int)call->nAcks > rx_nDgramThreshold) {
4762 if (peer->maxDgramPackets > 1) {
4763 if (call->nDgramPackets < peer->maxDgramPackets) {
4764 call->nDgramPackets++;
4766 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4767 } else if (call->MTU < peer->maxMTU) {
4768 /* don't upgrade if we can't handle it */
4769 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4770 call->MTU = peer->ifMTU;
4772 call->MTU += peer->natMTU;
4773 call->MTU = MIN(call->MTU, peer->maxMTU);
4780 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4782 /* Servers need to hold the call until all response packets have
4783 * been acknowledged. Soft acks are good enough since clients
4784 * are not allowed to clear their receive queues. */
4785 if (call->state == RX_STATE_HOLD
4786 && call->tfirst + call->nSoftAcked >= call->tnext) {
4787 call->state = RX_STATE_DALLY;
4788 rxi_ClearTransmitQueue(call, 0);
4789 rxi_CancelKeepAliveEvent(call);
4790 } else if (!opr_queue_IsEmpty(&call->tq)) {
4791 rxi_Start(call, istack);
4797 * Schedule a connection abort to be sent after some delay.
4799 * @param[in] conn The connection to send the abort on.
4800 * @param[in] msec The number of milliseconds to wait before sending.
4802 * @pre conn_data_lock must be held
4805 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4807 struct clock when, now;
4809 MUTEX_ASSERT(&conn->conn_data_lock);
4813 if (!conn->delayedAbortEvent) {
4814 clock_GetTime(&now);
4816 clock_Addmsec(&when, msec);
4817 rx_GetConnection(conn);
4818 conn->delayedAbortEvent =
4819 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4823 /* Received a response to a challenge packet */
4824 static struct rx_packet *
4825 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4826 struct rx_packet *np, int istack)
4830 /* Ignore the packet if we're the client */
4831 if (conn->type == RX_CLIENT_CONNECTION)
4834 /* If already authenticated, ignore the packet (it's probably a retry) */
4835 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4838 if (!conn->securityChallengeSent) {
4839 /* We've never sent out a challenge for this connection, so this
4840 * response cannot possibly be correct; ignore it. This can happen
4841 * if we sent a challenge to the client, then we were restarted, and
4842 * then the client sent us a response. If we ignore the response, the
4843 * client will eventually resend a data packet, causing us to send a
4844 * new challenge and the client to send a new response. */
4848 /* Otherwise, have the security object evaluate the response packet */
4849 error = RXS_CheckResponse(conn->securityObject, conn, np);
4851 /* If the response is invalid, reset the connection, sending
4852 * an abort to the peer. Send the abort with a 1 second delay,
4853 * to avoid a peer hammering us by constantly recreating a
4854 * connection with bad credentials. */
4855 rxi_ConnectionError(conn, error);
4856 MUTEX_ENTER(&conn->conn_data_lock);
4857 rxi_SendConnectionAbortLater(conn, 1000);
4858 MUTEX_EXIT(&conn->conn_data_lock);
4861 /* If the response is valid, any calls waiting to attach
4862 * servers can now do so */
4865 for (i = 0; i < RX_MAXCALLS; i++) {
4866 struct rx_call *call = conn->call[i];
4868 MUTEX_ENTER(&call->lock);
4869 if (call->state == RX_STATE_PRECALL)
4870 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4871 /* tnop can be null if newcallp is null */
4872 MUTEX_EXIT(&call->lock);
4876 /* Update the peer reachability information, just in case
4877 * some calls went into attach-wait while we were waiting
4878 * for authentication..
4880 rxi_UpdatePeerReach(conn, NULL, istack);
4885 /* A client has received an authentication challenge: the security
4886 * object is asked to cough up a respectable response packet to send
4887 * back to the server. The server is responsible for retrying the
4888 * challenge if it fails to get a response. */
4890 static struct rx_packet *
4891 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4892 struct rx_packet *np, int istack)
4896 /* Ignore the challenge if we're the server */
4897 if (conn->type == RX_SERVER_CONNECTION)
4900 /* Ignore the challenge if the connection is otherwise idle; someone's
4901 * trying to use us as an oracle. */
4902 if (!rxi_HasActiveCalls(conn))
4905 /* Send the security object the challenge packet. It is expected to fill
4906 * in the response. */
4907 error = RXS_GetResponse(conn->securityObject, conn, np);
4909 /* If the security object is unable to return a valid response, reset the
4910 * connection and send an abort to the peer. Otherwise send the response
4911 * packet to the peer connection. */
4913 rxi_ConnectionError(conn, error);
4914 MUTEX_ENTER(&conn->conn_data_lock);
4915 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4916 MUTEX_EXIT(&conn->conn_data_lock);
4918 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4919 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4925 /* Find an available server process to service the current request in
4926 * the given call structure. If one isn't available, queue up this
4927 * call so it eventually gets one */
4929 rxi_AttachServerProc(struct rx_call *call,
4930 osi_socket socket, int *tnop,
4931 struct rx_call **newcallp)
4933 struct rx_serverQueueEntry *sq;
4934 struct rx_service *service = call->conn->service;
4937 /* May already be attached */
4938 if (call->state == RX_STATE_ACTIVE)
4941 MUTEX_ENTER(&rx_serverPool_lock);
4943 haveQuota = QuotaOK(service);
4944 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4945 /* If there are no processes available to service this call,
4946 * put the call on the incoming call queue (unless it's
4947 * already on the queue).
4949 #ifdef RX_ENABLE_LOCKS
4951 ReturnToServerPool(service);
4952 #endif /* RX_ENABLE_LOCKS */
4954 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4955 call->flags |= RX_CALL_WAIT_PROC;
4956 rx_atomic_inc(&rx_nWaiting);
4957 rx_atomic_inc(&rx_nWaited);
4958 rxi_calltrace(RX_CALL_ARRIVAL, call);
4959 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4960 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4963 sq = opr_queue_Last(&rx_idleServerQueue,
4964 struct rx_serverQueueEntry, entry);
4966 /* If hot threads are enabled, and both newcallp and sq->socketp
4967 * are non-null, then this thread will process the call, and the
4968 * idle server thread will start listening on this threads socket.
4970 opr_queue_Remove(&sq->entry);
4972 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4975 *sq->socketp = socket;
4976 clock_GetTime(&call->startTime);
4977 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4981 if (call->flags & RX_CALL_WAIT_PROC) {
4982 /* Conservative: I don't think this should happen */
4983 call->flags &= ~RX_CALL_WAIT_PROC;
4984 rx_atomic_dec(&rx_nWaiting);
4985 if (opr_queue_IsOnQueue(&call->entry)) {
4986 opr_queue_Remove(&call->entry);
4988 CLEAR_CALL_QUEUE_LOCK(call);
4990 call->state = RX_STATE_ACTIVE;
4991 call->app.mode = RX_MODE_RECEIVING;
4992 #ifdef RX_KERNEL_TRACE
4994 int glockOwner = ISAFS_GLOCK();
4997 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4998 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
5004 if (call->flags & RX_CALL_CLEARED) {
5005 /* send an ack now to start the packet flow up again */
5006 call->flags &= ~RX_CALL_CLEARED;
5007 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5009 #ifdef RX_ENABLE_LOCKS
5012 service->nRequestsRunning++;
5013 MUTEX_ENTER(&rx_quota_mutex);
5014 if (service->nRequestsRunning <= service->minProcs)
5017 MUTEX_EXIT(&rx_quota_mutex);
5021 MUTEX_EXIT(&rx_serverPool_lock);
5024 /* Delay the sending of an acknowledge event for a short while, while
5025 * a new call is being prepared (in the case of a client) or a reply
5026 * is being prepared (in the case of a server). Rather than sending
5027 * an ack packet, an ACKALL packet is sent. */
5029 rxi_AckAll(struct rx_call *call)
5031 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
5033 call->flags |= RX_CALL_ACKALL_SENT;
5037 * Event handler for per-call delayed acks.
5038 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5042 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5045 struct rx_call *call = arg1;
5046 #ifdef RX_ENABLE_LOCKS
5048 MUTEX_ENTER(&call->lock);
5049 if (event == call->delayedAckEvent)
5050 rxevent_Put(&call->delayedAckEvent);
5052 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5054 MUTEX_EXIT(&call->lock);
5055 #else /* RX_ENABLE_LOCKS */
5057 rxevent_Put(&call->delayedAckEvent);
5058 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5059 #endif /* RX_ENABLE_LOCKS */
5060 /* Release the call reference for the event that fired. */
5062 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5065 #ifdef RX_ENABLE_LOCKS
5066 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5067 * clearing them out.
5070 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5072 struct opr_queue *cursor;
5075 for (opr_queue_Scan(&call->tq, cursor)) {
5077 = opr_queue_Entry(cursor, struct rx_packet, entry);
5079 p->flags |= RX_PKTFLAG_ACKED;
5084 call->flags |= RX_CALL_TQ_CLEARME;
5085 call->flags |= RX_CALL_TQ_SOME_ACKED;
5088 rxi_rto_cancel(call);
5090 call->tfirst = call->tnext;
5091 call->nSoftAcked = 0;
5093 if (call->flags & RX_CALL_FAST_RECOVER) {
5094 call->flags &= ~RX_CALL_FAST_RECOVER;
5095 call->cwind = call->nextCwind;
5096 call->nextCwind = 0;
5099 CV_SIGNAL(&call->cv_twind);
5101 #endif /* RX_ENABLE_LOCKS */
5104 * Acknowledge the whole transmit queue.
5106 * If we're running without locks, or the transmit queue isn't busy, then
5107 * we can just clear the queue now. Otherwise, we have to mark all of the
5108 * packets as acknowledged, and let rxi_Start clear it later on
5111 rxi_AckAllInTransmitQueue(struct rx_call *call)
5113 #ifdef RX_ENABLE_LOCKS
5114 if (call->flags & RX_CALL_TQ_BUSY) {
5115 rxi_SetAcksInTransmitQueue(call);
5119 rxi_ClearTransmitQueue(call, 0);
5121 /* Clear out the transmit queue for the current call (all packets have
5122 * been received by peer) */
5124 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5126 #ifdef RX_ENABLE_LOCKS
5127 struct opr_queue *cursor;
5128 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5130 for (opr_queue_Scan(&call->tq, cursor)) {
5132 = opr_queue_Entry(cursor, struct rx_packet, entry);
5134 p->flags |= RX_PKTFLAG_ACKED;
5138 call->flags |= RX_CALL_TQ_CLEARME;
5139 call->flags |= RX_CALL_TQ_SOME_ACKED;
5142 #endif /* RX_ENABLE_LOCKS */
5143 #ifdef RXDEBUG_PACKET
5145 #endif /* RXDEBUG_PACKET */
5146 rxi_FreePackets(0, &call->tq);
5147 rxi_WakeUpTransmitQueue(call);
5148 #ifdef RX_ENABLE_LOCKS
5149 call->flags &= ~RX_CALL_TQ_CLEARME;
5153 rxi_rto_cancel(call);
5154 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5155 call->nSoftAcked = 0;
5157 if (call->flags & RX_CALL_FAST_RECOVER) {
5158 call->flags &= ~RX_CALL_FAST_RECOVER;
5159 call->cwind = call->nextCwind;
5161 #ifdef RX_ENABLE_LOCKS
5162 CV_SIGNAL(&call->cv_twind);
5164 osi_rxWakeup(&call->twind);
5169 rxi_ClearReceiveQueue(struct rx_call *call)
5171 if (!opr_queue_IsEmpty(&call->rq)) {
5174 count = rxi_FreePackets(0, &call->rq);
5175 rx_packetReclaims += count;
5176 #ifdef RXDEBUG_PACKET
5178 if ( call->rqc != 0 )
5179 dpf(("rxi_ClearReceiveQueue call %p rqc %u != 0\n", call, call->rqc));
5181 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5183 if (call->state == RX_STATE_PRECALL) {
5184 call->flags |= RX_CALL_CLEARED;
5188 /* Send an abort packet for the specified call */
5189 static struct rx_packet *
5190 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5191 int istack, int force)
5194 struct clock when, now;
5199 /* Clients should never delay abort messages */
5200 if (rx_IsClientConn(call->conn))
5204 * An opcode that has been deprecated or has yet to be implemented is not
5205 * a misbehavior of the client. Do not punish the client by introducing
5208 if (call->error == RXGEN_OPCODE) {
5210 } else if (call->abortCode != call->error) {
5211 call->abortCode = call->error;
5212 call->abortCount = 0;
5215 if (force || rxi_callAbortThreshhold == 0
5216 || call->abortCount < rxi_callAbortThreshhold) {
5217 rxi_CancelDelayedAbortEvent(call);
5218 error = htonl(call->error);
5222 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5223 (char *)&error, sizeof(error), istack);
5224 } else if (!call->delayedAbortEvent) {
5225 clock_GetTime(&now);
5227 clock_Addmsec(&when, rxi_callAbortDelay);
5228 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5229 call->delayedAbortEvent =
5230 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5236 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5238 MUTEX_ASSERT(&call->lock);
5239 if (rxevent_Cancel(&call->delayedAbortEvent))
5240 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5243 /* Send an abort packet for the specified connection. Packet is an
5244 * optional pointer to a packet that can be used to send the abort.
5245 * Once the number of abort messages reaches the threshhold, an
5246 * event is scheduled to send the abort. Setting the force flag
5247 * overrides sending delayed abort messages.
5249 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5250 * to send the abort packet.
5253 rxi_SendConnectionAbort(struct rx_connection *conn,
5254 struct rx_packet *packet, int istack, int force)
5261 /* Clients should never delay abort messages */
5262 if (rx_IsClientConn(conn))
5265 if (force || rxi_connAbortThreshhold == 0
5266 || conn->abortCount < rxi_connAbortThreshhold) {
5268 if (rxevent_Cancel(&conn->delayedAbortEvent))
5269 putConnection(conn);
5270 error = htonl(conn->error);
5272 MUTEX_EXIT(&conn->conn_data_lock);
5274 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5275 RX_PACKET_TYPE_ABORT, (char *)&error,
5276 sizeof(error), istack);
5277 MUTEX_ENTER(&conn->conn_data_lock);
5279 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5284 /* Associate an error all of the calls owned by a connection. Called
5285 * with error non-zero. This is only for really fatal things, like
5286 * bad authentication responses. The connection itself is set in
5287 * error at this point, so that future packets received will be
5290 rxi_ConnectionError(struct rx_connection *conn,
5296 dpf(("rxi_ConnectionError conn %p error %d\n", conn, error));
5298 MUTEX_ENTER(&conn->conn_data_lock);
5299 if (rxevent_Cancel(&conn->challengeEvent))
5300 putConnection(conn);
5301 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5302 putConnection(conn);
5303 if (rxevent_Cancel(&conn->checkReachEvent)) {
5304 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5305 putConnection(conn);
5307 MUTEX_EXIT(&conn->conn_data_lock);
5308 for (i = 0; i < RX_MAXCALLS; i++) {
5309 struct rx_call *call = conn->call[i];
5311 MUTEX_ENTER(&call->lock);
5312 rxi_CallError(call, error);
5313 MUTEX_EXIT(&call->lock);
5316 conn->error = error;
5317 if (rx_stats_active)
5318 rx_atomic_inc(&rx_stats.fatalErrors);
5323 * Interrupt an in-progress call with the specified error and wakeup waiters.
5325 * @param[in] call The call to interrupt
5326 * @param[in] error The error code to send to the peer
5329 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5331 MUTEX_ENTER(&call->lock);
5332 rxi_CallError(call, error);
5333 rxi_SendCallAbort(call, NULL, 0, 1);
5334 MUTEX_EXIT(&call->lock);
5338 rxi_CallError(struct rx_call *call, afs_int32 error)
5340 MUTEX_ASSERT(&call->lock);
5341 dpf(("rxi_CallError call %p error %d call->error %d\n", call, error, call->error));
5343 error = call->error;
5345 #ifdef RX_ENABLE_LOCKS
5346 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5347 rxi_ResetCall(call, 0);
5350 rxi_ResetCall(call, 0);
5352 call->error = error;
5355 /* Reset various fields in a call structure, and wakeup waiting
5356 * processes. Some fields aren't changed: state & mode are not
5357 * touched (these must be set by the caller), and bufptr, nLeft, and
5358 * nFree are not reset, since these fields are manipulated by
5359 * unprotected macros, and may only be reset by non-interrupting code.
5363 rxi_ResetCall(struct rx_call *call, int newcall)
5366 struct rx_peer *peer;
5367 struct rx_packet *packet;
5369 MUTEX_ASSERT(&call->lock);
5370 dpf(("rxi_ResetCall(call %p, newcall %d)\n", call, newcall));
5372 /* Notify anyone who is waiting for asynchronous packet arrival */
5373 if (call->arrivalProc) {
5374 (*call->arrivalProc) (call, call->arrivalProcHandle,
5375 call->arrivalProcArg);
5376 call->arrivalProc = NULL;
5380 rxi_CancelGrowMTUEvent(call);
5382 if (call->delayedAbortEvent) {
5383 rxi_CancelDelayedAbortEvent(call);
5384 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5386 rxi_SendCallAbort(call, packet, 0, 1);
5387 rxi_FreePacket(packet);
5392 * Update the peer with the congestion information in this call
5393 * so other calls on this connection can pick up where this call
5394 * left off. If the congestion sequence numbers don't match then
5395 * another call experienced a retransmission.
5397 peer = call->conn->peer;
5398 MUTEX_ENTER(&peer->peer_lock);
5400 if (call->congestSeq == peer->congestSeq) {
5401 peer->cwind = MAX(peer->cwind, call->cwind);
5402 peer->MTU = MAX(peer->MTU, call->MTU);
5403 peer->nDgramPackets =
5404 MAX(peer->nDgramPackets, call->nDgramPackets);
5407 call->abortCode = 0;
5408 call->abortCount = 0;
5410 if (peer->maxDgramPackets > 1) {
5411 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5413 call->MTU = peer->MTU;
5415 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5416 call->ssthresh = rx_maxSendWindow;
5417 call->nDgramPackets = peer->nDgramPackets;
5418 call->congestSeq = peer->congestSeq;
5419 call->rtt = peer->rtt;
5420 call->rtt_dev = peer->rtt_dev;
5421 clock_Zero(&call->rto);
5422 clock_Addmsec(&call->rto,
5423 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5424 MUTEX_EXIT(&peer->peer_lock);
5426 flags = call->flags;
5427 rxi_WaitforTQBusy(call);
5429 rxi_ClearTransmitQueue(call, 1);
5430 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5431 dpf(("rcall %p has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5435 rxi_ClearReceiveQueue(call);
5436 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5440 call->twind = call->conn->twind[call->channel];
5441 call->rwind = call->conn->rwind[call->channel];
5442 call->nSoftAcked = 0;
5443 call->nextCwind = 0;
5446 call->nCwindAcks = 0;
5447 call->nSoftAcks = 0;
5448 call->nHardAcks = 0;
5450 call->tfirst = call->rnext = call->tnext = 1;
5453 call->lastAcked = 0;
5454 call->localStatus = call->remoteStatus = 0;
5456 if (flags & RX_CALL_READER_WAIT) {
5457 #ifdef RX_ENABLE_LOCKS
5458 CV_BROADCAST(&call->cv_rq);
5460 osi_rxWakeup(&call->rq);
5463 if (flags & RX_CALL_WAIT_PACKETS) {
5464 MUTEX_ENTER(&rx_freePktQ_lock);
5465 rxi_PacketsUnWait(); /* XXX */
5466 MUTEX_EXIT(&rx_freePktQ_lock);
5468 #ifdef RX_ENABLE_LOCKS
5469 CV_SIGNAL(&call->cv_twind);
5471 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5472 osi_rxWakeup(&call->twind);
5475 if (flags & RX_CALL_WAIT_PROC) {
5476 rx_atomic_dec(&rx_nWaiting);
5478 #ifdef RX_ENABLE_LOCKS
5479 /* The following ensures that we don't mess with any queue while some
5480 * other thread might also be doing so. The call_queue_lock field is
5481 * is only modified under the call lock. If the call is in the process
5482 * of being removed from a queue, the call is not locked until the
5483 * the queue lock is dropped and only then is the call_queue_lock field
5484 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5485 * Note that any other routine which removes a call from a queue has to
5486 * obtain the queue lock before examing the queue and removing the call.
5488 if (call->call_queue_lock) {
5489 MUTEX_ENTER(call->call_queue_lock);
5490 if (opr_queue_IsOnQueue(&call->entry)) {
5491 opr_queue_Remove(&call->entry);
5493 MUTEX_EXIT(call->call_queue_lock);
5494 CLEAR_CALL_QUEUE_LOCK(call);
5496 #else /* RX_ENABLE_LOCKS */
5497 if (opr_queue_IsOnQueue(&call->entry)) {
5498 opr_queue_Remove(&call->entry);
5500 #endif /* RX_ENABLE_LOCKS */
5502 rxi_CancelKeepAliveEvent(call);
5503 rxi_CancelDelayedAckEvent(call);
5506 /* Send an acknowledge for the indicated packet (seq,serial) of the
5507 * indicated call, for the indicated reason (reason). This
5508 * acknowledge will specifically acknowledge receiving the packet, and
5509 * will also specify which other packets for this call have been
5510 * received. This routine returns the packet that was used to the
5511 * caller. The caller is responsible for freeing it or re-using it.
5512 * This acknowledgement also returns the highest sequence number
5513 * actually read out by the higher level to the sender; the sender
5514 * promises to keep around packets that have not been read by the
5515 * higher level yet (unless, of course, the sender decides to abort
5516 * the call altogether). Any of p, seq, serial, pflags, or reason may
5517 * be set to zero without ill effect. That is, if they are zero, they
5518 * will not convey any information.
5519 * NOW there is a trailer field, after the ack where it will safely be
5520 * ignored by mundanes, which indicates the maximum size packet this
5521 * host can swallow. */
5523 struct rx_packet *optionalPacket; use to send ack (or null)
5524 int seq; Sequence number of the packet we are acking
5525 int serial; Serial number of the packet
5526 int pflags; Flags field from packet header
5527 int reason; Reason an acknowledge was prompted
5530 #define RX_ZEROS 1024
5531 static char rx_zeros[RX_ZEROS];
5534 rxi_SendAck(struct rx_call *call,
5535 struct rx_packet *optionalPacket, int serial, int reason,
5538 struct rx_ackPacket *ap;
5539 struct rx_packet *p;
5540 struct opr_queue *cursor;
5543 afs_uint32 padbytes = 0;
5544 #ifdef RX_ENABLE_TSFPQ
5545 struct rx_ts_info_t * rx_ts_info;
5549 * Open the receive window once a thread starts reading packets
5551 if (call->rnext > 1) {
5552 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5555 /* Don't attempt to grow MTU if this is a critical ping */
5556 if (reason == RX_ACK_MTU) {
5557 /* keep track of per-call attempts, if we're over max, do in small
5558 * otherwise in larger? set a size to increment by, decrease
5561 if (call->conn->peer->maxPacketSize &&
5562 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5564 padbytes = call->conn->peer->maxPacketSize+16;
5566 padbytes = call->conn->peer->maxMTU + 128;
5568 /* do always try a minimum size ping */
5569 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5571 /* subtract the ack payload */
5572 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5573 reason = RX_ACK_PING;
5576 call->nHardAcks = 0;
5577 call->nSoftAcks = 0;
5578 if (call->rnext > call->lastAcked)
5579 call->lastAcked = call->rnext;
5583 rx_computelen(p, p->length); /* reset length, you never know */
5584 } /* where that's been... */
5585 #ifdef RX_ENABLE_TSFPQ
5587 RX_TS_INFO_GET(rx_ts_info);
5588 if ((p = rx_ts_info->local_special_packet)) {
5589 rx_computelen(p, p->length);
5590 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5591 rx_ts_info->local_special_packet = p;
5592 } else { /* We won't send the ack, but don't panic. */
5593 return optionalPacket;
5597 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5598 /* We won't send the ack, but don't panic. */
5599 return optionalPacket;
5604 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5607 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5608 #ifndef RX_ENABLE_TSFPQ
5609 if (!optionalPacket)
5612 return optionalPacket;
5614 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5615 if (rx_Contiguous(p) < templ) {
5616 #ifndef RX_ENABLE_TSFPQ
5617 if (!optionalPacket)
5620 return optionalPacket;
5625 /* MTUXXX failing to send an ack is very serious. We should */
5626 /* try as hard as possible to send even a partial ack; it's */
5627 /* better than nothing. */
5628 ap = (struct rx_ackPacket *)rx_DataOf(p);
5629 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5630 ap->reason = reason;
5632 /* The skew computation used to be bogus, I think it's better now. */
5633 /* We should start paying attention to skew. XXX */
5634 ap->serial = htonl(serial);
5635 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5638 * First packet not yet forwarded to reader. When ACKALL has been
5639 * sent the peer has been told that all received packets will be
5640 * delivered to the reader. The value 'rnext' is used internally
5641 * to refer to the next packet in the receive queue that must be
5642 * delivered to the reader. From the perspective of the peer it
5643 * already has so report the last sequence number plus one if there
5644 * are packets in the receive queue awaiting processing.
5646 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5647 !opr_queue_IsEmpty(&call->rq)) {
5648 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5650 ap->firstPacket = htonl(call->rnext);
5652 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5654 /* No fear of running out of ack packet here because there can only
5655 * be at most one window full of unacknowledged packets. The window
5656 * size must be constrained to be less than the maximum ack size,
5657 * of course. Also, an ack should always fit into a single packet
5658 * -- it should not ever be fragmented. */
5660 for (opr_queue_Scan(&call->rq, cursor)) {
5661 struct rx_packet *rqp
5662 = opr_queue_Entry(cursor, struct rx_packet, entry);
5664 if (!rqp || !call->rq.next
5665 || (rqp->header.seq > (call->rnext + call->rwind))) {
5666 #ifndef RX_ENABLE_TSFPQ
5667 if (!optionalPacket)
5670 rxi_CallError(call, RX_CALL_DEAD);
5671 return optionalPacket;
5674 while (rqp->header.seq > call->rnext + offset)
5675 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5676 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5678 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5679 #ifndef RX_ENABLE_TSFPQ
5680 if (!optionalPacket)
5683 rxi_CallError(call, RX_CALL_DEAD);
5684 return optionalPacket;
5690 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5692 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5695 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5697 /* these are new for AFS 3.3 */
5698 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5699 templ = htonl(templ);
5700 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5701 templ = htonl(call->conn->peer->ifMTU);
5702 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5703 sizeof(afs_int32), &templ);
5705 /* new for AFS 3.4 */
5706 templ = htonl(call->rwind);
5707 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5708 sizeof(afs_int32), &templ);
5710 /* new for AFS 3.5 */
5711 templ = htonl(call->conn->peer->ifDgramPackets);
5712 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5713 sizeof(afs_int32), &templ);
5715 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5717 p->header.serviceId = call->conn->serviceId;
5718 p->header.cid = (call->conn->cid | call->channel);
5719 p->header.callNumber = *call->callNumber;
5721 p->header.securityIndex = call->conn->securityIndex;
5722 p->header.epoch = call->conn->epoch;
5723 p->header.type = RX_PACKET_TYPE_ACK;
5724 p->header.flags = RX_SLOW_START_OK;
5725 if (reason == RX_ACK_PING)
5726 p->header.flags |= RX_REQUEST_ACK;
5728 while (padbytes > 0) {
5729 if (padbytes > RX_ZEROS) {
5730 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5731 p->length += RX_ZEROS;
5732 padbytes -= RX_ZEROS;
5734 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5735 p->length += padbytes;
5740 if (call->conn->type == RX_CLIENT_CONNECTION)
5741 p->header.flags |= RX_CLIENT_INITIATED;
5745 if (rxdebug_active) {
5749 len = _snprintf(msg, sizeof(msg),
5750 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5751 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5752 ntohl(ap->serial), ntohl(ap->previousPacket),
5753 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5754 ap->nAcks, ntohs(ap->bufferSpace) );
5758 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5759 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5763 OutputDebugString(msg);
5765 #else /* AFS_NT40_ENV */
5767 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5768 ap->reason, ntohl(ap->previousPacket),
5769 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5771 for (offset = 0; offset < ap->nAcks; offset++)
5772 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5777 #endif /* AFS_NT40_ENV */
5780 int i, nbytes = p->length;
5782 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5783 if (nbytes <= p->wirevec[i].iov_len) {
5786 savelen = p->wirevec[i].iov_len;
5788 p->wirevec[i].iov_len = nbytes;
5790 rxi_Send(call, p, istack);
5791 p->wirevec[i].iov_len = savelen;
5795 nbytes -= p->wirevec[i].iov_len;
5798 if (rx_stats_active)
5799 rx_atomic_inc(&rx_stats.ackPacketsSent);
5800 #ifndef RX_ENABLE_TSFPQ
5801 if (!optionalPacket)
5804 return optionalPacket; /* Return packet for re-use by caller */
5808 struct rx_packet **list;
5813 /* Send all of the packets in the list in single datagram */
5815 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5816 int istack, int moreFlag)
5822 struct rx_connection *conn = call->conn;
5823 struct rx_peer *peer = conn->peer;
5825 MUTEX_ENTER(&peer->peer_lock);
5826 peer->nSent += xmit->len;
5827 if (xmit->resending)
5828 peer->reSends += xmit->len;
5829 MUTEX_EXIT(&peer->peer_lock);
5831 if (rx_stats_active) {
5832 if (xmit->resending)
5833 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5835 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5838 clock_GetTime(&now);
5840 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5844 /* Set the packet flags and schedule the resend events */
5845 /* Only request an ack for the last packet in the list */
5846 for (i = 0; i < xmit->len; i++) {
5847 struct rx_packet *packet = xmit->list[i];
5849 /* Record the time sent */
5850 packet->timeSent = now;
5851 packet->flags |= RX_PKTFLAG_SENT;
5853 /* Ask for an ack on retransmitted packets, on every other packet
5854 * if the peer doesn't support slow start. Ask for an ack on every
5855 * packet until the congestion window reaches the ack rate. */
5856 if (packet->header.serial) {
5859 packet->firstSent = now;
5860 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5861 || (!(call->flags & RX_CALL_SLOW_START_OK)
5862 && (packet->header.seq & 1)))) {
5867 /* Tag this packet as not being the last in this group,
5868 * for the receiver's benefit */
5869 if (i < xmit->len - 1 || moreFlag) {
5870 packet->header.flags |= RX_MORE_PACKETS;
5875 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5878 /* Since we're about to send a data packet to the peer, it's
5879 * safe to nuke any scheduled end-of-packets ack */
5880 rxi_CancelDelayedAckEvent(call);
5882 MUTEX_EXIT(&call->lock);
5883 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5884 if (xmit->len > 1) {
5885 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5887 rxi_SendPacket(call, conn, xmit->list[0], istack);
5889 MUTEX_ENTER(&call->lock);
5890 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5892 /* Tell the RTO calculation engine that we have sent a packet, and
5893 * if it was the last one */
5894 rxi_rto_packet_sent(call, lastPacket, istack);
5896 /* Update last send time for this call (for keep-alive
5897 * processing), and for the connection (so that we can discover
5898 * idle connections) */
5899 conn->lastSendTime = call->lastSendTime = clock_Sec();
5902 /* When sending packets we need to follow these rules:
5903 * 1. Never send more than maxDgramPackets in a jumbogram.
5904 * 2. Never send a packet with more than two iovecs in a jumbogram.
5905 * 3. Never send a retransmitted packet in a jumbogram.
5906 * 4. Never send more than cwind/4 packets in a jumbogram
5907 * We always keep the last list we should have sent so we
5908 * can set the RX_MORE_PACKETS flags correctly.
5912 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5917 struct xmitlist working;
5918 struct xmitlist last;
5920 struct rx_peer *peer = call->conn->peer;
5921 int morePackets = 0;
5923 memset(&last, 0, sizeof(struct xmitlist));
5924 working.list = &list[0];
5926 working.resending = 0;
5928 recovery = call->flags & RX_CALL_FAST_RECOVER;
5930 for (i = 0; i < len; i++) {
5931 /* Does the current packet force us to flush the current list? */
5933 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5934 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5936 /* This sends the 'last' list and then rolls the current working
5937 * set into the 'last' one, and resets the working set */
5940 rxi_SendList(call, &last, istack, 1);
5941 /* If the call enters an error state stop sending, or if
5942 * we entered congestion recovery mode, stop sending */
5944 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5949 working.resending = 0;
5950 working.list = &list[i];
5952 /* Add the current packet to the list if it hasn't been acked.
5953 * Otherwise adjust the list pointer to skip the current packet. */
5954 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5957 if (list[i]->header.serial)
5958 working.resending = 1;
5960 /* Do we need to flush the list? */
5961 if (working.len >= (int)peer->maxDgramPackets
5962 || working.len >= (int)call->nDgramPackets
5963 || working.len >= (int)call->cwind
5964 || list[i]->header.serial
5965 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5967 rxi_SendList(call, &last, istack, 1);
5968 /* If the call enters an error state stop sending, or if
5969 * we entered congestion recovery mode, stop sending */
5971 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5976 working.resending = 0;
5977 working.list = &list[i + 1];
5980 if (working.len != 0) {
5981 osi_Panic("rxi_SendList error");
5983 working.list = &list[i + 1];
5987 /* Send the whole list when the call is in receive mode, when
5988 * the call is in eof mode, when we are in fast recovery mode,
5989 * and when we have the last packet */
5990 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5991 * the listener or event threads
5993 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5994 || (call->flags & RX_CALL_FLUSH)
5995 || (call->flags & RX_CALL_FAST_RECOVER)) {
5996 /* Check for the case where the current list contains
5997 * an acked packet. Since we always send retransmissions
5998 * in a separate packet, we only need to check the first
5999 * packet in the list */
6000 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
6004 rxi_SendList(call, &last, istack, morePackets);
6005 /* If the call enters an error state stop sending, or if
6006 * we entered congestion recovery mode, stop sending */
6008 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6012 rxi_SendList(call, &working, istack, 0);
6014 } else if (last.len > 0) {
6015 rxi_SendList(call, &last, istack, 0);
6016 /* Packets which are in 'working' are not sent by this call */
6021 * Check if the peer for the given call is known to be dead
6023 * If the call's peer appears dead (it has encountered fatal network errors
6024 * since the call started) the call is killed with RX_CALL_DEAD if the call
6025 * is active. Otherwise, we do nothing.
6027 * @param[in] call The call to check
6030 * @retval 0 The call is fine, and we haven't done anything to the call
6031 * @retval nonzero The call's peer appears dead, and the call has been
6032 * terminated if it was active
6034 * @pre call->lock must be locked
6037 rxi_CheckPeerDead(struct rx_call *call)
6039 #ifdef AFS_RXERRQ_ENV
6042 if (call->state == RX_STATE_DALLY) {
6046 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6047 if (call->neterr_gen < peererrs) {
6048 /* we have received network errors since this call started; kill
6050 if (call->state == RX_STATE_ACTIVE) {
6051 rxi_CallError(call, RX_CALL_DEAD);
6055 if (call->neterr_gen > peererrs) {
6056 /* someone has reset the number of peer errors; set the call error gen
6057 * so we can detect if more errors are encountered */
6058 call->neterr_gen = peererrs;
6065 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6067 struct rx_call *call = arg0;
6068 struct rx_peer *peer;
6069 struct opr_queue *cursor;
6070 struct clock maxTimeout = { 60, 0 };
6072 MUTEX_ENTER(&call->lock);
6074 peer = call->conn->peer;
6076 /* Make sure that the event pointer is removed from the call
6077 * structure, since there is no longer a per-call retransmission
6079 if (event == call->resendEvent)
6080 rxevent_Put(&call->resendEvent);
6082 rxi_CheckPeerDead(call);
6084 if (opr_queue_IsEmpty(&call->tq)) {
6085 /* Nothing to do. This means that we've been raced, and that an
6086 * ACK has come in between when we were triggered, and when we
6087 * actually got to run. */
6091 /* We're in loss recovery */
6092 call->flags |= RX_CALL_FAST_RECOVER;
6094 /* Mark all of the pending packets in the queue as being lost */
6095 for (opr_queue_Scan(&call->tq, cursor)) {
6096 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6097 if (!(p->flags & RX_PKTFLAG_ACKED))
6098 p->flags &= ~RX_PKTFLAG_SENT;
6101 /* We're resending, so we double the timeout of the call. This will be
6102 * dropped back down by the first successful ACK that we receive.
6104 * We apply a maximum value here of 60 seconds
6106 clock_Add(&call->rto, &call->rto);
6107 if (clock_Gt(&call->rto, &maxTimeout))
6108 call->rto = maxTimeout;
6110 /* Packet loss is most likely due to congestion, so drop our window size
6111 * and start again from the beginning */
6112 if (peer->maxDgramPackets >1) {
6113 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6114 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6116 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6117 call->nDgramPackets = 1;
6119 call->nextCwind = 1;
6122 MUTEX_ENTER(&peer->peer_lock);
6123 peer->MTU = call->MTU;
6124 peer->cwind = call->cwind;
6125 peer->nDgramPackets = 1;
6127 call->congestSeq = peer->congestSeq;
6128 MUTEX_EXIT(&peer->peer_lock);
6130 rxi_Start(call, istack);
6133 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6134 MUTEX_EXIT(&call->lock);
6137 /* This routine is called when new packets are readied for
6138 * transmission and when retransmission may be necessary, or when the
6139 * transmission window or burst count are favourable. This should be
6140 * better optimized for new packets, the usual case, now that we've
6141 * got rid of queues of send packets. XXXXXXXXXXX */
6143 rxi_Start(struct rx_call *call, int istack)
6145 struct opr_queue *cursor;
6146 #ifdef RX_ENABLE_LOCKS
6147 struct opr_queue *store;
6153 #ifdef RX_ENABLE_LOCKS
6154 if (rx_stats_active)
6155 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6160 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6161 /* Send (or resend) any packets that need it, subject to
6162 * window restrictions and congestion burst control
6163 * restrictions. Ask for an ack on the last packet sent in
6164 * this burst. For now, we're relying upon the window being
6165 * considerably bigger than the largest number of packets that
6166 * are typically sent at once by one initial call to
6167 * rxi_Start. This is probably bogus (perhaps we should ask
6168 * for an ack when we're half way through the current
6169 * window?). Also, for non file transfer applications, this
6170 * may end up asking for an ack for every packet. Bogus. XXXX
6173 * But check whether we're here recursively, and let the other guy
6176 #ifdef RX_ENABLE_LOCKS
6177 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6178 call->flags |= RX_CALL_TQ_BUSY;
6180 #endif /* RX_ENABLE_LOCKS */
6182 #ifdef RX_ENABLE_LOCKS
6183 call->flags &= ~RX_CALL_NEED_START;
6184 #endif /* RX_ENABLE_LOCKS */
6186 maxXmitPackets = MIN(call->twind, call->cwind);
6187 for (opr_queue_Scan(&call->tq, cursor)) {
6189 = opr_queue_Entry(cursor, struct rx_packet, entry);
6191 if (p->flags & RX_PKTFLAG_ACKED) {
6192 /* Since we may block, don't trust this */
6193 if (rx_stats_active)
6194 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6195 continue; /* Ignore this packet if it has been acknowledged */
6198 /* Turn off all flags except these ones, which are the same
6199 * on each transmission */
6200 p->header.flags &= RX_PRESET_FLAGS;
6202 if (p->header.seq >=
6203 call->tfirst + MIN((int)call->twind,
6204 (int)(call->nSoftAcked +
6206 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6207 /* Note: if we're waiting for more window space, we can
6208 * still send retransmits; hence we don't return here, but
6209 * break out to schedule a retransmit event */
6210 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6211 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6216 /* Transmit the packet if it needs to be sent. */
6217 if (!(p->flags & RX_PKTFLAG_SENT)) {
6218 if (nXmitPackets == maxXmitPackets) {
6219 rxi_SendXmitList(call, call->xmitList,
6220 nXmitPackets, istack);
6223 dpf(("call %d xmit packet %p\n",
6224 *(call->callNumber), p));
6225 call->xmitList[nXmitPackets++] = p;
6227 } /* end of the queue_Scan */
6229 /* xmitList now hold pointers to all of the packets that are
6230 * ready to send. Now we loop to send the packets */
6231 if (nXmitPackets > 0) {
6232 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6236 #ifdef RX_ENABLE_LOCKS
6238 /* We went into the error state while sending packets. Now is
6239 * the time to reset the call. This will also inform the using
6240 * process that the call is in an error state.
6242 if (rx_stats_active)
6243 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6244 call->flags &= ~RX_CALL_TQ_BUSY;
6245 rxi_WakeUpTransmitQueue(call);
6246 rxi_CallError(call, call->error);
6250 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6252 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6253 /* Some packets have received acks. If they all have, we can clear
6254 * the transmit queue.
6257 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6259 = opr_queue_Entry(cursor, struct rx_packet, entry);
6261 if (p->header.seq < call->tfirst
6262 && (p->flags & RX_PKTFLAG_ACKED)) {
6263 opr_queue_Remove(&p->entry);
6264 #ifdef RX_TRACK_PACKETS
6265 p->flags &= ~RX_PKTFLAG_TQ;
6267 #ifdef RXDEBUG_PACKET
6275 call->flags |= RX_CALL_TQ_CLEARME;
6277 if (call->flags & RX_CALL_TQ_CLEARME)
6278 rxi_ClearTransmitQueue(call, 1);
6279 } while (call->flags & RX_CALL_NEED_START);
6281 * TQ references no longer protected by this flag; they must remain
6282 * protected by the call lock.
6284 call->flags &= ~RX_CALL_TQ_BUSY;
6285 rxi_WakeUpTransmitQueue(call);
6287 call->flags |= RX_CALL_NEED_START;
6289 #endif /* RX_ENABLE_LOCKS */
6291 rxi_rto_cancel(call);
6295 /* Also adjusts the keep alive parameters for the call, to reflect
6296 * that we have just sent a packet (so keep alives aren't sent
6299 rxi_Send(struct rx_call *call, struct rx_packet *p,
6303 struct rx_connection *conn = call->conn;
6305 /* Stamp each packet with the user supplied status */
6306 p->header.userStatus = call->localStatus;
6308 /* Allow the security object controlling this call's security to
6309 * make any last-minute changes to the packet */
6310 code = RXS_SendPacket(conn->securityObject, call, p);
6312 MUTEX_EXIT(&call->lock);
6313 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6314 rxi_ConnectionError(conn, code);
6315 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6316 MUTEX_ENTER(&call->lock);
6320 /* Since we're about to send SOME sort of packet to the peer, it's
6321 * safe to nuke any scheduled end-of-packets ack */
6322 rxi_CancelDelayedAckEvent(call);
6324 /* Actually send the packet, filling in more connection-specific fields */
6325 MUTEX_EXIT(&call->lock);
6326 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6327 rxi_SendPacket(call, conn, p, istack);
6328 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6329 MUTEX_ENTER(&call->lock);
6331 /* Update last send time for this call (for keep-alive
6332 * processing), and for the connection (so that we can discover
6333 * idle connections) */
6334 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6335 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6336 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6338 conn->lastSendTime = call->lastSendTime = clock_Sec();
6342 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6343 * that things are fine. Also called periodically to guarantee that nothing
6344 * falls through the cracks (e.g. (error + dally) connections have keepalive
6345 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6347 * haveCTLock Set if calling from rxi_ReapConnections
6350 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6352 struct rx_connection *conn = call->conn;
6354 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6355 afs_uint32 fudgeFactor;
6358 int idle_timeout = 0;
6359 afs_int32 clock_diff = 0;
6361 if (rxi_CheckPeerDead(call)) {
6367 /* Large swings in the clock can have a significant impact on
6368 * the performance of RX call processing. Forward clock shifts
6369 * will result in premature event triggering or timeouts.
6370 * Backward shifts can result in calls not completing until
6371 * the clock catches up with the original start clock value.
6373 * If a backward clock shift of more than five minutes is noticed,
6374 * just fail the call.
6376 if (now < call->lastSendTime)
6377 clock_diff = call->lastSendTime - now;
6378 if (now < call->startWait)
6379 clock_diff = MAX(clock_diff, call->startWait - now);
6380 if (now < call->lastReceiveTime)
6381 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6382 if (clock_diff > 5 * 60)
6384 if (call->state == RX_STATE_ACTIVE)
6385 rxi_CallError(call, RX_CALL_TIMEOUT);
6389 #ifdef RX_ENABLE_LOCKS
6390 if (call->flags & RX_CALL_TQ_BUSY) {
6391 /* Call is active and will be reset by rxi_Start if it's
6392 * in an error state.
6397 /* RTT + 8*MDEV, rounded up to the next second. */
6398 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6399 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6401 deadTime = conn->secondsUntilDead + fudgeFactor;
6402 /* These are computed to the second (+- 1 second). But that's
6403 * good enough for these values, which should be a significant
6404 * number of seconds. */
6405 if (now > (call->lastReceiveTime + deadTime)) {
6406 if (call->state == RX_STATE_ACTIVE) {
6407 cerror = RX_CALL_DEAD;
6410 #ifdef RX_ENABLE_LOCKS
6411 /* Cancel pending events */
6412 rxi_CancelDelayedAckEvent(call);
6413 rxi_rto_cancel(call);
6414 rxi_CancelKeepAliveEvent(call);
6415 rxi_CancelGrowMTUEvent(call);
6416 MUTEX_ENTER(&rx_refcnt_mutex);
6417 /* if rxi_FreeCall returns 1 it has freed the call */
6418 if (call->refCount == 0 &&
6419 rxi_FreeCall(call, haveCTLock))
6421 MUTEX_EXIT(&rx_refcnt_mutex);
6424 MUTEX_EXIT(&rx_refcnt_mutex);
6426 #else /* RX_ENABLE_LOCKS */
6427 rxi_FreeCall(call, 0);
6429 #endif /* RX_ENABLE_LOCKS */
6431 /* Non-active calls are destroyed if they are not responding
6432 * to pings; active calls are simply flagged in error, so the
6433 * attached process can die reasonably gracefully. */
6436 if (conn->idleDeadTime) {
6437 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6441 /* see if we have a non-activity timeout */
6442 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6443 if (call->state == RX_STATE_ACTIVE) {
6444 cerror = RX_CALL_TIMEOUT;
6450 if (conn->hardDeadTime) {
6451 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6454 /* see if we have a hard timeout */
6456 && (now > (hardDeadTime + call->startTime.sec))) {
6457 if (call->state == RX_STATE_ACTIVE)
6458 rxi_CallError(call, RX_CALL_TIMEOUT);
6463 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6464 call->lastReceiveTime) {
6465 int oldMTU = conn->peer->ifMTU;
6467 /* If we thought we could send more, perhaps things got worse.
6468 * Shrink by 128 bytes and try again. */
6469 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6470 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6471 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6472 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6474 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6476 /* minimum capped in SetPeerMtu */
6477 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6480 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6482 /* needed so ResetCall doesn't clobber us. */
6483 call->MTU = conn->peer->ifMTU;
6485 /* if we never succeeded, let the error pass out as-is */
6486 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6487 cerror = conn->msgsizeRetryErr;
6490 rxi_CallError(call, cerror);
6495 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6496 void *dummy, int dummy2)
6498 struct rx_connection *conn = arg1;
6499 struct rx_header theader;
6500 char tbuffer[1 + sizeof(struct rx_header)];
6501 struct sockaddr_in taddr;
6505 struct iovec tmpiov[2];
6508 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6511 tp = &tbuffer[sizeof(struct rx_header)];
6512 taddr.sin_family = AF_INET;
6513 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6514 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6515 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6516 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6517 taddr.sin_len = sizeof(struct sockaddr_in);
6519 memset(&theader, 0, sizeof(theader));
6520 theader.epoch = htonl(999);
6522 theader.callNumber = 0;
6525 theader.type = RX_PACKET_TYPE_VERSION;
6526 theader.flags = RX_LAST_PACKET;
6527 theader.serviceId = 0;
6529 memcpy(tbuffer, &theader, sizeof(theader));
6530 memcpy(tp, &a, sizeof(a));
6531 tmpiov[0].iov_base = tbuffer;
6532 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6534 rxi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6536 MUTEX_ENTER(&conn->conn_data_lock);
6537 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6538 if (event == conn->natKeepAliveEvent)
6539 rxevent_Put(&conn->natKeepAliveEvent);
6540 MUTEX_ENTER(&rx_refcnt_mutex);
6541 /* Only reschedule ourselves if the connection would not be destroyed */
6542 if (conn->refCount > 1)
6544 if (conn->refCount <= 0) {
6545 #ifdef RX_REFCOUNT_CHECK
6546 osi_Assert(conn->refCount == 0);
6548 if (rx_stats_active) {
6549 MUTEX_ENTER(&rx_stats_mutex);
6550 rxi_lowConnRefCount++;
6551 MUTEX_EXIT(&rx_stats_mutex);
6554 MUTEX_EXIT(&rx_refcnt_mutex);
6556 rxi_ScheduleNatKeepAliveEvent(conn);
6557 MUTEX_EXIT(&conn->conn_data_lock);
6558 putConnection(conn);
6562 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6564 MUTEX_ASSERT(&conn->conn_data_lock);
6565 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6566 struct clock when, now;
6567 clock_GetTime(&now);
6569 when.sec += conn->secondsUntilNatPing;
6570 rx_GetConnection(conn);
6571 conn->natKeepAliveEvent =
6572 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6577 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6579 MUTEX_ENTER(&conn->conn_data_lock);
6580 conn->secondsUntilNatPing = seconds;
6582 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6583 rxi_ScheduleNatKeepAliveEvent(conn);
6585 conn->flags |= RX_CONN_NAT_PING;
6587 MUTEX_EXIT(&conn->conn_data_lock);
6590 /* When a call is in progress, this routine is called occasionally to
6591 * make sure that some traffic has arrived (or been sent to) the peer.
6592 * If nothing has arrived in a reasonable amount of time, the call is
6593 * declared dead; if nothing has been sent for a while, we send a
6594 * keep-alive packet (if we're actually trying to keep the call alive)
6597 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6600 struct rx_call *call = arg1;
6601 struct rx_connection *conn;
6604 MUTEX_ENTER(&call->lock);
6606 if (event == call->keepAliveEvent)
6607 rxevent_Put(&call->keepAliveEvent);
6611 if (rxi_CheckCall(call, 0)) {
6612 MUTEX_EXIT(&call->lock);
6613 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6617 /* Don't try to keep alive dallying calls */
6618 if (call->state == RX_STATE_DALLY) {
6619 MUTEX_EXIT(&call->lock);
6620 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6625 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6626 /* Don't try to send keepalives if there is unacknowledged data */
6627 /* the rexmit code should be good enough, this little hack
6628 * doesn't quite work XXX */
6629 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6631 rxi_ScheduleKeepAliveEvent(call);
6632 MUTEX_EXIT(&call->lock);
6633 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6636 /* Does what's on the nameplate. */
6638 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6640 struct rx_call *call = arg1;
6641 struct rx_connection *conn;
6643 MUTEX_ENTER(&call->lock);
6645 if (event == call->growMTUEvent)
6646 rxevent_Put(&call->growMTUEvent);
6648 if (rxi_CheckCall(call, 0))
6651 /* Don't bother with dallying calls */
6652 if (call->state == RX_STATE_DALLY)
6658 * keep being scheduled, just don't do anything if we're at peak,
6659 * or we're not set up to be properly handled (idle timeout required)
6661 if ((conn->peer->maxPacketSize != 0) &&
6662 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6664 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6665 rxi_ScheduleGrowMTUEvent(call, 0);
6667 MUTEX_EXIT(&call->lock);
6668 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6672 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6674 MUTEX_ASSERT(&call->lock);
6675 if (!call->keepAliveEvent) {
6676 struct clock when, now;
6677 clock_GetTime(&now);
6679 when.sec += call->conn->secondsUntilPing;
6680 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6681 call->keepAliveEvent =
6682 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6687 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6688 MUTEX_ASSERT(&call->lock);
6689 if (rxevent_Cancel(&call->keepAliveEvent))
6690 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6694 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6696 MUTEX_ASSERT(&call->lock);
6697 if (!call->growMTUEvent) {
6698 struct clock when, now;
6700 clock_GetTime(&now);
6703 if (call->conn->secondsUntilPing)
6704 secs = (6*call->conn->secondsUntilPing)-1;
6706 if (call->conn->secondsUntilDead)
6707 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6711 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6712 call->growMTUEvent =
6713 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6718 rxi_CancelGrowMTUEvent(struct rx_call *call)
6720 MUTEX_ASSERT(&call->lock);
6721 if (rxevent_Cancel(&call->growMTUEvent))
6722 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6726 * Increment the counter for the next connection ID, handling overflow.
6729 update_nextCid(void)
6731 /* Overflow is technically undefined behavior; avoid it. */
6732 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6733 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6735 rx_nextCid += 1 << RX_CIDSHIFT;
6739 rxi_KeepAliveOn(struct rx_call *call)
6741 /* Pretend last packet received was received now--i.e. if another
6742 * packet isn't received within the keep alive time, then the call
6743 * will die; Initialize last send time to the current time--even
6744 * if a packet hasn't been sent yet. This will guarantee that a
6745 * keep-alive is sent within the ping time */
6746 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6747 rxi_ScheduleKeepAliveEvent(call);
6751 rxi_GrowMTUOn(struct rx_call *call)
6753 struct rx_connection *conn = call->conn;
6754 MUTEX_ENTER(&conn->conn_data_lock);
6755 conn->lastPingSizeSer = conn->lastPingSize = 0;
6756 MUTEX_EXIT(&conn->conn_data_lock);
6757 rxi_ScheduleGrowMTUEvent(call, 1);
6760 /* This routine is called to send connection abort messages
6761 * that have been delayed to throttle looping clients. */
6763 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6766 struct rx_connection *conn = arg1;
6769 struct rx_packet *packet;
6771 MUTEX_ENTER(&conn->conn_data_lock);
6772 if (event == conn->delayedAbortEvent)
6773 rxevent_Put(&conn->delayedAbortEvent);
6774 error = htonl(conn->error);
6776 MUTEX_EXIT(&conn->conn_data_lock);
6777 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6780 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6781 RX_PACKET_TYPE_ABORT, (char *)&error,
6783 rxi_FreePacket(packet);
6785 putConnection(conn);
6788 /* This routine is called to send call abort messages
6789 * that have been delayed to throttle looping clients. */
6791 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6794 struct rx_call *call = arg1;
6797 struct rx_packet *packet;
6799 MUTEX_ENTER(&call->lock);
6800 if (event == call->delayedAbortEvent)
6801 rxevent_Put(&call->delayedAbortEvent);
6802 error = htonl(call->error);
6804 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6807 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6808 (char *)&error, sizeof(error), 0);
6809 rxi_FreePacket(packet);
6811 MUTEX_EXIT(&call->lock);
6812 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6816 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6817 * seconds) to ask the client to authenticate itself. The routine
6818 * issues a challenge to the client, which is obtained from the
6819 * security object associated with the connection
6821 * This routine is both an event handler and a function called directly;
6822 * when called directly the passed |event| is NULL and the
6823 * conn->conn->data>lock must must not be held. Also, when called as an
6824 * an event handler, we must putConnection before we exit; but when called
6825 * directly (the first challenge), we must NOT putConnection.
6828 rxi_ChallengeEvent(struct rxevent *event,
6829 void *arg0, void *arg1, int tries)
6831 struct rx_connection *conn = arg0;
6832 int event_raised = 0; /* assume we were called directly */
6834 MUTEX_ENTER(&conn->conn_data_lock);
6835 if (event != NULL && event == conn->challengeEvent) {
6836 event_raised = 1; /* called as an event */
6837 rxevent_Put(&conn->challengeEvent);
6839 MUTEX_EXIT(&conn->conn_data_lock);
6841 /* If there are no active calls it is not worth re-issuing the
6842 * challenge. If the client issues another call on this connection
6843 * the challenge can be requested at that time.
6845 if (!rxi_HasActiveCalls(conn))
6848 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6849 struct rx_packet *packet;
6850 struct clock when, now;
6853 /* We've failed to authenticate for too long.
6854 * Reset any calls waiting for authentication;
6855 * they are all in RX_STATE_PRECALL.
6859 MUTEX_ENTER(&conn->conn_call_lock);
6860 for (i = 0; i < RX_MAXCALLS; i++) {
6861 struct rx_call *call = conn->call[i];
6863 MUTEX_ENTER(&call->lock);
6864 if (call->state == RX_STATE_PRECALL) {
6865 rxi_CallError(call, RX_CALL_DEAD);
6866 rxi_SendCallAbort(call, NULL, 0, 0);
6868 MUTEX_EXIT(&call->lock);
6871 MUTEX_EXIT(&conn->conn_call_lock);
6875 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6878 code = RXS_GetChallenge(conn->securityObject, conn, packet);
6879 if (code && event_raised) {
6881 * We can only rxi_ConnectionError the connection if we are
6882 * running as an event. Otherwise, the caller may have our call
6883 * locked, and so we cannot call rxi_ConnectionError (since it
6884 * tries to lock each call in the conn).
6886 rxi_FreePacket(packet);
6887 rxi_ConnectionError(conn, code);
6891 /* Only send a challenge packet if we were able to allocate a
6892 * packet, and the security layer successfully populated the
6894 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6895 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6896 conn->securityChallengeSent = 1;
6898 rxi_FreePacket(packet);
6900 clock_GetTime(&now);
6902 when.sec += RX_CHALLENGE_TIMEOUT;
6903 MUTEX_ENTER(&conn->conn_data_lock);
6904 /* Only reschedule ourselves if not already pending. */
6905 if (conn->challengeEvent == NULL) {
6906 rx_GetConnection(conn);
6907 conn->challengeEvent =
6908 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6911 MUTEX_EXIT(&conn->conn_data_lock);
6915 putConnection(conn);
6918 /* Call this routine to start requesting the client to authenticate
6919 * itself. This will continue until authentication is established,
6920 * the call times out, or an invalid response is returned. The
6921 * security object associated with the connection is asked to create
6922 * the challenge at this time. */
6924 rxi_ChallengeOn(struct rx_connection *conn)
6927 MUTEX_ENTER(&conn->conn_data_lock);
6928 if (!conn->challengeEvent)
6930 MUTEX_EXIT(&conn->conn_data_lock);
6933 code = RXS_CreateChallenge(conn->securityObject, conn);
6937 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6943 /* rxi_ComputeRoundTripTime is called with peer locked. */
6944 /* peer may be null */
6946 rxi_ComputeRoundTripTime(struct rx_packet *p,
6947 struct rx_ackPacket *ack,
6948 struct rx_call *call,
6949 struct rx_peer *peer,
6952 struct clock thisRtt, *sentp;
6956 /* If the ACK is delayed, then do nothing */
6957 if (ack->reason == RX_ACK_DELAY)
6960 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6961 * their RTT multiple times, so only include the RTT of the last packet
6963 if (p->flags & RX_JUMBO_PACKET)
6966 /* Use the serial number to determine which transmission the ACK is for,
6967 * and set the sent time to match this. If we have no serial number, then
6968 * only use the ACK for RTT calculations if the packet has not been
6972 serial = ntohl(ack->serial);
6974 if (serial == p->header.serial) {
6975 sentp = &p->timeSent;
6976 } else if (serial == p->firstSerial) {
6977 sentp = &p->firstSent;
6978 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6979 sentp = &p->firstSent;
6983 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6984 sentp = &p->firstSent;
6991 if (clock_Lt(&thisRtt, sentp))
6992 return; /* somebody set the clock back, don't count this time. */
6994 clock_Sub(&thisRtt, sentp);
6995 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rttp=%d.%06d sec)\n",
6996 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6998 if (clock_IsZero(&thisRtt)) {
7000 * The actual round trip time is shorter than the
7001 * clock_GetTime resolution. It is most likely 1ms or 100ns.
7002 * Since we can't tell which at the moment we will assume 1ms.
7004 thisRtt.usec = 1000;
7007 if (rx_stats_active) {
7008 MUTEX_ENTER(&rx_stats_mutex);
7009 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
7010 rx_stats.minRtt = thisRtt;
7011 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
7012 if (thisRtt.sec > 60) {
7013 MUTEX_EXIT(&rx_stats_mutex);
7014 return; /* somebody set the clock ahead */
7016 rx_stats.maxRtt = thisRtt;
7018 clock_Add(&rx_stats.totalRtt, &thisRtt);
7019 rx_atomic_inc(&rx_stats.nRttSamples);
7020 MUTEX_EXIT(&rx_stats_mutex);
7023 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
7025 /* Apply VanJacobson round-trip estimations */
7030 * srtt (call->rtt) is in units of one-eighth-milliseconds.
7031 * srtt is stored as fixed point with 3 bits after the binary
7032 * point (i.e., scaled by 8). The following magic is
7033 * equivalent to the smoothing algorithm in rfc793 with an
7034 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
7035 * srtt'*8 = rtt + srtt*7
7036 * srtt'*8 = srtt*8 + rtt - srtt
7037 * srtt' = srtt + rtt/8 - srtt/8
7038 * srtt' = srtt + (rtt - srtt)/8
7041 delta = _8THMSEC(&thisRtt) - call->rtt;
7042 call->rtt += (delta >> 3);
7045 * We accumulate a smoothed rtt variance (actually, a smoothed
7046 * mean difference), then set the retransmit timer to smoothed
7047 * rtt + 4 times the smoothed variance (was 2x in van's original
7048 * paper, but 4x works better for me, and apparently for him as
7050 * rttvar is stored as
7051 * fixed point with 2 bits after the binary point (scaled by
7052 * 4). The following is equivalent to rfc793 smoothing with
7053 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7054 * rttvar'*4 = rttvar*3 + |delta|
7055 * rttvar'*4 = rttvar*4 + |delta| - rttvar
7056 * rttvar' = rttvar + |delta|/4 - rttvar/4
7057 * rttvar' = rttvar + (|delta| - rttvar)/4
7058 * This replaces rfc793's wired-in beta.
7059 * dev*4 = dev*4 + (|actual - expected| - dev)
7065 delta -= (call->rtt_dev << 1);
7066 call->rtt_dev += (delta >> 3);
7068 /* I don't have a stored RTT so I start with this value. Since I'm
7069 * probably just starting a call, and will be pushing more data down
7070 * this, I expect congestion to increase rapidly. So I fudge a
7071 * little, and I set deviance to half the rtt. In practice,
7072 * deviance tends to approach something a little less than
7073 * half the smoothed rtt. */
7074 call->rtt = _8THMSEC(&thisRtt) + 8;
7075 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7077 /* the smoothed RTT time is RTT + 4*MDEV
7079 * We allow a user specified minimum to be set for this, to allow clamping
7080 * at a minimum value in the same way as TCP. In addition, we have to allow
7081 * for the possibility that this packet is answered by a delayed ACK, so we
7082 * add on a fixed 200ms to account for that timer expiring.
7085 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7086 rx_minPeerTimeout) + 200;
7087 clock_Zero(&call->rto);
7088 clock_Addmsec(&call->rto, rtt_timeout);
7090 /* Update the peer, so any new calls start with our values */
7091 peer->rtt_dev = call->rtt_dev;
7092 peer->rtt = call->rtt;
7094 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rtt=%d ms, srtt=%d ms, "
7095 "rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7096 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3,
7097 call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7101 /* Find all server connections that have not been active for a long time, and
7104 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7107 struct clock now, when;
7108 struct rxevent *event;
7109 clock_GetTime(&now);
7111 /* Find server connection structures that haven't been used for
7112 * greater than rx_idleConnectionTime */
7114 struct rx_connection **conn_ptr, **conn_end;
7115 int i, havecalls = 0;
7116 MUTEX_ENTER(&rx_connHashTable_lock);
7117 for (conn_ptr = &rx_connHashTable[0], conn_end =
7118 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7120 struct rx_connection *conn, *next;
7121 struct rx_call *call;
7125 for (conn = *conn_ptr; conn; conn = next) {
7126 /* XXX -- Shouldn't the connection be locked? */
7129 for (i = 0; i < RX_MAXCALLS; i++) {
7130 call = conn->call[i];
7134 code = MUTEX_TRYENTER(&call->lock);
7137 result = rxi_CheckCall(call, 1);
7138 MUTEX_EXIT(&call->lock);
7140 /* If CheckCall freed the call, it might
7141 * have destroyed the connection as well,
7142 * which screws up the linked lists.
7148 if (conn->type == RX_SERVER_CONNECTION) {
7149 /* This only actually destroys the connection if
7150 * there are no outstanding calls */
7151 MUTEX_ENTER(&conn->conn_data_lock);
7152 MUTEX_ENTER(&rx_refcnt_mutex);
7153 if (!havecalls && !conn->refCount
7154 && ((conn->lastSendTime + rx_idleConnectionTime) <
7156 conn->refCount++; /* it will be decr in rx_DestroyConn */
7157 MUTEX_EXIT(&rx_refcnt_mutex);
7158 MUTEX_EXIT(&conn->conn_data_lock);
7159 #ifdef RX_ENABLE_LOCKS
7160 rxi_DestroyConnectionNoLock(conn);
7161 #else /* RX_ENABLE_LOCKS */
7162 rxi_DestroyConnection(conn);
7163 #endif /* RX_ENABLE_LOCKS */
7165 #ifdef RX_ENABLE_LOCKS
7167 MUTEX_EXIT(&rx_refcnt_mutex);
7168 MUTEX_EXIT(&conn->conn_data_lock);
7170 #endif /* RX_ENABLE_LOCKS */
7174 #ifdef RX_ENABLE_LOCKS
7175 while (rx_connCleanup_list) {
7176 struct rx_connection *conn;
7177 conn = rx_connCleanup_list;
7178 rx_connCleanup_list = rx_connCleanup_list->next;
7179 MUTEX_EXIT(&rx_connHashTable_lock);
7180 rxi_CleanupConnection(conn);
7181 MUTEX_ENTER(&rx_connHashTable_lock);
7183 MUTEX_EXIT(&rx_connHashTable_lock);
7184 #endif /* RX_ENABLE_LOCKS */
7187 /* Find any peer structures that haven't been used (haven't had an
7188 * associated connection) for greater than rx_idlePeerTime */
7190 struct rx_peer **peer_ptr, **peer_end;
7194 * Why do we need to hold the rx_peerHashTable_lock across
7195 * the incrementing of peer_ptr since the rx_peerHashTable
7196 * array is not changing? We don't.
7198 * By dropping the lock periodically we can permit other
7199 * activities to be performed while a rxi_ReapConnections
7200 * call is in progress. The goal of reap connections
7201 * is to clean up quickly without causing large amounts
7202 * of contention. Therefore, it is important that global
7203 * mutexes not be held for extended periods of time.
7205 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7206 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7208 struct rx_peer *peer, *next, *prev;
7210 MUTEX_ENTER(&rx_peerHashTable_lock);
7211 for (prev = peer = *peer_ptr; peer; peer = next) {
7213 code = MUTEX_TRYENTER(&peer->peer_lock);
7214 if ((code) && (peer->refCount == 0)
7215 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7216 struct opr_queue *cursor, *store;
7220 * now know that this peer object is one to be
7221 * removed from the hash table. Once it is removed
7222 * it can't be referenced by other threads.
7223 * Lets remove it first and decrement the struct
7224 * nPeerStructs count.
7226 if (peer == *peer_ptr) {
7232 if (rx_stats_active)
7233 rx_atomic_dec(&rx_stats.nPeerStructs);
7236 * Now if we hold references on 'prev' and 'next'
7237 * we can safely drop the rx_peerHashTable_lock
7238 * while we destroy this 'peer' object.
7244 MUTEX_EXIT(&rx_peerHashTable_lock);
7246 MUTEX_EXIT(&peer->peer_lock);
7247 MUTEX_DESTROY(&peer->peer_lock);
7249 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7250 unsigned int num_funcs;
7251 struct rx_interface_stat *rpc_stat
7252 = opr_queue_Entry(cursor, struct rx_interface_stat,
7257 opr_queue_Remove(&rpc_stat->entry);
7258 opr_queue_Remove(&rpc_stat->entryPeers);
7260 num_funcs = rpc_stat->stats[0].func_total;
7262 sizeof(rx_interface_stat_t) +
7263 rpc_stat->stats[0].func_total *
7264 sizeof(rx_function_entry_v1_t);
7266 rxi_Free(rpc_stat, space);
7268 MUTEX_ENTER(&rx_rpc_stats);
7269 rxi_rpc_peer_stat_cnt -= num_funcs;
7270 MUTEX_EXIT(&rx_rpc_stats);
7275 * Regain the rx_peerHashTable_lock and
7276 * decrement the reference count on 'prev'
7279 MUTEX_ENTER(&rx_peerHashTable_lock);
7286 MUTEX_EXIT(&peer->peer_lock);
7291 MUTEX_EXIT(&rx_peerHashTable_lock);
7295 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7296 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7297 * GC, just below. Really, we shouldn't have to keep moving packets from
7298 * one place to another, but instead ought to always know if we can
7299 * afford to hold onto a packet in its particular use. */
7300 MUTEX_ENTER(&rx_freePktQ_lock);
7301 if (rx_waitingForPackets) {
7302 rx_waitingForPackets = 0;
7303 #ifdef RX_ENABLE_LOCKS
7304 CV_BROADCAST(&rx_waitingForPackets_cv);
7306 osi_rxWakeup(&rx_waitingForPackets);
7309 MUTEX_EXIT(&rx_freePktQ_lock);
7312 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7313 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7314 rxevent_Put(&event);
7318 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7319 * rx.h is sort of strange this is better. This is called with a security
7320 * object before it is discarded. Each connection using a security object has
7321 * its own refcount to the object so it won't actually be freed until the last
7322 * connection is destroyed.
7324 * This is the only rxs module call. A hold could also be written but no one
7328 rxs_Release(struct rx_securityClass *aobj)
7330 return RXS_Close(aobj);
7338 #define TRACE_OPTION_RX_DEBUG 16
7346 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7347 0, KEY_QUERY_VALUE, &parmKey);
7348 if (code != ERROR_SUCCESS)
7351 dummyLen = sizeof(TraceOption);
7352 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7353 (BYTE *) &TraceOption, &dummyLen);
7354 if (code == ERROR_SUCCESS) {
7355 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7357 RegCloseKey (parmKey);
7358 #endif /* AFS_NT40_ENV */
7363 rx_DebugOnOff(int on)
7367 rxdebug_active = on;
7373 rx_StatsOnOff(int on)
7375 rx_stats_active = on;
7379 /* Don't call this debugging routine directly; use dpf */
7381 rxi_DebugPrint(char *format, ...)
7390 va_start(ap, format);
7392 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7395 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7397 OutputDebugString(msg);
7403 va_start(ap, format);
7405 clock_GetTime(&now);
7406 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7407 (unsigned int)now.usec);
7408 vfprintf(rx_Log, format, ap);
7416 * This function is used to process the rx_stats structure that is local
7417 * to a process as well as an rx_stats structure received from a remote
7418 * process (via rxdebug). Therefore, it needs to do minimal version
7422 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7423 afs_int32 freePackets, char version)
7427 if (size != sizeof(struct rx_statistics)) {
7429 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7430 size, sizeof(struct rx_statistics));
7433 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7436 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7437 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7438 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7439 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7440 s->specialPktAllocFailures);
7442 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7443 s->receivePktAllocFailures, s->sendPktAllocFailures,
7444 s->specialPktAllocFailures);
7448 " greedy %u, " "bogusReads %u (last from host %x), "
7449 "noPackets %u, " "noBuffers %u, " "selects %u, "
7450 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7451 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7452 s->selects, s->sendSelects);
7454 fprintf(file, " packets read: ");
7455 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7456 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7458 fprintf(file, "\n");
7461 " other read counters: data %u, " "ack %u, " "dup %u "
7462 "spurious %u " "dally %u\n", s->dataPacketsRead,
7463 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7464 s->ignorePacketDally);
7466 fprintf(file, " packets sent: ");
7467 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7468 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7470 fprintf(file, "\n");
7473 " other send counters: ack %u, " "data %u (not resends), "
7474 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7475 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7476 s->dataPacketsPushed, s->ignoreAckedPacket);
7479 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7480 s->netSendFailures, (int)s->fatalErrors);
7482 if (s->nRttSamples) {
7483 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7484 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7486 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7487 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7491 " %d server connections, " "%d client connections, "
7492 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7493 s->nServerConns, s->nClientConns, s->nPeerStructs,
7494 s->nCallStructs, s->nFreeCallStructs);
7496 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7497 fprintf(file, " %d clock updates\n", clock_nUpdates);
7501 /* for backward compatibility */
7503 rx_PrintStats(FILE * file)
7505 MUTEX_ENTER(&rx_stats_mutex);
7506 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7507 sizeof(rx_stats), rx_nFreePackets,
7509 MUTEX_EXIT(&rx_stats_mutex);
7513 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7515 fprintf(file, "Peer %x.%d.\n",
7516 ntohl(peer->host), (int)ntohs(peer->port));
7519 " Rtt %d, " "total sent %d, " "resent %d\n",
7520 peer->rtt, peer->nSent, peer->reSends);
7522 fprintf(file, " Packet size %d\n", peer->ifMTU);
7526 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7528 * This mutex protects the following static variables:
7532 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7533 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7535 #define LOCK_RX_DEBUG
7536 #define UNLOCK_RX_DEBUG
7537 #endif /* AFS_PTHREAD_ENV */
7539 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7541 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7542 u_char type, void *inputData, size_t inputLength,
7543 void *outputData, size_t outputLength)
7545 static afs_int32 counter = 100;
7546 time_t waitTime, waitCount;
7547 struct rx_header theader;
7550 struct timeval tv_now, tv_wake, tv_delta;
7551 struct sockaddr_in taddr, faddr;
7565 tp = &tbuffer[sizeof(struct rx_header)];
7566 taddr.sin_family = AF_INET;
7567 taddr.sin_port = remotePort;
7568 taddr.sin_addr.s_addr = remoteAddr;
7569 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7570 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7571 taddr.sin_len = sizeof(struct sockaddr_in);
7574 memset(&theader, 0, sizeof(theader));
7575 theader.epoch = htonl(999);
7577 theader.callNumber = htonl(counter);
7580 theader.type = type;
7581 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7582 theader.serviceId = 0;
7584 memcpy(tbuffer, &theader, sizeof(theader));
7585 memcpy(tp, inputData, inputLength);
7587 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7588 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7590 /* see if there's a packet available */
7591 gettimeofday(&tv_wake, NULL);
7592 tv_wake.tv_sec += waitTime;
7595 FD_SET(socket, &imask);
7596 tv_delta.tv_sec = tv_wake.tv_sec;
7597 tv_delta.tv_usec = tv_wake.tv_usec;
7598 gettimeofday(&tv_now, NULL);
7600 if (tv_delta.tv_usec < tv_now.tv_usec) {
7602 tv_delta.tv_usec += 1000000;
7605 tv_delta.tv_usec -= tv_now.tv_usec;
7607 if (tv_delta.tv_sec < tv_now.tv_sec) {
7611 tv_delta.tv_sec -= tv_now.tv_sec;
7614 code = select(0, &imask, 0, 0, &tv_delta);
7615 #else /* AFS_NT40_ENV */
7616 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7617 #endif /* AFS_NT40_ENV */
7618 if (code == 1 && FD_ISSET(socket, &imask)) {
7619 /* now receive a packet */
7620 faddrLen = sizeof(struct sockaddr_in);
7622 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7623 (struct sockaddr *)&faddr, &faddrLen);
7626 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7627 if (counter == ntohl(theader.callNumber))
7635 /* see if we've timed out */
7643 code -= sizeof(struct rx_header);
7644 if (code > outputLength)
7645 code = outputLength;
7646 memcpy(outputData, tp, code);
7649 #endif /* RXDEBUG */
7652 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7653 afs_uint16 remotePort, struct rx_debugStats * stat,
7654 afs_uint32 * supportedValues)
7656 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7658 struct rx_debugIn in;
7660 *supportedValues = 0;
7661 in.type = htonl(RX_DEBUGI_GETSTATS);
7664 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7665 &in, sizeof(in), stat, sizeof(*stat));
7668 * If the call was successful, fixup the version and indicate
7669 * what contents of the stat structure are valid.
7670 * Also do net to host conversion of fields here.
7674 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7675 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7677 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7678 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7680 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7681 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7683 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7684 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7686 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7687 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7689 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7690 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7692 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7693 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7695 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7696 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7698 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7699 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7701 stat->nFreePackets = ntohl(stat->nFreePackets);
7702 stat->packetReclaims = ntohl(stat->packetReclaims);
7703 stat->callsExecuted = ntohl(stat->callsExecuted);
7704 stat->nWaiting = ntohl(stat->nWaiting);
7705 stat->idleThreads = ntohl(stat->idleThreads);
7706 stat->nWaited = ntohl(stat->nWaited);
7707 stat->nPackets = ntohl(stat->nPackets);
7716 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7717 afs_uint16 remotePort, struct rx_statistics * stat,
7718 afs_uint32 * supportedValues)
7720 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7722 struct rx_debugIn in;
7723 afs_int32 *lp = (afs_int32 *) stat;
7727 * supportedValues is currently unused, but added to allow future
7728 * versioning of this function.
7731 *supportedValues = 0;
7732 in.type = htonl(RX_DEBUGI_RXSTATS);
7734 memset(stat, 0, sizeof(*stat));
7736 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7737 &in, sizeof(in), stat, sizeof(*stat));
7742 * Do net to host conversion here
7745 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7756 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7757 afs_uint16 remotePort, size_t version_length,
7760 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7762 return MakeDebugCall(socket, remoteAddr, remotePort,
7763 RX_PACKET_TYPE_VERSION, a, 1, version,
7771 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7772 afs_uint16 remotePort, afs_int32 * nextConnection,
7773 int allConnections, afs_uint32 debugSupportedValues,
7774 struct rx_debugConn * conn,
7775 afs_uint32 * supportedValues)
7777 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7779 struct rx_debugIn in;
7783 * supportedValues is currently unused, but added to allow future
7784 * versioning of this function.
7787 *supportedValues = 0;
7788 if (allConnections) {
7789 in.type = htonl(RX_DEBUGI_GETALLCONN);
7791 in.type = htonl(RX_DEBUGI_GETCONN);
7793 in.index = htonl(*nextConnection);
7794 memset(conn, 0, sizeof(*conn));
7796 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7797 &in, sizeof(in), conn, sizeof(*conn));
7800 *nextConnection += 1;
7803 * Convert old connection format to new structure.
7806 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7807 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7808 #define MOVEvL(a) (conn->a = vL->a)
7810 /* any old or unrecognized version... */
7811 for (i = 0; i < RX_MAXCALLS; i++) {
7812 MOVEvL(callState[i]);
7813 MOVEvL(callMode[i]);
7814 MOVEvL(callFlags[i]);
7815 MOVEvL(callOther[i]);
7817 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7818 MOVEvL(secStats.type);
7819 MOVEvL(secStats.level);
7820 MOVEvL(secStats.flags);
7821 MOVEvL(secStats.expires);
7822 MOVEvL(secStats.packetsReceived);
7823 MOVEvL(secStats.packetsSent);
7824 MOVEvL(secStats.bytesReceived);
7825 MOVEvL(secStats.bytesSent);
7830 * Do net to host conversion here
7832 * I don't convert host or port since we are most likely
7833 * going to want these in NBO.
7835 conn->cid = ntohl(conn->cid);
7836 conn->serial = ntohl(conn->serial);
7837 for (i = 0; i < RX_MAXCALLS; i++) {
7838 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7840 conn->error = ntohl(conn->error);
7841 conn->secStats.flags = ntohl(conn->secStats.flags);
7842 conn->secStats.expires = ntohl(conn->secStats.expires);
7843 conn->secStats.packetsReceived =
7844 ntohl(conn->secStats.packetsReceived);
7845 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7846 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7847 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7848 conn->epoch = ntohl(conn->epoch);
7849 conn->natMTU = ntohl(conn->natMTU);
7858 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7859 afs_uint16 remotePort, afs_int32 * nextPeer,
7860 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7861 afs_uint32 * supportedValues)
7863 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7865 struct rx_debugIn in;
7868 * supportedValues is currently unused, but added to allow future
7869 * versioning of this function.
7872 *supportedValues = 0;
7873 in.type = htonl(RX_DEBUGI_GETPEER);
7874 in.index = htonl(*nextPeer);
7875 memset(peer, 0, sizeof(*peer));
7877 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7878 &in, sizeof(in), peer, sizeof(*peer));
7884 * Do net to host conversion here
7886 * I don't convert host or port since we are most likely
7887 * going to want these in NBO.
7889 peer->ifMTU = ntohs(peer->ifMTU);
7890 peer->idleWhen = ntohl(peer->idleWhen);
7891 peer->refCount = ntohs(peer->refCount);
7892 peer->rtt = ntohl(peer->rtt);
7893 peer->rtt_dev = ntohl(peer->rtt_dev);
7894 peer->timeout.sec = 0;
7895 peer->timeout.usec = 0;
7896 peer->nSent = ntohl(peer->nSent);
7897 peer->reSends = ntohl(peer->reSends);
7898 peer->natMTU = ntohs(peer->natMTU);
7899 peer->maxMTU = ntohs(peer->maxMTU);
7900 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7901 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7902 peer->MTU = ntohs(peer->MTU);
7903 peer->cwind = ntohs(peer->cwind);
7904 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7905 peer->congestSeq = ntohs(peer->congestSeq);
7906 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7907 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7908 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7909 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7918 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7919 struct rx_debugPeer * peerStats)
7922 afs_int32 error = 1; /* default to "did not succeed" */
7923 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7925 MUTEX_ENTER(&rx_peerHashTable_lock);
7926 for(tp = rx_peerHashTable[hashValue];
7927 tp != NULL; tp = tp->next) {
7928 if (tp->host == peerHost)
7934 MUTEX_EXIT(&rx_peerHashTable_lock);
7938 MUTEX_ENTER(&tp->peer_lock);
7939 peerStats->host = tp->host;
7940 peerStats->port = tp->port;
7941 peerStats->ifMTU = tp->ifMTU;
7942 peerStats->idleWhen = tp->idleWhen;
7943 peerStats->refCount = tp->refCount;
7944 peerStats->burstSize = 0;
7945 peerStats->burst = 0;
7946 peerStats->burstWait.sec = 0;
7947 peerStats->burstWait.usec = 0;
7948 peerStats->rtt = tp->rtt;
7949 peerStats->rtt_dev = tp->rtt_dev;
7950 peerStats->timeout.sec = 0;
7951 peerStats->timeout.usec = 0;
7952 peerStats->nSent = tp->nSent;
7953 peerStats->reSends = tp->reSends;
7954 peerStats->natMTU = tp->natMTU;
7955 peerStats->maxMTU = tp->maxMTU;
7956 peerStats->maxDgramPackets = tp->maxDgramPackets;
7957 peerStats->ifDgramPackets = tp->ifDgramPackets;
7958 peerStats->MTU = tp->MTU;
7959 peerStats->cwind = tp->cwind;
7960 peerStats->nDgramPackets = tp->nDgramPackets;
7961 peerStats->congestSeq = tp->congestSeq;
7962 peerStats->bytesSent.high = tp->bytesSent >> 32;
7963 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7964 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7965 peerStats->bytesReceived.low
7966 = tp->bytesReceived & MAX_AFS_UINT32;
7967 MUTEX_EXIT(&tp->peer_lock);
7969 MUTEX_ENTER(&rx_peerHashTable_lock);
7972 MUTEX_EXIT(&rx_peerHashTable_lock);
7980 struct rx_serverQueueEntry *np;
7983 struct rx_call *call;
7984 struct rx_serverQueueEntry *sq;
7988 if (!rxi_IsRunning()) {
7990 return; /* Already shutdown. */
7992 rx_atomic_set(&rxi_running, 0);
7995 #ifndef AFS_PTHREAD_ENV
7996 FD_ZERO(&rx_selectMask);
7997 #endif /* AFS_PTHREAD_ENV */
7998 rxi_dataQuota = RX_MAX_QUOTA;
7999 #ifndef AFS_PTHREAD_ENV
8001 #endif /* AFS_PTHREAD_ENV */
8004 #ifndef AFS_PTHREAD_ENV
8005 #ifndef AFS_USE_GETTIMEOFDAY
8007 #endif /* AFS_USE_GETTIMEOFDAY */
8008 #endif /* AFS_PTHREAD_ENV */
8010 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
8011 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
8012 opr_queue_Remove(&call->entry);
8013 rxi_Free(call, sizeof(struct rx_call));
8016 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
8017 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
8019 opr_queue_Remove(&sq->entry);
8024 struct rx_peer **peer_ptr, **peer_end;
8025 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8026 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8028 struct rx_peer *peer, *next;
8030 MUTEX_ENTER(&rx_peerHashTable_lock);
8031 for (peer = *peer_ptr; peer; peer = next) {
8032 struct opr_queue *cursor, *store;
8035 MUTEX_ENTER(&rx_rpc_stats);
8036 MUTEX_ENTER(&peer->peer_lock);
8037 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8038 unsigned int num_funcs;
8039 struct rx_interface_stat *rpc_stat
8040 = opr_queue_Entry(cursor, struct rx_interface_stat,
8044 opr_queue_Remove(&rpc_stat->entry);
8045 opr_queue_Remove(&rpc_stat->entryPeers);
8046 num_funcs = rpc_stat->stats[0].func_total;
8048 sizeof(rx_interface_stat_t) +
8049 rpc_stat->stats[0].func_total *
8050 sizeof(rx_function_entry_v1_t);
8052 rxi_Free(rpc_stat, space);
8054 /* rx_rpc_stats must be held */
8055 rxi_rpc_peer_stat_cnt -= num_funcs;
8057 MUTEX_EXIT(&peer->peer_lock);
8058 MUTEX_EXIT(&rx_rpc_stats);
8062 if (rx_stats_active)
8063 rx_atomic_dec(&rx_stats.nPeerStructs);
8065 MUTEX_EXIT(&rx_peerHashTable_lock);
8068 for (i = 0; i < RX_MAX_SERVICES; i++) {
8070 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8072 for (i = 0; i < rx_hashTableSize; i++) {
8073 struct rx_connection *tc, *ntc;
8074 MUTEX_ENTER(&rx_connHashTable_lock);
8075 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8077 for (j = 0; j < RX_MAXCALLS; j++) {
8079 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8082 rxi_Free(tc, sizeof(*tc));
8084 MUTEX_EXIT(&rx_connHashTable_lock);
8087 MUTEX_ENTER(&freeSQEList_lock);
8089 while (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
8090 np = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
8092 opr_queue_Remove(&np->entry);
8093 MUTEX_DESTROY(&np->lock);
8094 rxi_Free(np, sizeof(*np));
8097 MUTEX_EXIT(&freeSQEList_lock);
8098 MUTEX_DESTROY(&freeSQEList_lock);
8099 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8100 MUTEX_DESTROY(&rx_connHashTable_lock);
8101 MUTEX_DESTROY(&rx_peerHashTable_lock);
8102 MUTEX_DESTROY(&rx_serverPool_lock);
8104 osi_Free(rx_connHashTable,
8105 rx_hashTableSize * sizeof(struct rx_connection *));
8106 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8108 UNPIN(rx_connHashTable,
8109 rx_hashTableSize * sizeof(struct rx_connection *));
8110 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8112 MUTEX_ENTER(&rx_quota_mutex);
8113 rxi_dataQuota = RX_MAX_QUOTA;
8114 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8115 MUTEX_EXIT(&rx_quota_mutex);
8122 * Routines to implement connection specific data.
8126 rx_KeyCreate(rx_destructor_t rtn)
8129 MUTEX_ENTER(&rxi_keyCreate_lock);
8130 key = rxi_keyCreate_counter++;
8131 rxi_keyCreate_destructor = (rx_destructor_t *)
8132 realloc((void *)rxi_keyCreate_destructor,
8133 (key + 1) * sizeof(rx_destructor_t));
8134 rxi_keyCreate_destructor[key] = rtn;
8135 MUTEX_EXIT(&rxi_keyCreate_lock);
8140 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8143 MUTEX_ENTER(&conn->conn_data_lock);
8144 if (!conn->specific) {
8145 conn->specific = malloc((key + 1) * sizeof(void *));
8146 for (i = 0; i < key; i++)
8147 conn->specific[i] = NULL;
8148 conn->nSpecific = key + 1;
8149 conn->specific[key] = ptr;
8150 } else if (key >= conn->nSpecific) {
8151 conn->specific = (void **)
8152 realloc(conn->specific, (key + 1) * sizeof(void *));
8153 for (i = conn->nSpecific; i < key; i++)
8154 conn->specific[i] = NULL;
8155 conn->nSpecific = key + 1;
8156 conn->specific[key] = ptr;
8158 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8159 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8160 conn->specific[key] = ptr;
8162 MUTEX_EXIT(&conn->conn_data_lock);
8166 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8169 MUTEX_ENTER(&svc->svc_data_lock);
8170 if (!svc->specific) {
8171 svc->specific = malloc((key + 1) * sizeof(void *));
8172 for (i = 0; i < key; i++)
8173 svc->specific[i] = NULL;
8174 svc->nSpecific = key + 1;
8175 svc->specific[key] = ptr;
8176 } else if (key >= svc->nSpecific) {
8177 svc->specific = (void **)
8178 realloc(svc->specific, (key + 1) * sizeof(void *));
8179 for (i = svc->nSpecific; i < key; i++)
8180 svc->specific[i] = NULL;
8181 svc->nSpecific = key + 1;
8182 svc->specific[key] = ptr;
8184 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8185 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8186 svc->specific[key] = ptr;
8188 MUTEX_EXIT(&svc->svc_data_lock);
8192 rx_GetSpecific(struct rx_connection *conn, int key)
8195 MUTEX_ENTER(&conn->conn_data_lock);
8196 if (key >= conn->nSpecific)
8199 ptr = conn->specific[key];
8200 MUTEX_EXIT(&conn->conn_data_lock);
8205 rx_GetServiceSpecific(struct rx_service *svc, int key)
8208 MUTEX_ENTER(&svc->svc_data_lock);
8209 if (key >= svc->nSpecific)
8212 ptr = svc->specific[key];
8213 MUTEX_EXIT(&svc->svc_data_lock);
8218 #endif /* !KERNEL */
8221 * processStats is a queue used to store the statistics for the local
8222 * process. Its contents are similar to the contents of the rpcStats
8223 * queue on a rx_peer structure, but the actual data stored within
8224 * this queue contains totals across the lifetime of the process (assuming
8225 * the stats have not been reset) - unlike the per peer structures
8226 * which can come and go based upon the peer lifetime.
8229 static struct opr_queue processStats = { &processStats, &processStats };
8232 * peerStats is a queue used to store the statistics for all peer structs.
8233 * Its contents are the union of all the peer rpcStats queues.
8236 static struct opr_queue peerStats = { &peerStats, &peerStats };
8239 * rxi_monitor_processStats is used to turn process wide stat collection
8243 static int rxi_monitor_processStats = 0;
8246 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8249 static int rxi_monitor_peerStats = 0;
8253 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8255 rpc_stat->invocations = 0;
8256 rpc_stat->bytes_sent = 0;
8257 rpc_stat->bytes_rcvd = 0;
8258 rpc_stat->queue_time_sum.sec = 0;
8259 rpc_stat->queue_time_sum.usec = 0;
8260 rpc_stat->queue_time_sum_sqr.sec = 0;
8261 rpc_stat->queue_time_sum_sqr.usec = 0;
8262 rpc_stat->queue_time_min.sec = 9999999;
8263 rpc_stat->queue_time_min.usec = 9999999;
8264 rpc_stat->queue_time_max.sec = 0;
8265 rpc_stat->queue_time_max.usec = 0;
8266 rpc_stat->execution_time_sum.sec = 0;
8267 rpc_stat->execution_time_sum.usec = 0;
8268 rpc_stat->execution_time_sum_sqr.sec = 0;
8269 rpc_stat->execution_time_sum_sqr.usec = 0;
8270 rpc_stat->execution_time_min.sec = 9999999;
8271 rpc_stat->execution_time_min.usec = 9999999;
8272 rpc_stat->execution_time_max.sec = 0;
8273 rpc_stat->execution_time_max.usec = 0;
8277 * Given all of the information for a particular rpc
8278 * call, find or create (if requested) the stat structure for the rpc.
8281 * the queue of stats that will be updated with the new value
8283 * @param rxInterface
8284 * a unique number that identifies the rpc interface
8287 * the total number of functions in this interface. this is only
8288 * required if create is true
8291 * if true, this invocation was made to a server
8294 * the ip address of the remote host. this is only required if create
8295 * and addToPeerList are true
8298 * the port of the remote host. this is only required if create
8299 * and addToPeerList are true
8301 * @param addToPeerList
8302 * if != 0, add newly created stat to the global peer list
8305 * if a new stats structure is allocated, the counter will
8306 * be updated with the new number of allocated stat structures.
8307 * only required if create is true
8310 * if no stats structure exists, allocate one
8314 static rx_interface_stat_p
8315 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8316 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8317 afs_uint32 remotePort, int addToPeerList,
8318 unsigned int *counter, int create)
8320 rx_interface_stat_p rpc_stat = NULL;
8321 struct opr_queue *cursor;
8324 * See if there's already a structure for this interface
8327 for (opr_queue_Scan(stats, cursor)) {
8328 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8330 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8331 && (rpc_stat->stats[0].remote_is_server == isServer))
8335 /* if they didn't ask us to create, we're done */
8337 if (opr_queue_IsEnd(stats, cursor))
8343 /* can't proceed without these */
8344 if (!totalFunc || !counter)
8348 * Didn't find a match so allocate a new structure and add it to the
8352 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8353 || (rpc_stat->stats[0].interfaceId != rxInterface)
8354 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8359 sizeof(rx_interface_stat_t) +
8360 totalFunc * sizeof(rx_function_entry_v1_t);
8362 rpc_stat = rxi_Alloc(space);
8363 if (rpc_stat == NULL)
8366 *counter += totalFunc;
8367 for (i = 0; i < totalFunc; i++) {
8368 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8369 rpc_stat->stats[i].remote_peer = remoteHost;
8370 rpc_stat->stats[i].remote_port = remotePort;
8371 rpc_stat->stats[i].remote_is_server = isServer;
8372 rpc_stat->stats[i].interfaceId = rxInterface;
8373 rpc_stat->stats[i].func_total = totalFunc;
8374 rpc_stat->stats[i].func_index = i;
8376 opr_queue_Prepend(stats, &rpc_stat->entry);
8377 if (addToPeerList) {
8378 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8385 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8387 rx_interface_stat_p rpc_stat;
8390 if (rxInterface == -1)
8393 MUTEX_ENTER(&rx_rpc_stats);
8394 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8397 totalFunc = rpc_stat->stats[0].func_total;
8398 for (i = 0; i < totalFunc; i++)
8399 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8401 MUTEX_EXIT(&rx_rpc_stats);
8406 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8408 rx_interface_stat_p rpc_stat;
8410 struct rx_peer * peer;
8412 if (rxInterface == -1)
8415 peer = rxi_FindPeer(peerHost, peerPort, 0);
8419 MUTEX_ENTER(&rx_rpc_stats);
8420 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8423 totalFunc = rpc_stat->stats[0].func_total;
8424 for (i = 0; i < totalFunc; i++)
8425 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8427 MUTEX_EXIT(&rx_rpc_stats);
8432 rx_CopyProcessRPCStats(afs_uint64 op)
8434 rx_interface_stat_p rpc_stat;
8435 rx_function_entry_v1_p rpcop_stat =
8436 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8437 int currentFunc = (op & MAX_AFS_UINT32);
8438 afs_int32 rxInterface = (op >> 32);
8440 if (!rxi_monitor_processStats)
8443 if (rxInterface == -1)
8446 if (rpcop_stat == NULL)
8449 MUTEX_ENTER(&rx_rpc_stats);
8450 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8453 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8454 sizeof(rx_function_entry_v1_t));
8455 MUTEX_EXIT(&rx_rpc_stats);
8457 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8464 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8466 rx_interface_stat_p rpc_stat;
8467 rx_function_entry_v1_p rpcop_stat =
8468 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8469 int currentFunc = (op & MAX_AFS_UINT32);
8470 afs_int32 rxInterface = (op >> 32);
8471 struct rx_peer *peer;
8473 if (!rxi_monitor_peerStats)
8476 if (rxInterface == -1)
8479 if (rpcop_stat == NULL)
8482 peer = rxi_FindPeer(peerHost, peerPort, 0);
8486 MUTEX_ENTER(&rx_rpc_stats);
8487 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8490 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8491 sizeof(rx_function_entry_v1_t));
8492 MUTEX_EXIT(&rx_rpc_stats);
8494 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8501 rx_ReleaseRPCStats(void *stats)
8504 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8508 * Given all of the information for a particular rpc
8509 * call, create (if needed) and update the stat totals for the rpc.
8512 * the queue of stats that will be updated with the new value
8514 * @param rxInterface
8515 * a unique number that identifies the rpc interface
8517 * @param currentFunc
8518 * the index of the function being invoked
8521 * the total number of functions in this interface
8524 * the amount of time this function waited for a thread
8527 * the amount of time this function invocation took to execute
8530 * the number bytes sent by this invocation
8533 * the number bytes received by this invocation
8536 * if true, this invocation was made to a server
8539 * the ip address of the remote host
8542 * the port of the remote host
8544 * @param addToPeerList
8545 * if != 0, add newly created stat to the global peer list
8548 * if a new stats structure is allocated, the counter will
8549 * be updated with the new number of allocated stat structures
8554 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8555 afs_uint32 currentFunc, afs_uint32 totalFunc,
8556 struct clock *queueTime, struct clock *execTime,
8557 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8558 afs_uint32 remoteHost, afs_uint32 remotePort,
8559 int addToPeerList, unsigned int *counter)
8562 rx_interface_stat_p rpc_stat;
8564 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8565 remoteHost, remotePort, addToPeerList, counter,
8573 * Increment the stats for this function
8576 rpc_stat->stats[currentFunc].invocations++;
8577 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8578 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8579 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8580 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8581 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8582 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8584 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8585 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8587 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8588 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8590 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8591 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8593 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8594 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8602 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8603 afs_uint32 currentFunc, afs_uint32 totalFunc,
8604 struct clock *queueTime, struct clock *execTime,
8605 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8609 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8612 MUTEX_ENTER(&rx_rpc_stats);
8614 if (rxi_monitor_peerStats) {
8615 MUTEX_ENTER(&peer->peer_lock);
8616 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8617 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8618 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8619 MUTEX_EXIT(&peer->peer_lock);
8622 if (rxi_monitor_processStats) {
8623 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8624 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8625 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8628 MUTEX_EXIT(&rx_rpc_stats);
8632 * Increment the times and count for a particular rpc function.
8634 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8635 * call rx_RecordCallStatistics instead, so the public version of this
8636 * function is left purely for legacy callers.
8639 * The peer who invoked the rpc
8641 * @param rxInterface
8642 * A unique number that identifies the rpc interface
8644 * @param currentFunc
8645 * The index of the function being invoked
8648 * The total number of functions in this interface
8651 * The amount of time this function waited for a thread
8654 * The amount of time this function invocation took to execute
8657 * The number bytes sent by this invocation
8660 * The number bytes received by this invocation
8663 * If true, this invocation was made to a server
8667 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8668 afs_uint32 currentFunc, afs_uint32 totalFunc,
8669 struct clock *queueTime, struct clock *execTime,
8670 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8676 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8677 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8679 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8680 queueTime, execTime, sent64, rcvd64,
8687 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8691 * IN callerVersion - the rpc stat version of the caller.
8693 * IN count - the number of entries to marshall.
8695 * IN stats - pointer to stats to be marshalled.
8697 * OUT ptr - Where to store the marshalled data.
8704 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8705 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8711 * We only support the first version
8713 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8714 *(ptr++) = stats->remote_peer;
8715 *(ptr++) = stats->remote_port;
8716 *(ptr++) = stats->remote_is_server;
8717 *(ptr++) = stats->interfaceId;
8718 *(ptr++) = stats->func_total;
8719 *(ptr++) = stats->func_index;
8720 *(ptr++) = stats->invocations >> 32;
8721 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8722 *(ptr++) = stats->bytes_sent >> 32;
8723 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8724 *(ptr++) = stats->bytes_rcvd >> 32;
8725 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8726 *(ptr++) = stats->queue_time_sum.sec;
8727 *(ptr++) = stats->queue_time_sum.usec;
8728 *(ptr++) = stats->queue_time_sum_sqr.sec;
8729 *(ptr++) = stats->queue_time_sum_sqr.usec;
8730 *(ptr++) = stats->queue_time_min.sec;
8731 *(ptr++) = stats->queue_time_min.usec;
8732 *(ptr++) = stats->queue_time_max.sec;
8733 *(ptr++) = stats->queue_time_max.usec;
8734 *(ptr++) = stats->execution_time_sum.sec;
8735 *(ptr++) = stats->execution_time_sum.usec;
8736 *(ptr++) = stats->execution_time_sum_sqr.sec;
8737 *(ptr++) = stats->execution_time_sum_sqr.usec;
8738 *(ptr++) = stats->execution_time_min.sec;
8739 *(ptr++) = stats->execution_time_min.usec;
8740 *(ptr++) = stats->execution_time_max.sec;
8741 *(ptr++) = stats->execution_time_max.usec;
8747 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8752 * IN callerVersion - the rpc stat version of the caller
8754 * OUT myVersion - the rpc stat version of this function
8756 * OUT clock_sec - local time seconds
8758 * OUT clock_usec - local time microseconds
8760 * OUT allocSize - the number of bytes allocated to contain stats
8762 * OUT statCount - the number stats retrieved from this process.
8764 * OUT stats - the actual stats retrieved from this process.
8768 * Returns void. If successful, stats will != NULL.
8772 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8773 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8774 size_t * allocSize, afs_uint32 * statCount,
8775 afs_uint32 ** stats)
8785 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8788 * Check to see if stats are enabled
8791 MUTEX_ENTER(&rx_rpc_stats);
8792 if (!rxi_monitor_processStats) {
8793 MUTEX_EXIT(&rx_rpc_stats);
8797 clock_GetTime(&now);
8798 *clock_sec = now.sec;
8799 *clock_usec = now.usec;
8802 * Allocate the space based upon the caller version
8804 * If the client is at an older version than we are,
8805 * we return the statistic data in the older data format, but
8806 * we still return our version number so the client knows we
8807 * are maintaining more data than it can retrieve.
8810 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8811 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8812 *statCount = rxi_rpc_process_stat_cnt;
8815 * This can't happen yet, but in the future version changes
8816 * can be handled by adding additional code here
8820 if (space > (size_t) 0) {
8822 ptr = *stats = rxi_Alloc(space);
8825 struct opr_queue *cursor;
8827 for (opr_queue_Scan(&processStats, cursor)) {
8828 struct rx_interface_stat *rpc_stat =
8829 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8831 * Copy the data based upon the caller version
8833 rx_MarshallProcessRPCStats(callerVersion,
8834 rpc_stat->stats[0].func_total,
8835 rpc_stat->stats, &ptr);
8841 MUTEX_EXIT(&rx_rpc_stats);
8846 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8850 * IN callerVersion - the rpc stat version of the caller
8852 * OUT myVersion - the rpc stat version of this function
8854 * OUT clock_sec - local time seconds
8856 * OUT clock_usec - local time microseconds
8858 * OUT allocSize - the number of bytes allocated to contain stats
8860 * OUT statCount - the number of stats retrieved from the individual
8863 * OUT stats - the actual stats retrieved from the individual peer structures.
8867 * Returns void. If successful, stats will != NULL.
8871 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8872 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8873 size_t * allocSize, afs_uint32 * statCount,
8874 afs_uint32 ** stats)
8884 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8887 * Check to see if stats are enabled
8890 MUTEX_ENTER(&rx_rpc_stats);
8891 if (!rxi_monitor_peerStats) {
8892 MUTEX_EXIT(&rx_rpc_stats);
8896 clock_GetTime(&now);
8897 *clock_sec = now.sec;
8898 *clock_usec = now.usec;
8901 * Allocate the space based upon the caller version
8903 * If the client is at an older version than we are,
8904 * we return the statistic data in the older data format, but
8905 * we still return our version number so the client knows we
8906 * are maintaining more data than it can retrieve.
8909 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8910 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8911 *statCount = rxi_rpc_peer_stat_cnt;
8914 * This can't happen yet, but in the future version changes
8915 * can be handled by adding additional code here
8919 if (space > (size_t) 0) {
8921 ptr = *stats = rxi_Alloc(space);
8924 struct opr_queue *cursor;
8926 for (opr_queue_Scan(&peerStats, cursor)) {
8927 struct rx_interface_stat *rpc_stat
8928 = opr_queue_Entry(cursor, struct rx_interface_stat,
8932 * Copy the data based upon the caller version
8934 rx_MarshallProcessRPCStats(callerVersion,
8935 rpc_stat->stats[0].func_total,
8936 rpc_stat->stats, &ptr);
8942 MUTEX_EXIT(&rx_rpc_stats);
8947 * rx_FreeRPCStats - free memory allocated by
8948 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8952 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8953 * rx_RetrievePeerRPCStats
8955 * IN allocSize - the number of bytes in stats.
8963 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8965 rxi_Free(stats, allocSize);
8969 * rx_queryProcessRPCStats - see if process rpc stat collection is
8970 * currently enabled.
8976 * Returns 0 if stats are not enabled != 0 otherwise
8980 rx_queryProcessRPCStats(void)
8983 MUTEX_ENTER(&rx_rpc_stats);
8984 rc = rxi_monitor_processStats;
8985 MUTEX_EXIT(&rx_rpc_stats);
8990 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8996 * Returns 0 if stats are not enabled != 0 otherwise
9000 rx_queryPeerRPCStats(void)
9003 MUTEX_ENTER(&rx_rpc_stats);
9004 rc = rxi_monitor_peerStats;
9005 MUTEX_EXIT(&rx_rpc_stats);
9010 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
9020 rx_enableProcessRPCStats(void)
9022 MUTEX_ENTER(&rx_rpc_stats);
9023 rx_enable_stats = 1;
9024 rxi_monitor_processStats = 1;
9025 MUTEX_EXIT(&rx_rpc_stats);
9029 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
9039 rx_enablePeerRPCStats(void)
9041 MUTEX_ENTER(&rx_rpc_stats);
9042 rx_enable_stats = 1;
9043 rxi_monitor_peerStats = 1;
9044 MUTEX_EXIT(&rx_rpc_stats);
9048 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9058 rx_disableProcessRPCStats(void)
9060 struct opr_queue *cursor, *store;
9063 MUTEX_ENTER(&rx_rpc_stats);
9066 * Turn off process statistics and if peer stats is also off, turn
9070 rxi_monitor_processStats = 0;
9071 if (rxi_monitor_peerStats == 0) {
9072 rx_enable_stats = 0;
9075 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9076 unsigned int num_funcs = 0;
9077 struct rx_interface_stat *rpc_stat
9078 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9080 opr_queue_Remove(&rpc_stat->entry);
9082 num_funcs = rpc_stat->stats[0].func_total;
9084 sizeof(rx_interface_stat_t) +
9085 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9087 rxi_Free(rpc_stat, space);
9088 rxi_rpc_process_stat_cnt -= num_funcs;
9090 MUTEX_EXIT(&rx_rpc_stats);
9094 * rx_disablePeerRPCStats - stop rpc stat collection for peers
9104 rx_disablePeerRPCStats(void)
9106 struct rx_peer **peer_ptr, **peer_end;
9110 * Turn off peer statistics and if process stats is also off, turn
9114 rxi_monitor_peerStats = 0;
9115 if (rxi_monitor_processStats == 0) {
9116 rx_enable_stats = 0;
9119 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9120 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9122 struct rx_peer *peer, *next, *prev;
9124 MUTEX_ENTER(&rx_peerHashTable_lock);
9125 MUTEX_ENTER(&rx_rpc_stats);
9126 for (prev = peer = *peer_ptr; peer; peer = next) {
9128 code = MUTEX_TRYENTER(&peer->peer_lock);
9131 struct opr_queue *cursor, *store;
9133 if (prev == *peer_ptr) {
9144 MUTEX_EXIT(&rx_peerHashTable_lock);
9146 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9147 unsigned int num_funcs = 0;
9148 struct rx_interface_stat *rpc_stat
9149 = opr_queue_Entry(cursor, struct rx_interface_stat,
9152 opr_queue_Remove(&rpc_stat->entry);
9153 opr_queue_Remove(&rpc_stat->entryPeers);
9154 num_funcs = rpc_stat->stats[0].func_total;
9156 sizeof(rx_interface_stat_t) +
9157 rpc_stat->stats[0].func_total *
9158 sizeof(rx_function_entry_v1_t);
9160 rxi_Free(rpc_stat, space);
9161 rxi_rpc_peer_stat_cnt -= num_funcs;
9163 MUTEX_EXIT(&peer->peer_lock);
9165 MUTEX_ENTER(&rx_peerHashTable_lock);
9175 MUTEX_EXIT(&rx_rpc_stats);
9176 MUTEX_EXIT(&rx_peerHashTable_lock);
9181 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9186 * IN clearFlag - flag indicating which stats to clear
9194 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9196 struct opr_queue *cursor;
9198 MUTEX_ENTER(&rx_rpc_stats);
9200 for (opr_queue_Scan(&processStats, cursor)) {
9201 unsigned int num_funcs = 0, i;
9202 struct rx_interface_stat *rpc_stat
9203 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9205 num_funcs = rpc_stat->stats[0].func_total;
9206 for (i = 0; i < num_funcs; i++) {
9207 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9208 rpc_stat->stats[i].invocations = 0;
9210 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9211 rpc_stat->stats[i].bytes_sent = 0;
9213 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9214 rpc_stat->stats[i].bytes_rcvd = 0;
9216 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9217 rpc_stat->stats[i].queue_time_sum.sec = 0;
9218 rpc_stat->stats[i].queue_time_sum.usec = 0;
9220 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9221 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9222 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9224 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9225 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9226 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9228 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9229 rpc_stat->stats[i].queue_time_max.sec = 0;
9230 rpc_stat->stats[i].queue_time_max.usec = 0;
9232 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9233 rpc_stat->stats[i].execution_time_sum.sec = 0;
9234 rpc_stat->stats[i].execution_time_sum.usec = 0;
9236 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9237 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9238 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9240 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9241 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9242 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9244 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9245 rpc_stat->stats[i].execution_time_max.sec = 0;
9246 rpc_stat->stats[i].execution_time_max.usec = 0;
9251 MUTEX_EXIT(&rx_rpc_stats);
9255 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9260 * IN clearFlag - flag indicating which stats to clear
9268 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9270 struct opr_queue *cursor;
9272 MUTEX_ENTER(&rx_rpc_stats);
9274 for (opr_queue_Scan(&peerStats, cursor)) {
9275 unsigned int num_funcs, i;
9276 struct rx_interface_stat *rpc_stat
9277 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9279 num_funcs = rpc_stat->stats[0].func_total;
9280 for (i = 0; i < num_funcs; i++) {
9281 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9282 rpc_stat->stats[i].invocations = 0;
9284 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9285 rpc_stat->stats[i].bytes_sent = 0;
9287 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9288 rpc_stat->stats[i].bytes_rcvd = 0;
9290 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9291 rpc_stat->stats[i].queue_time_sum.sec = 0;
9292 rpc_stat->stats[i].queue_time_sum.usec = 0;
9294 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9295 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9296 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9298 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9299 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9300 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9302 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9303 rpc_stat->stats[i].queue_time_max.sec = 0;
9304 rpc_stat->stats[i].queue_time_max.usec = 0;
9306 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9307 rpc_stat->stats[i].execution_time_sum.sec = 0;
9308 rpc_stat->stats[i].execution_time_sum.usec = 0;
9310 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9311 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9312 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9314 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9315 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9316 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9318 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9319 rpc_stat->stats[i].execution_time_max.sec = 0;
9320 rpc_stat->stats[i].execution_time_max.usec = 0;
9325 MUTEX_EXIT(&rx_rpc_stats);
9329 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9330 * is authorized to enable/disable/clear RX statistics.
9332 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9335 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9337 rxi_rxstat_userok = proc;
9341 rx_RxStatUserOk(struct rx_call *call)
9343 if (!rxi_rxstat_userok)
9345 return rxi_rxstat_userok(call);
9350 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9351 * function in the MSVC runtime DLL (msvcrt.dll).
9353 * Note: the system serializes calls to this function.
9356 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9357 DWORD reason, /* reason function is being called */
9358 LPVOID reserved) /* reserved for future use */
9361 case DLL_PROCESS_ATTACH:
9362 /* library is being attached to a process */
9366 case DLL_PROCESS_DETACH:
9373 #endif /* AFS_NT40_ENV */
9376 int rx_DumpCalls(FILE *outputFile, char *cookie)
9378 #ifdef RXDEBUG_PACKET
9379 #ifdef KDUMP_RX_LOCK
9380 struct rx_call_rx_lock *c;
9387 #define RXDPRINTF sprintf
9388 #define RXDPRINTOUT output
9390 #define RXDPRINTF fprintf
9391 #define RXDPRINTOUT outputFile
9394 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9396 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9399 for (c = rx_allCallsp; c; c = c->allNextp) {
9400 u_short rqc, tqc, iovqc;
9402 MUTEX_ENTER(&c->lock);
9403 rqc = opr_queue_Count(&c->rq);
9404 tqc = opr_queue_Count(&c->tq);
9405 iovqc = opr_queue_Count(&c->app.iovq);
9407 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, "
9408 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9409 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9410 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9411 "lastSendTime=%u, lastRecvTime=%u"
9412 #ifdef RX_ENABLE_LOCKS
9415 #ifdef RX_REFCOUNT_CHECK
9416 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9417 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9420 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,
9421 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9422 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9423 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9424 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9425 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9426 #ifdef RX_ENABLE_LOCKS
9427 , (afs_uint32)c->refCount
9429 #ifdef RX_REFCOUNT_CHECK
9430 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9433 MUTEX_EXIT(&c->lock);
9436 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9439 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9441 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9443 #endif /* RXDEBUG_PACKET */
9448 #ifdef AFS_RXERRQ_ENV
9450 rxi_HandleSocketErrors(osi_socket sock)
9452 size_t cmsgbuf_len = 256;
9455 int errno_save = errno;
9458 cmsgbuf = rxi_Alloc(cmsgbuf_len);
9459 if (cmsgbuf == NULL) {
9463 while (osi_HandleSocketError(sock, cmsgbuf, cmsgbuf_len))
9466 rxi_Free(cmsgbuf, cmsgbuf_len);
9476 NetSend_retry(osi_socket sock, void *addr, struct iovec *dvec, int nvecs,
9477 int length, int istack)
9482 * If an ICMP error comes in for any peer, sendmsg() can return -1 with an
9483 * errno of EHOSTUNREACH, ENETUNREACH, etc. There may be no problem with
9484 * sending this packet (an error is returned just to indicate we need to
9485 * read in pending errors), but the packet wasn't actually sent.
9487 * It's difficult to determine in general whether sendmsg() is returning an
9488 * error due to a received ICMP error, or we're getting an actual error for
9489 * this specific sendmsg() call, since there may be other threads running
9490 * sendmsg/recvmsg/rxi_HandleSocketErrors at the same time. So, just retry
9491 * the sendmsg a few times; make sure not to retry forever, in case we are
9492 * getting an actual error from this sendmsg() call.
9494 * Also note that if we accidentally drop a packet here that we didn't need
9495 * to, it's not the end of the world. Packets get dropped, and we should be
9498 for (safety = 0; safety < RXI_SENDMSG_RETRY; safety++) {
9499 code = osi_NetSend(sock, addr, dvec, nvecs, length, istack);
9503 rxi_HandleSocketErrors(sock);
9511 rxi_NetSend(osi_socket socket, void *addr, struct iovec *dvec,
9512 int nvecs, int length, int istack)
9514 if (rxi_IsRunning()) {
9515 #ifdef AFS_RXERRQ_ENV
9516 return NetSend_retry(socket, addr, dvec, nvecs, length, istack);
9518 return osi_NetSend(socket, addr, dvec, nvecs, length, istack);
9522 return WSAESHUTDOWN;