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>
76 #include "rx_atomic.h"
77 #include "rx_globals.h"
79 #include "rx_internal.h"
85 #include "rx_packet.h"
87 #include <afs/rxgen_consts.h>
90 #ifdef AFS_PTHREAD_ENV
92 int (*registerProgram) (pid_t, char *) = 0;
93 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
96 int (*registerProgram) (PROCESS, char *) = 0;
97 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
101 /* Local static routines */
102 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
103 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
104 struct rx_call *, struct rx_peer *,
106 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
108 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
109 void *dummy, int dummy2);
110 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
111 void *dummy, int dummy2);
112 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
113 void *unused, int unused2);
114 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
115 void *unused2, int unused3);
117 #ifdef RX_ENABLE_LOCKS
118 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
121 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
123 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
124 rx_atomic_t rxi_start_in_error;
126 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
128 /* Constant delay time before sending an acknowledge of the last packet
129 * received. This is to avoid sending an extra acknowledge when the
130 * client is about to make another call, anyway, or the server is
133 * The lastAckDelay may not exceeed 400ms without causing peers to
134 * unecessarily timeout.
136 struct clock rx_lastAckDelay = {0, 400000};
138 /* Constant delay time before sending a soft ack when none was requested.
139 * This is to make sure we send soft acks before the sender times out,
140 * Normally we wait and send a hard ack when the receiver consumes the packet
142 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
143 * will require changes to the peer's RTT calculations.
145 struct clock rx_softAckDelay = {0, 100000};
148 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
149 * currently allocated within rx. This number is used to allocate the
150 * memory required to return the statistics when queried.
151 * Protected by the rx_rpc_stats mutex.
154 static unsigned int rxi_rpc_peer_stat_cnt;
157 * rxi_rpc_process_stat_cnt counts the total number of local process stat
158 * structures currently allocated within rx. The number is used to allocate
159 * the memory required to return the statistics when queried.
160 * Protected by the rx_rpc_stats mutex.
163 static unsigned int rxi_rpc_process_stat_cnt;
166 * rxi_busyChannelError is a boolean. It indicates whether or not RX_CALL_BUSY
167 * errors should be reported to the application when a call channel appears busy
168 * (inferred from the receipt of RX_PACKET_TYPE_BUSY packets on the channel),
169 * and there are other call channels in the connection that are not busy.
170 * If 0, we do not return errors upon receiving busy packets; we just keep
171 * trying on the same call channel until we hit a timeout.
173 static afs_int32 rxi_busyChannelError = 0;
175 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
176 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
178 #if !defined(offsetof)
179 #include <stddef.h> /* for definition of offsetof() */
182 #ifdef RX_ENABLE_LOCKS
183 afs_kmutex_t rx_atomic_mutex;
186 /* Forward prototypes */
187 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
190 putConnection (struct rx_connection *conn) {
191 MUTEX_ENTER(&rx_refcnt_mutex);
193 MUTEX_EXIT(&rx_refcnt_mutex);
196 #ifdef AFS_PTHREAD_ENV
199 * Use procedural initialization of mutexes/condition variables
203 extern afs_kmutex_t rx_quota_mutex;
204 extern afs_kmutex_t rx_pthread_mutex;
205 extern afs_kmutex_t rx_packets_mutex;
206 extern afs_kmutex_t rx_refcnt_mutex;
207 extern afs_kmutex_t des_init_mutex;
208 extern afs_kmutex_t des_random_mutex;
209 extern afs_kmutex_t rx_clock_mutex;
210 extern afs_kmutex_t rxi_connCacheMutex;
211 extern afs_kmutex_t event_handler_mutex;
212 extern afs_kmutex_t listener_mutex;
213 extern afs_kmutex_t rx_if_init_mutex;
214 extern afs_kmutex_t rx_if_mutex;
216 extern afs_kcondvar_t rx_event_handler_cond;
217 extern afs_kcondvar_t rx_listener_cond;
219 static afs_kmutex_t epoch_mutex;
220 static afs_kmutex_t rx_init_mutex;
221 static afs_kmutex_t rx_debug_mutex;
222 static afs_kmutex_t rx_rpc_stats;
225 rxi_InitPthread(void)
227 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
228 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
229 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
230 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
231 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
232 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
233 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
234 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
235 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
236 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
237 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
238 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
239 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
240 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
241 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
243 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
244 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
246 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
247 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
249 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
250 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
251 #ifdef RX_ENABLE_LOCKS
254 #endif /* RX_LOCKS_DB */
255 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
256 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
258 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
260 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
262 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
264 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
265 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
266 #endif /* RX_ENABLE_LOCKS */
269 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
270 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
272 * The rx_stats_mutex mutex protects the following global variables:
273 * rxi_lowConnRefCount
274 * rxi_lowPeerRefCount
283 * The rx_quota_mutex mutex protects the following global variables:
291 * The rx_freePktQ_lock protects the following global variables:
296 * The rx_packets_mutex mutex protects the following global variables:
304 * The rx_pthread_mutex mutex protects the following global variables:
305 * rxi_fcfs_thread_num
308 #define INIT_PTHREAD_LOCKS
312 /* Variables for handling the minProcs implementation. availProcs gives the
313 * number of threads available in the pool at this moment (not counting dudes
314 * executing right now). totalMin gives the total number of procs required
315 * for handling all minProcs requests. minDeficit is a dynamic variable
316 * tracking the # of procs required to satisfy all of the remaining minProcs
318 * For fine grain locking to work, the quota check and the reservation of
319 * a server thread has to come while rxi_availProcs and rxi_minDeficit
320 * are locked. To this end, the code has been modified under #ifdef
321 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
322 * same time. A new function, ReturnToServerPool() returns the allocation.
324 * A call can be on several queue's (but only one at a time). When
325 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
326 * that no one else is touching the queue. To this end, we store the address
327 * of the queue lock in the call structure (under the call lock) when we
328 * put the call on a queue, and we clear the call_queue_lock when the
329 * call is removed from a queue (once the call lock has been obtained).
330 * This allows rxi_ResetCall to safely synchronize with others wishing
331 * to manipulate the queue.
334 #if defined(RX_ENABLE_LOCKS)
335 static afs_kmutex_t rx_rpc_stats;
338 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
339 ** pretty good that the next packet coming in is from the same connection
340 ** as the last packet, since we're send multiple packets in a transmit window.
342 struct rx_connection *rxLastConn = 0;
344 #ifdef RX_ENABLE_LOCKS
345 /* The locking hierarchy for rx fine grain locking is composed of these
348 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
349 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
350 * call->lock - locks call data fields.
351 * These are independent of each other:
352 * rx_freeCallQueue_lock
357 * serverQueueEntry->lock
358 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
360 * peer->lock - locks peer data fields.
361 * conn_data_lock - that more than one thread is not updating a conn data
362 * field at the same time.
373 * Do we need a lock to protect the peer field in the conn structure?
374 * conn->peer was previously a constant for all intents and so has no
375 * lock protecting this field. The multihomed client delta introduced
376 * a RX code change : change the peer field in the connection structure
377 * to that remote interface from which the last packet for this
378 * connection was sent out. This may become an issue if further changes
381 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
382 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
384 /* rxdb_fileID is used to identify the lock location, along with line#. */
385 static int rxdb_fileID = RXDB_FILE_RX;
386 #endif /* RX_LOCKS_DB */
387 #else /* RX_ENABLE_LOCKS */
388 #define SET_CALL_QUEUE_LOCK(C, L)
389 #define CLEAR_CALL_QUEUE_LOCK(C)
390 #endif /* RX_ENABLE_LOCKS */
391 struct rx_serverQueueEntry *rx_waitForPacket = 0;
392 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
394 /* ------------Exported Interfaces------------- */
396 /* This function allows rxkad to set the epoch to a suitably random number
397 * which rx_NewConnection will use in the future. The principle purpose is to
398 * get rxnull connections to use the same epoch as the rxkad connections do, at
399 * least once the first rxkad connection is established. This is important now
400 * that the host/port addresses aren't used in FindConnection: the uniqueness
401 * of epoch/cid matters and the start time won't do. */
403 #ifdef AFS_PTHREAD_ENV
405 * This mutex protects the following global variables:
409 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
410 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
414 #endif /* AFS_PTHREAD_ENV */
417 rx_SetEpoch(afs_uint32 epoch)
424 /* Initialize rx. A port number may be mentioned, in which case this
425 * becomes the default port number for any service installed later.
426 * If 0 is provided for the port number, a random port will be chosen
427 * by the kernel. Whether this will ever overlap anything in
428 * /etc/services is anybody's guess... Returns 0 on success, -1 on
433 int rxinit_status = 1;
434 #ifdef AFS_PTHREAD_ENV
436 * This mutex protects the following global variables:
440 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
441 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
444 #define UNLOCK_RX_INIT
448 rx_InitHost(u_int host, u_int port)
455 char *htable, *ptable;
462 if (rxinit_status == 0) {
463 tmp_status = rxinit_status;
465 return tmp_status; /* Already started; return previous error code. */
471 if (afs_winsockInit() < 0)
477 * Initialize anything necessary to provide a non-premptive threading
480 rxi_InitializeThreadSupport();
483 /* Allocate and initialize a socket for client and perhaps server
486 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
487 if (rx_socket == OSI_NULLSOCKET) {
491 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
494 #endif /* RX_LOCKS_DB */
495 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
496 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
497 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
498 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
499 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
500 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
501 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
502 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
503 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
505 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
507 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
509 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
511 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
512 #if defined(AFS_HPUX110_ENV)
514 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
515 #endif /* AFS_HPUX110_ENV */
516 #endif /* RX_ENABLE_LOCKS && KERNEL */
519 rx_connDeadTime = 12;
520 rx_tranquil = 0; /* reset flag */
521 rxi_ResetStatistics();
523 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
524 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
525 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
526 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
527 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
528 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
530 /* Malloc up a bunch of packets & buffers */
532 queue_Init(&rx_freePacketQueue);
533 rxi_NeedMorePackets = FALSE;
534 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
536 /* enforce a minimum number of allocated packets */
537 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
538 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
540 /* allocate the initial free packet pool */
541 #ifdef RX_ENABLE_TSFPQ
542 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
543 #else /* RX_ENABLE_TSFPQ */
544 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
545 #endif /* RX_ENABLE_TSFPQ */
552 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
553 tv.tv_sec = clock_now.sec;
554 tv.tv_usec = clock_now.usec;
555 srand((unsigned int)tv.tv_usec);
562 #if defined(KERNEL) && !defined(UKERNEL)
563 /* Really, this should never happen in a real kernel */
566 struct sockaddr_in addr;
568 int addrlen = sizeof(addr);
570 socklen_t addrlen = sizeof(addr);
572 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
576 rx_port = addr.sin_port;
579 rx_stats.minRtt.sec = 9999999;
581 rx_SetEpoch(tv.tv_sec | 0x80000000);
583 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
584 * will provide a randomer value. */
586 MUTEX_ENTER(&rx_quota_mutex);
587 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
588 MUTEX_EXIT(&rx_quota_mutex);
589 /* *Slightly* random start time for the cid. This is just to help
590 * out with the hashing function at the peer */
591 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
592 rx_connHashTable = (struct rx_connection **)htable;
593 rx_peerHashTable = (struct rx_peer **)ptable;
595 rx_hardAckDelay.sec = 0;
596 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
598 rxevent_Init(20, rxi_ReScheduleEvents);
600 /* Initialize various global queues */
601 queue_Init(&rx_idleServerQueue);
602 queue_Init(&rx_incomingCallQueue);
603 queue_Init(&rx_freeCallQueue);
605 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
606 /* Initialize our list of usable IP addresses. */
610 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
611 /* Start listener process (exact function is dependent on the
612 * implementation environment--kernel or user space) */
617 tmp_status = rxinit_status = 0;
625 return rx_InitHost(htonl(INADDR_ANY), port);
631 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
632 * maintaing the round trip timer.
637 * Start a new RTT timer for a given call and packet.
639 * There must be no resendEvent already listed for this call, otherwise this
640 * will leak events - intended for internal use within the RTO code only
643 * the RX call to start the timer for
644 * @param[in] lastPacket
645 * a flag indicating whether the last packet has been sent or not
647 * @pre call must be locked before calling this function
651 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
653 struct clock now, retryTime;
658 clock_Add(&retryTime, &call->rto);
660 /* If we're sending the last packet, and we're the client, then the server
661 * may wait for an additional 400ms before returning the ACK, wait for it
662 * rather than hitting a timeout */
663 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
664 clock_Addmsec(&retryTime, 400);
666 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
667 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
672 * Cancel an RTT timer for a given call.
676 * the RX call to cancel the timer for
678 * @pre call must be locked before calling this function
683 rxi_rto_cancel(struct rx_call *call)
685 rxevent_Cancel(&call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
689 * Tell the RTO timer that we have sent a packet.
691 * If the timer isn't already running, then start it. If the timer is running,
695 * the RX call that the packet has been sent on
696 * @param[in] lastPacket
697 * A flag which is true if this is the last packet for the call
699 * @pre The call must be locked before calling this function
704 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
706 if (call->resendEvent)
709 rxi_rto_startTimer(call, lastPacket, istack);
713 * Tell the RTO timer that we have received an new ACK message
715 * This function should be called whenever a call receives an ACK that
716 * acknowledges new packets. Whatever happens, we stop the current timer.
717 * If there are unacked packets in the queue which have been sent, then
718 * we restart the timer from now. Otherwise, we leave it stopped.
721 * the RX call that the ACK has been received on
725 rxi_rto_packet_acked(struct rx_call *call, int istack)
727 struct rx_packet *p, *nxp;
729 rxi_rto_cancel(call);
731 if (queue_IsEmpty(&call->tq))
734 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
735 if (p->header.seq > call->tfirst + call->twind)
738 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
739 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
747 * Set an initial round trip timeout for a peer connection
749 * @param[in] secs The timeout to set in seconds
753 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
754 peer->rtt = secs * 8000;
758 * Enables or disables the busy call channel error (RX_CALL_BUSY).
760 * @param[in] onoff Non-zero to enable busy call channel errors.
762 * @pre Neither rx_Init nor rx_InitHost have been called yet
765 rx_SetBusyChannelError(afs_int32 onoff)
767 osi_Assert(rxinit_status != 0);
768 rxi_busyChannelError = onoff ? 1 : 0;
772 * Set a delayed ack event on the specified call for the given time
774 * @param[in] call - the call on which to set the event
775 * @param[in] offset - the delay from now after which the event fires
778 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
780 struct clock now, when;
784 clock_Add(&when, offset);
786 if (!call->delayedAckEvent
787 || clock_Gt(&call->delayedAckTime, &when)) {
789 rxevent_Cancel(&call->delayedAckEvent, call,
790 RX_CALL_REFCOUNT_DELAY);
791 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
793 call->delayedAckEvent = rxevent_Post(&when, &now,
796 call->delayedAckTime = when;
800 /* called with unincremented nRequestsRunning to see if it is OK to start
801 * a new thread in this service. Could be "no" for two reasons: over the
802 * max quota, or would prevent others from reaching their min quota.
804 #ifdef RX_ENABLE_LOCKS
805 /* This verion of QuotaOK reserves quota if it's ok while the
806 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
809 QuotaOK(struct rx_service *aservice)
811 /* check if over max quota */
812 if (aservice->nRequestsRunning >= aservice->maxProcs) {
816 /* under min quota, we're OK */
817 /* otherwise, can use only if there are enough to allow everyone
818 * to go to their min quota after this guy starts.
821 MUTEX_ENTER(&rx_quota_mutex);
822 if ((aservice->nRequestsRunning < aservice->minProcs)
823 || (rxi_availProcs > rxi_minDeficit)) {
824 aservice->nRequestsRunning++;
825 /* just started call in minProcs pool, need fewer to maintain
827 if (aservice->nRequestsRunning <= aservice->minProcs)
830 MUTEX_EXIT(&rx_quota_mutex);
833 MUTEX_EXIT(&rx_quota_mutex);
839 ReturnToServerPool(struct rx_service *aservice)
841 aservice->nRequestsRunning--;
842 MUTEX_ENTER(&rx_quota_mutex);
843 if (aservice->nRequestsRunning < aservice->minProcs)
846 MUTEX_EXIT(&rx_quota_mutex);
849 #else /* RX_ENABLE_LOCKS */
851 QuotaOK(struct rx_service *aservice)
854 /* under min quota, we're OK */
855 if (aservice->nRequestsRunning < aservice->minProcs)
858 /* check if over max quota */
859 if (aservice->nRequestsRunning >= aservice->maxProcs)
862 /* otherwise, can use only if there are enough to allow everyone
863 * to go to their min quota after this guy starts.
865 MUTEX_ENTER(&rx_quota_mutex);
866 if (rxi_availProcs > rxi_minDeficit)
868 MUTEX_EXIT(&rx_quota_mutex);
871 #endif /* RX_ENABLE_LOCKS */
874 /* Called by rx_StartServer to start up lwp's to service calls.
875 NExistingProcs gives the number of procs already existing, and which
876 therefore needn't be created. */
878 rxi_StartServerProcs(int nExistingProcs)
880 struct rx_service *service;
885 /* For each service, reserve N processes, where N is the "minimum"
886 * number of processes that MUST be able to execute a request in parallel,
887 * at any time, for that process. Also compute the maximum difference
888 * between any service's maximum number of processes that can run
889 * (i.e. the maximum number that ever will be run, and a guarantee
890 * that this number will run if other services aren't running), and its
891 * minimum number. The result is the extra number of processes that
892 * we need in order to provide the latter guarantee */
893 for (i = 0; i < RX_MAX_SERVICES; i++) {
895 service = rx_services[i];
896 if (service == (struct rx_service *)0)
898 nProcs += service->minProcs;
899 diff = service->maxProcs - service->minProcs;
903 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
904 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
905 for (i = 0; i < nProcs; i++) {
906 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
912 /* This routine is only required on Windows */
914 rx_StartClientThread(void)
916 #ifdef AFS_PTHREAD_ENV
918 pid = pthread_self();
919 #endif /* AFS_PTHREAD_ENV */
921 #endif /* AFS_NT40_ENV */
923 /* This routine must be called if any services are exported. If the
924 * donateMe flag is set, the calling process is donated to the server
927 rx_StartServer(int donateMe)
929 struct rx_service *service;
935 /* Start server processes, if necessary (exact function is dependent
936 * on the implementation environment--kernel or user space). DonateMe
937 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
938 * case, one less new proc will be created rx_StartServerProcs.
940 rxi_StartServerProcs(donateMe);
942 /* count up the # of threads in minProcs, and add set the min deficit to
943 * be that value, too.
945 for (i = 0; i < RX_MAX_SERVICES; i++) {
946 service = rx_services[i];
947 if (service == (struct rx_service *)0)
949 MUTEX_ENTER(&rx_quota_mutex);
950 rxi_totalMin += service->minProcs;
951 /* below works even if a thread is running, since minDeficit would
952 * still have been decremented and later re-incremented.
954 rxi_minDeficit += service->minProcs;
955 MUTEX_EXIT(&rx_quota_mutex);
958 /* Turn on reaping of idle server connections */
959 rxi_ReapConnections(NULL, NULL, NULL, 0);
968 #ifdef AFS_PTHREAD_ENV
970 pid = afs_pointer_to_int(pthread_self());
971 #else /* AFS_PTHREAD_ENV */
973 LWP_CurrentProcess(&pid);
974 #endif /* AFS_PTHREAD_ENV */
976 sprintf(name, "srv_%d", ++nProcs);
978 (*registerProgram) (pid, name);
980 #endif /* AFS_NT40_ENV */
981 rx_ServerProc(NULL); /* Never returns */
983 #ifdef RX_ENABLE_TSFPQ
984 /* no use leaving packets around in this thread's local queue if
985 * it isn't getting donated to the server thread pool.
987 rxi_FlushLocalPacketsTSFPQ();
988 #endif /* RX_ENABLE_TSFPQ */
992 /* Create a new client connection to the specified service, using the
993 * specified security object to implement the security model for this
995 struct rx_connection *
996 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
997 struct rx_securityClass *securityObject,
998 int serviceSecurityIndex)
1002 struct rx_connection *conn;
1007 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1008 "serviceSecurityIndex %d)\n",
1009 ntohl(shost), ntohs(sport), sservice, securityObject,
1010 serviceSecurityIndex));
1012 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1013 * the case of kmem_alloc? */
1014 conn = rxi_AllocConnection();
1015 #ifdef RX_ENABLE_LOCKS
1016 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1017 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1018 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1021 MUTEX_ENTER(&rx_connHashTable_lock);
1022 cid = (rx_nextCid += RX_MAXCALLS);
1023 conn->type = RX_CLIENT_CONNECTION;
1025 conn->epoch = rx_epoch;
1026 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
1027 conn->serviceId = sservice;
1028 conn->securityObject = securityObject;
1029 conn->securityData = (void *) 0;
1030 conn->securityIndex = serviceSecurityIndex;
1031 rx_SetConnDeadTime(conn, rx_connDeadTime);
1032 rx_SetConnSecondsUntilNatPing(conn, 0);
1033 conn->ackRate = RX_FAST_ACK_RATE;
1034 conn->nSpecific = 0;
1035 conn->specific = NULL;
1036 conn->challengeEvent = NULL;
1037 conn->delayedAbortEvent = NULL;
1038 conn->abortCount = 0;
1040 for (i = 0; i < RX_MAXCALLS; i++) {
1041 conn->twind[i] = rx_initSendWindow;
1042 conn->rwind[i] = rx_initReceiveWindow;
1043 conn->lastBusy[i] = 0;
1046 RXS_NewConnection(securityObject, conn);
1048 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1050 conn->refCount++; /* no lock required since only this thread knows... */
1051 conn->next = rx_connHashTable[hashindex];
1052 rx_connHashTable[hashindex] = conn;
1053 if (rx_stats_active)
1054 rx_atomic_inc(&rx_stats.nClientConns);
1055 MUTEX_EXIT(&rx_connHashTable_lock);
1061 * Ensure a connection's timeout values are valid.
1063 * @param[in] conn The connection to check
1065 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1066 * unless idleDeadTime and/or hardDeadTime are not set
1070 rxi_CheckConnTimeouts(struct rx_connection *conn)
1072 /* a connection's timeouts must have the relationship
1073 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1074 * total loss of network to a peer may cause an idle timeout instead of a
1075 * dead timeout, simply because the idle timeout gets hit first. Also set
1076 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1077 /* this logic is slightly complicated by the fact that
1078 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1080 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1081 if (conn->idleDeadTime) {
1082 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1084 if (conn->hardDeadTime) {
1085 if (conn->idleDeadTime) {
1086 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1088 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1094 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1096 /* The idea is to set the dead time to a value that allows several
1097 * keepalives to be dropped without timing out the connection. */
1098 conn->secondsUntilDead = seconds;
1099 rxi_CheckConnTimeouts(conn);
1100 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1104 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1106 conn->hardDeadTime = seconds;
1107 rxi_CheckConnTimeouts(conn);
1111 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1113 conn->idleDeadTime = seconds;
1114 conn->idleDeadDetection = (seconds ? 1 : 0);
1115 rxi_CheckConnTimeouts(conn);
1118 int rxi_lowPeerRefCount = 0;
1119 int rxi_lowConnRefCount = 0;
1122 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1123 * NOTE: must not be called with rx_connHashTable_lock held.
1126 rxi_CleanupConnection(struct rx_connection *conn)
1128 /* Notify the service exporter, if requested, that this connection
1129 * is being destroyed */
1130 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1131 (*conn->service->destroyConnProc) (conn);
1133 /* Notify the security module that this connection is being destroyed */
1134 RXS_DestroyConnection(conn->securityObject, conn);
1136 /* If this is the last connection using the rx_peer struct, set its
1137 * idle time to now. rxi_ReapConnections will reap it if it's still
1138 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1140 MUTEX_ENTER(&rx_peerHashTable_lock);
1141 if (conn->peer->refCount < 2) {
1142 conn->peer->idleWhen = clock_Sec();
1143 if (conn->peer->refCount < 1) {
1144 conn->peer->refCount = 1;
1145 if (rx_stats_active) {
1146 MUTEX_ENTER(&rx_stats_mutex);
1147 rxi_lowPeerRefCount++;
1148 MUTEX_EXIT(&rx_stats_mutex);
1152 conn->peer->refCount--;
1153 MUTEX_EXIT(&rx_peerHashTable_lock);
1155 if (rx_stats_active)
1157 if (conn->type == RX_SERVER_CONNECTION)
1158 rx_atomic_dec(&rx_stats.nServerConns);
1160 rx_atomic_dec(&rx_stats.nClientConns);
1163 if (conn->specific) {
1165 for (i = 0; i < conn->nSpecific; i++) {
1166 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1167 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1168 conn->specific[i] = NULL;
1170 free(conn->specific);
1172 conn->specific = NULL;
1173 conn->nSpecific = 0;
1174 #endif /* !KERNEL */
1176 MUTEX_DESTROY(&conn->conn_call_lock);
1177 MUTEX_DESTROY(&conn->conn_data_lock);
1178 CV_DESTROY(&conn->conn_call_cv);
1180 rxi_FreeConnection(conn);
1183 /* Destroy the specified connection */
1185 rxi_DestroyConnection(struct rx_connection *conn)
1187 MUTEX_ENTER(&rx_connHashTable_lock);
1188 rxi_DestroyConnectionNoLock(conn);
1189 /* conn should be at the head of the cleanup list */
1190 if (conn == rx_connCleanup_list) {
1191 rx_connCleanup_list = rx_connCleanup_list->next;
1192 MUTEX_EXIT(&rx_connHashTable_lock);
1193 rxi_CleanupConnection(conn);
1195 #ifdef RX_ENABLE_LOCKS
1197 MUTEX_EXIT(&rx_connHashTable_lock);
1199 #endif /* RX_ENABLE_LOCKS */
1203 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1205 struct rx_connection **conn_ptr;
1207 struct rx_packet *packet;
1214 MUTEX_ENTER(&conn->conn_data_lock);
1215 MUTEX_ENTER(&rx_refcnt_mutex);
1216 if (conn->refCount > 0)
1219 if (rx_stats_active) {
1220 MUTEX_ENTER(&rx_stats_mutex);
1221 rxi_lowConnRefCount++;
1222 MUTEX_EXIT(&rx_stats_mutex);
1226 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1227 /* Busy; wait till the last guy before proceeding */
1228 MUTEX_EXIT(&rx_refcnt_mutex);
1229 MUTEX_EXIT(&conn->conn_data_lock);
1234 /* If the client previously called rx_NewCall, but it is still
1235 * waiting, treat this as a running call, and wait to destroy the
1236 * connection later when the call completes. */
1237 if ((conn->type == RX_CLIENT_CONNECTION)
1238 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1239 conn->flags |= RX_CONN_DESTROY_ME;
1240 MUTEX_EXIT(&conn->conn_data_lock);
1244 MUTEX_EXIT(&rx_refcnt_mutex);
1245 MUTEX_EXIT(&conn->conn_data_lock);
1247 /* Check for extant references to this connection */
1248 MUTEX_ENTER(&conn->conn_call_lock);
1249 for (i = 0; i < RX_MAXCALLS; i++) {
1250 struct rx_call *call = conn->call[i];
1253 if (conn->type == RX_CLIENT_CONNECTION) {
1254 MUTEX_ENTER(&call->lock);
1255 if (call->delayedAckEvent) {
1256 /* Push the final acknowledgment out now--there
1257 * won't be a subsequent call to acknowledge the
1258 * last reply packets */
1259 rxevent_Cancel(&call->delayedAckEvent, call,
1260 RX_CALL_REFCOUNT_DELAY);
1261 if (call->state == RX_STATE_PRECALL
1262 || call->state == RX_STATE_ACTIVE) {
1263 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1265 rxi_AckAll(NULL, call, 0);
1268 MUTEX_EXIT(&call->lock);
1272 MUTEX_EXIT(&conn->conn_call_lock);
1274 #ifdef RX_ENABLE_LOCKS
1276 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1277 MUTEX_EXIT(&conn->conn_data_lock);
1279 /* Someone is accessing a packet right now. */
1283 #endif /* RX_ENABLE_LOCKS */
1286 /* Don't destroy the connection if there are any call
1287 * structures still in use */
1288 MUTEX_ENTER(&conn->conn_data_lock);
1289 conn->flags |= RX_CONN_DESTROY_ME;
1290 MUTEX_EXIT(&conn->conn_data_lock);
1295 if (conn->natKeepAliveEvent) {
1296 rxi_NatKeepAliveOff(conn);
1299 if (conn->delayedAbortEvent) {
1300 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
1301 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1303 MUTEX_ENTER(&conn->conn_data_lock);
1304 rxi_SendConnectionAbort(conn, packet, 0, 1);
1305 MUTEX_EXIT(&conn->conn_data_lock);
1306 rxi_FreePacket(packet);
1310 /* Remove from connection hash table before proceeding */
1312 &rx_connHashTable[CONN_HASH
1313 (peer->host, peer->port, conn->cid, conn->epoch,
1315 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1316 if (*conn_ptr == conn) {
1317 *conn_ptr = conn->next;
1321 /* if the conn that we are destroying was the last connection, then we
1322 * clear rxLastConn as well */
1323 if (rxLastConn == conn)
1326 /* Make sure the connection is completely reset before deleting it. */
1327 /* get rid of pending events that could zap us later */
1328 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
1329 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
1330 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
1332 /* Add the connection to the list of destroyed connections that
1333 * need to be cleaned up. This is necessary to avoid deadlocks
1334 * in the routines we call to inform others that this connection is
1335 * being destroyed. */
1336 conn->next = rx_connCleanup_list;
1337 rx_connCleanup_list = conn;
1340 /* Externally available version */
1342 rx_DestroyConnection(struct rx_connection *conn)
1347 rxi_DestroyConnection(conn);
1352 rx_GetConnection(struct rx_connection *conn)
1357 MUTEX_ENTER(&rx_refcnt_mutex);
1359 MUTEX_EXIT(&rx_refcnt_mutex);
1363 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1364 /* Wait for the transmit queue to no longer be busy.
1365 * requires the call->lock to be held */
1367 rxi_WaitforTQBusy(struct rx_call *call) {
1368 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1369 call->flags |= RX_CALL_TQ_WAIT;
1371 #ifdef RX_ENABLE_LOCKS
1372 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1373 CV_WAIT(&call->cv_tq, &call->lock);
1374 #else /* RX_ENABLE_LOCKS */
1375 osi_rxSleep(&call->tq);
1376 #endif /* RX_ENABLE_LOCKS */
1378 if (call->tqWaiters == 0) {
1379 call->flags &= ~RX_CALL_TQ_WAIT;
1386 rxi_WakeUpTransmitQueue(struct rx_call *call)
1388 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1389 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1390 call, call->tqWaiters, call->flags));
1391 #ifdef RX_ENABLE_LOCKS
1392 osirx_AssertMine(&call->lock, "rxi_Start start");
1393 CV_BROADCAST(&call->cv_tq);
1394 #else /* RX_ENABLE_LOCKS */
1395 osi_rxWakeup(&call->tq);
1396 #endif /* RX_ENABLE_LOCKS */
1400 /* Start a new rx remote procedure call, on the specified connection.
1401 * If wait is set to 1, wait for a free call channel; otherwise return
1402 * 0. Maxtime gives the maximum number of seconds this call may take,
1403 * after rx_NewCall returns. After this time interval, a call to any
1404 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1405 * For fine grain locking, we hold the conn_call_lock in order to
1406 * to ensure that we don't get signalle after we found a call in an active
1407 * state and before we go to sleep.
1410 rx_NewCall(struct rx_connection *conn)
1412 int i, wait, ignoreBusy = 1;
1413 struct rx_call *call;
1414 struct clock queueTime;
1415 afs_uint32 leastBusy = 0;
1419 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1422 clock_GetTime(&queueTime);
1424 * Check if there are others waiting for a new call.
1425 * If so, let them go first to avoid starving them.
1426 * This is a fairly simple scheme, and might not be
1427 * a complete solution for large numbers of waiters.
1429 * makeCallWaiters keeps track of the number of
1430 * threads waiting to make calls and the
1431 * RX_CONN_MAKECALL_WAITING flag bit is used to
1432 * indicate that there are indeed calls waiting.
1433 * The flag is set when the waiter is incremented.
1434 * It is only cleared when makeCallWaiters is 0.
1435 * This prevents us from accidently destroying the
1436 * connection while it is potentially about to be used.
1438 MUTEX_ENTER(&conn->conn_call_lock);
1439 MUTEX_ENTER(&conn->conn_data_lock);
1440 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1441 conn->flags |= RX_CONN_MAKECALL_WAITING;
1442 conn->makeCallWaiters++;
1443 MUTEX_EXIT(&conn->conn_data_lock);
1445 #ifdef RX_ENABLE_LOCKS
1446 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1450 MUTEX_ENTER(&conn->conn_data_lock);
1451 conn->makeCallWaiters--;
1452 if (conn->makeCallWaiters == 0)
1453 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1456 /* We are now the active thread in rx_NewCall */
1457 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1458 MUTEX_EXIT(&conn->conn_data_lock);
1463 for (i = 0; i < RX_MAXCALLS; i++) {
1464 call = conn->call[i];
1466 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1467 /* we're not ignoring busy call slots; only look at the
1468 * call slot that is the "least" busy */
1472 if (call->state == RX_STATE_DALLY) {
1473 MUTEX_ENTER(&call->lock);
1474 if (call->state == RX_STATE_DALLY) {
1475 if (ignoreBusy && conn->lastBusy[i]) {
1476 /* if we're ignoring busy call slots, skip any ones that
1477 * have lastBusy set */
1478 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1479 leastBusy = conn->lastBusy[i];
1481 MUTEX_EXIT(&call->lock);
1486 * We are setting the state to RX_STATE_RESET to
1487 * ensure that no one else will attempt to use this
1488 * call once we drop the conn->conn_call_lock and
1489 * call->lock. We must drop the conn->conn_call_lock
1490 * before calling rxi_ResetCall because the process
1491 * of clearing the transmit queue can block for an
1492 * extended period of time. If we block while holding
1493 * the conn->conn_call_lock, then all rx_EndCall
1494 * processing will block as well. This has a detrimental
1495 * effect on overall system performance.
1497 call->state = RX_STATE_RESET;
1498 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1499 (*call->callNumber)++;
1500 MUTEX_EXIT(&conn->conn_call_lock);
1501 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1502 rxi_ResetCall(call, 0);
1503 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1507 * If we failed to be able to safely obtain the
1508 * conn->conn_call_lock we will have to drop the
1509 * call->lock to avoid a deadlock. When the call->lock
1510 * is released the state of the call can change. If it
1511 * is no longer RX_STATE_RESET then some other thread is
1514 MUTEX_EXIT(&call->lock);
1515 MUTEX_ENTER(&conn->conn_call_lock);
1516 MUTEX_ENTER(&call->lock);
1518 if (call->state == RX_STATE_RESET)
1522 * If we get here it means that after dropping
1523 * the conn->conn_call_lock and call->lock that
1524 * the call is no longer ours. If we can't find
1525 * a free call in the remaining slots we should
1526 * not go immediately to RX_CONN_MAKECALL_WAITING
1527 * because by dropping the conn->conn_call_lock
1528 * we have given up synchronization with rx_EndCall.
1529 * Instead, cycle through one more time to see if
1530 * we can find a call that can call our own.
1532 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1535 MUTEX_EXIT(&call->lock);
1538 if (ignoreBusy && conn->lastBusy[i]) {
1539 /* if we're ignoring busy call slots, skip any ones that
1540 * have lastBusy set */
1541 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1542 leastBusy = conn->lastBusy[i];
1547 /* rxi_NewCall returns with mutex locked */
1548 call = rxi_NewCall(conn, i);
1549 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1553 if (i < RX_MAXCALLS) {
1554 conn->lastBusy[i] = 0;
1555 call->flags &= ~RX_CALL_PEER_BUSY;
1560 if (leastBusy && ignoreBusy) {
1561 /* we didn't find a useable call slot, but we did see at least one
1562 * 'busy' slot; look again and only use a slot with the 'least
1568 MUTEX_ENTER(&conn->conn_data_lock);
1569 conn->flags |= RX_CONN_MAKECALL_WAITING;
1570 conn->makeCallWaiters++;
1571 MUTEX_EXIT(&conn->conn_data_lock);
1573 #ifdef RX_ENABLE_LOCKS
1574 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1578 MUTEX_ENTER(&conn->conn_data_lock);
1579 conn->makeCallWaiters--;
1580 if (conn->makeCallWaiters == 0)
1581 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1582 MUTEX_EXIT(&conn->conn_data_lock);
1584 /* Client is initially in send mode */
1585 call->state = RX_STATE_ACTIVE;
1586 call->error = conn->error;
1588 call->mode = RX_MODE_ERROR;
1590 call->mode = RX_MODE_SENDING;
1592 /* remember start time for call in case we have hard dead time limit */
1593 call->queueTime = queueTime;
1594 clock_GetTime(&call->startTime);
1595 hzero(call->bytesSent);
1596 hzero(call->bytesRcvd);
1598 /* Turn on busy protocol. */
1599 rxi_KeepAliveOn(call);
1601 /* Attempt MTU discovery */
1602 rxi_GrowMTUOn(call);
1605 * We are no longer the active thread in rx_NewCall
1607 MUTEX_ENTER(&conn->conn_data_lock);
1608 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1609 MUTEX_EXIT(&conn->conn_data_lock);
1612 * Wake up anyone else who might be giving us a chance to
1613 * run (see code above that avoids resource starvation).
1615 #ifdef RX_ENABLE_LOCKS
1616 CV_BROADCAST(&conn->conn_call_cv);
1620 MUTEX_EXIT(&conn->conn_call_lock);
1622 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1623 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1624 osi_Panic("rx_NewCall call about to be used without an empty tq");
1626 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1628 MUTEX_EXIT(&call->lock);
1631 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1636 rxi_HasActiveCalls(struct rx_connection *aconn)
1639 struct rx_call *tcall;
1643 for (i = 0; i < RX_MAXCALLS; i++) {
1644 if ((tcall = aconn->call[i])) {
1645 if ((tcall->state == RX_STATE_ACTIVE)
1646 || (tcall->state == RX_STATE_PRECALL)) {
1657 rxi_GetCallNumberVector(struct rx_connection *aconn,
1658 afs_int32 * aint32s)
1661 struct rx_call *tcall;
1665 MUTEX_ENTER(&aconn->conn_call_lock);
1666 for (i = 0; i < RX_MAXCALLS; i++) {
1667 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1668 aint32s[i] = aconn->callNumber[i] + 1;
1670 aint32s[i] = aconn->callNumber[i];
1672 MUTEX_EXIT(&aconn->conn_call_lock);
1678 rxi_SetCallNumberVector(struct rx_connection *aconn,
1679 afs_int32 * aint32s)
1682 struct rx_call *tcall;
1686 MUTEX_ENTER(&aconn->conn_call_lock);
1687 for (i = 0; i < RX_MAXCALLS; i++) {
1688 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1689 aconn->callNumber[i] = aint32s[i] - 1;
1691 aconn->callNumber[i] = aint32s[i];
1693 MUTEX_EXIT(&aconn->conn_call_lock);
1698 /* Advertise a new service. A service is named locally by a UDP port
1699 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1702 char *serviceName; Name for identification purposes (e.g. the
1703 service name might be used for probing for
1706 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1707 char *serviceName, struct rx_securityClass **securityObjects,
1708 int nSecurityObjects,
1709 afs_int32(*serviceProc) (struct rx_call * acall))
1711 osi_socket socket = OSI_NULLSOCKET;
1712 struct rx_service *tservice;
1718 if (serviceId == 0) {
1720 "rx_NewService: service id for service %s is not non-zero.\n",
1727 "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",
1735 tservice = rxi_AllocService();
1738 #ifdef RX_ENABLE_LOCKS
1739 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1742 for (i = 0; i < RX_MAX_SERVICES; i++) {
1743 struct rx_service *service = rx_services[i];
1745 if (port == service->servicePort && host == service->serviceHost) {
1746 if (service->serviceId == serviceId) {
1747 /* The identical service has already been
1748 * installed; if the caller was intending to
1749 * change the security classes used by this
1750 * service, he/she loses. */
1752 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1753 serviceName, serviceId, service->serviceName);
1755 rxi_FreeService(tservice);
1758 /* Different service, same port: re-use the socket
1759 * which is bound to the same port */
1760 socket = service->socket;
1763 if (socket == OSI_NULLSOCKET) {
1764 /* If we don't already have a socket (from another
1765 * service on same port) get a new one */
1766 socket = rxi_GetHostUDPSocket(host, port);
1767 if (socket == OSI_NULLSOCKET) {
1769 rxi_FreeService(tservice);
1774 service->socket = socket;
1775 service->serviceHost = host;
1776 service->servicePort = port;
1777 service->serviceId = serviceId;
1778 service->serviceName = serviceName;
1779 service->nSecurityObjects = nSecurityObjects;
1780 service->securityObjects = securityObjects;
1781 service->minProcs = 0;
1782 service->maxProcs = 1;
1783 service->idleDeadTime = 60;
1784 service->idleDeadErr = 0;
1785 service->connDeadTime = rx_connDeadTime;
1786 service->executeRequestProc = serviceProc;
1787 service->checkReach = 0;
1788 service->nSpecific = 0;
1789 service->specific = NULL;
1790 rx_services[i] = service; /* not visible until now */
1796 rxi_FreeService(tservice);
1797 (osi_Msg "rx_NewService: cannot support > %d services\n",
1802 /* Set configuration options for all of a service's security objects */
1805 rx_SetSecurityConfiguration(struct rx_service *service,
1806 rx_securityConfigVariables type,
1810 for (i = 0; i<service->nSecurityObjects; i++) {
1811 if (service->securityObjects[i]) {
1812 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1820 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1821 struct rx_securityClass **securityObjects, int nSecurityObjects,
1822 afs_int32(*serviceProc) (struct rx_call * acall))
1824 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1827 /* Generic request processing loop. This routine should be called
1828 * by the implementation dependent rx_ServerProc. If socketp is
1829 * non-null, it will be set to the file descriptor that this thread
1830 * is now listening on. If socketp is null, this routine will never
1833 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1835 struct rx_call *call;
1837 struct rx_service *tservice = NULL;
1844 call = rx_GetCall(threadID, tservice, socketp);
1845 if (socketp && *socketp != OSI_NULLSOCKET) {
1846 /* We are now a listener thread */
1852 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1853 #ifdef RX_ENABLE_LOCKS
1855 #endif /* RX_ENABLE_LOCKS */
1856 afs_termState = AFSOP_STOP_AFS;
1857 afs_osi_Wakeup(&afs_termState);
1858 #ifdef RX_ENABLE_LOCKS
1860 #endif /* RX_ENABLE_LOCKS */
1865 /* if server is restarting( typically smooth shutdown) then do not
1866 * allow any new calls.
1869 if (rx_tranquil && (call != NULL)) {
1873 MUTEX_ENTER(&call->lock);
1875 rxi_CallError(call, RX_RESTARTING);
1876 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1878 MUTEX_EXIT(&call->lock);
1883 tservice = call->conn->service;
1885 if (tservice->beforeProc)
1886 (*tservice->beforeProc) (call);
1888 code = tservice->executeRequestProc(call);
1890 if (tservice->afterProc)
1891 (*tservice->afterProc) (call, code);
1893 rx_EndCall(call, code);
1895 if (tservice->postProc)
1896 (*tservice->postProc) (code);
1898 if (rx_stats_active) {
1899 MUTEX_ENTER(&rx_stats_mutex);
1901 MUTEX_EXIT(&rx_stats_mutex);
1908 rx_WakeupServerProcs(void)
1910 struct rx_serverQueueEntry *np, *tqp;
1914 MUTEX_ENTER(&rx_serverPool_lock);
1916 #ifdef RX_ENABLE_LOCKS
1917 if (rx_waitForPacket)
1918 CV_BROADCAST(&rx_waitForPacket->cv);
1919 #else /* RX_ENABLE_LOCKS */
1920 if (rx_waitForPacket)
1921 osi_rxWakeup(rx_waitForPacket);
1922 #endif /* RX_ENABLE_LOCKS */
1923 MUTEX_ENTER(&freeSQEList_lock);
1924 for (np = rx_FreeSQEList; np; np = tqp) {
1925 tqp = *(struct rx_serverQueueEntry **)np;
1926 #ifdef RX_ENABLE_LOCKS
1927 CV_BROADCAST(&np->cv);
1928 #else /* RX_ENABLE_LOCKS */
1930 #endif /* RX_ENABLE_LOCKS */
1932 MUTEX_EXIT(&freeSQEList_lock);
1933 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1934 #ifdef RX_ENABLE_LOCKS
1935 CV_BROADCAST(&np->cv);
1936 #else /* RX_ENABLE_LOCKS */
1938 #endif /* RX_ENABLE_LOCKS */
1940 MUTEX_EXIT(&rx_serverPool_lock);
1945 * One thing that seems to happen is that all the server threads get
1946 * tied up on some empty or slow call, and then a whole bunch of calls
1947 * arrive at once, using up the packet pool, so now there are more
1948 * empty calls. The most critical resources here are server threads
1949 * and the free packet pool. The "doreclaim" code seems to help in
1950 * general. I think that eventually we arrive in this state: there
1951 * are lots of pending calls which do have all their packets present,
1952 * so they won't be reclaimed, are multi-packet calls, so they won't
1953 * be scheduled until later, and thus are tying up most of the free
1954 * packet pool for a very long time.
1956 * 1. schedule multi-packet calls if all the packets are present.
1957 * Probably CPU-bound operation, useful to return packets to pool.
1958 * Do what if there is a full window, but the last packet isn't here?
1959 * 3. preserve one thread which *only* runs "best" calls, otherwise
1960 * it sleeps and waits for that type of call.
1961 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1962 * the current dataquota business is badly broken. The quota isn't adjusted
1963 * to reflect how many packets are presently queued for a running call.
1964 * So, when we schedule a queued call with a full window of packets queued
1965 * up for it, that *should* free up a window full of packets for other 2d-class
1966 * calls to be able to use from the packet pool. But it doesn't.
1968 * NB. Most of the time, this code doesn't run -- since idle server threads
1969 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1970 * as a new call arrives.
1972 /* Sleep until a call arrives. Returns a pointer to the call, ready
1973 * for an rx_Read. */
1974 #ifdef RX_ENABLE_LOCKS
1976 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1978 struct rx_serverQueueEntry *sq;
1979 struct rx_call *call = (struct rx_call *)0;
1980 struct rx_service *service = NULL;
1982 MUTEX_ENTER(&freeSQEList_lock);
1984 if ((sq = rx_FreeSQEList)) {
1985 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1986 MUTEX_EXIT(&freeSQEList_lock);
1987 } else { /* otherwise allocate a new one and return that */
1988 MUTEX_EXIT(&freeSQEList_lock);
1989 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1990 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1991 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1994 MUTEX_ENTER(&rx_serverPool_lock);
1995 if (cur_service != NULL) {
1996 ReturnToServerPool(cur_service);
1999 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2000 struct rx_call *tcall, *ncall, *choice2 = NULL;
2002 /* Scan for eligible incoming calls. A call is not eligible
2003 * if the maximum number of calls for its service type are
2004 * already executing */
2005 /* One thread will process calls FCFS (to prevent starvation),
2006 * while the other threads may run ahead looking for calls which
2007 * have all their input data available immediately. This helps
2008 * keep threads from blocking, waiting for data from the client. */
2009 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2010 service = tcall->conn->service;
2011 if (!QuotaOK(service)) {
2014 MUTEX_ENTER(&rx_pthread_mutex);
2015 if (tno == rxi_fcfs_thread_num
2016 || queue_IsLast(&rx_incomingCallQueue, tcall)) {
2017 MUTEX_EXIT(&rx_pthread_mutex);
2018 /* If we're the fcfs thread , then we'll just use
2019 * this call. If we haven't been able to find an optimal
2020 * choice, and we're at the end of the list, then use a
2021 * 2d choice if one has been identified. Otherwise... */
2022 call = (choice2 ? choice2 : tcall);
2023 service = call->conn->service;
2025 MUTEX_EXIT(&rx_pthread_mutex);
2026 if (!queue_IsEmpty(&tcall->rq)) {
2027 struct rx_packet *rp;
2028 rp = queue_First(&tcall->rq, rx_packet);
2029 if (rp->header.seq == 1) {
2031 || (rp->header.flags & RX_LAST_PACKET)) {
2033 } else if (rxi_2dchoice && !choice2
2034 && !(tcall->flags & RX_CALL_CLEARED)
2035 && (tcall->rprev > rxi_HardAckRate)) {
2045 ReturnToServerPool(service);
2052 MUTEX_EXIT(&rx_serverPool_lock);
2053 MUTEX_ENTER(&call->lock);
2055 if (call->flags & RX_CALL_WAIT_PROC) {
2056 call->flags &= ~RX_CALL_WAIT_PROC;
2057 rx_atomic_dec(&rx_nWaiting);
2060 if (call->state != RX_STATE_PRECALL || call->error) {
2061 MUTEX_EXIT(&call->lock);
2062 MUTEX_ENTER(&rx_serverPool_lock);
2063 ReturnToServerPool(service);
2068 if (queue_IsEmpty(&call->rq)
2069 || queue_First(&call->rq, rx_packet)->header.seq != 1)
2070 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2072 CLEAR_CALL_QUEUE_LOCK(call);
2075 /* If there are no eligible incoming calls, add this process
2076 * to the idle server queue, to wait for one */
2080 *socketp = OSI_NULLSOCKET;
2082 sq->socketp = socketp;
2083 queue_Append(&rx_idleServerQueue, sq);
2084 #ifndef AFS_AIX41_ENV
2085 rx_waitForPacket = sq;
2087 rx_waitingForPacket = sq;
2088 #endif /* AFS_AIX41_ENV */
2090 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2092 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2093 MUTEX_EXIT(&rx_serverPool_lock);
2094 return (struct rx_call *)0;
2097 } while (!(call = sq->newcall)
2098 && !(socketp && *socketp != OSI_NULLSOCKET));
2099 MUTEX_EXIT(&rx_serverPool_lock);
2101 MUTEX_ENTER(&call->lock);
2107 MUTEX_ENTER(&freeSQEList_lock);
2108 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2109 rx_FreeSQEList = sq;
2110 MUTEX_EXIT(&freeSQEList_lock);
2113 clock_GetTime(&call->startTime);
2114 call->state = RX_STATE_ACTIVE;
2115 call->mode = RX_MODE_RECEIVING;
2116 #ifdef RX_KERNEL_TRACE
2117 if (ICL_SETACTIVE(afs_iclSetp)) {
2118 int glockOwner = ISAFS_GLOCK();
2121 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2122 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2129 rxi_calltrace(RX_CALL_START, call);
2130 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2131 call->conn->service->servicePort, call->conn->service->serviceId,
2134 MUTEX_EXIT(&call->lock);
2135 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2137 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2142 #else /* RX_ENABLE_LOCKS */
2144 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2146 struct rx_serverQueueEntry *sq;
2147 struct rx_call *call = (struct rx_call *)0, *choice2;
2148 struct rx_service *service = NULL;
2152 MUTEX_ENTER(&freeSQEList_lock);
2154 if ((sq = rx_FreeSQEList)) {
2155 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2156 MUTEX_EXIT(&freeSQEList_lock);
2157 } else { /* otherwise allocate a new one and return that */
2158 MUTEX_EXIT(&freeSQEList_lock);
2159 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2160 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2161 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2163 MUTEX_ENTER(&sq->lock);
2165 if (cur_service != NULL) {
2166 cur_service->nRequestsRunning--;
2167 MUTEX_ENTER(&rx_quota_mutex);
2168 if (cur_service->nRequestsRunning < cur_service->minProcs)
2171 MUTEX_EXIT(&rx_quota_mutex);
2173 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2174 struct rx_call *tcall, *ncall;
2175 /* Scan for eligible incoming calls. A call is not eligible
2176 * if the maximum number of calls for its service type are
2177 * already executing */
2178 /* One thread will process calls FCFS (to prevent starvation),
2179 * while the other threads may run ahead looking for calls which
2180 * have all their input data available immediately. This helps
2181 * keep threads from blocking, waiting for data from the client. */
2182 choice2 = (struct rx_call *)0;
2183 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2184 service = tcall->conn->service;
2185 if (QuotaOK(service)) {
2186 MUTEX_ENTER(&rx_pthread_mutex);
2187 if (tno == rxi_fcfs_thread_num
2188 || !tcall->queue_item_header.next) {
2189 MUTEX_EXIT(&rx_pthread_mutex);
2190 /* If we're the fcfs thread, then we'll just use
2191 * this call. If we haven't been able to find an optimal
2192 * choice, and we're at the end of the list, then use a
2193 * 2d choice if one has been identified. Otherwise... */
2194 call = (choice2 ? choice2 : tcall);
2195 service = call->conn->service;
2197 MUTEX_EXIT(&rx_pthread_mutex);
2198 if (!queue_IsEmpty(&tcall->rq)) {
2199 struct rx_packet *rp;
2200 rp = queue_First(&tcall->rq, rx_packet);
2201 if (rp->header.seq == 1
2203 || (rp->header.flags & RX_LAST_PACKET))) {
2205 } else if (rxi_2dchoice && !choice2
2206 && !(tcall->flags & RX_CALL_CLEARED)
2207 && (tcall->rprev > rxi_HardAckRate)) {
2221 /* we can't schedule a call if there's no data!!! */
2222 /* send an ack if there's no data, if we're missing the
2223 * first packet, or we're missing something between first
2224 * and last -- there's a "hole" in the incoming data. */
2225 if (queue_IsEmpty(&call->rq)
2226 || queue_First(&call->rq, rx_packet)->header.seq != 1
2227 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2228 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2230 call->flags &= (~RX_CALL_WAIT_PROC);
2231 service->nRequestsRunning++;
2232 /* just started call in minProcs pool, need fewer to maintain
2234 MUTEX_ENTER(&rx_quota_mutex);
2235 if (service->nRequestsRunning <= service->minProcs)
2238 MUTEX_EXIT(&rx_quota_mutex);
2239 rx_atomic_dec(&rx_nWaiting);
2240 /* MUTEX_EXIT(&call->lock); */
2242 /* If there are no eligible incoming calls, add this process
2243 * to the idle server queue, to wait for one */
2246 *socketp = OSI_NULLSOCKET;
2248 sq->socketp = socketp;
2249 queue_Append(&rx_idleServerQueue, sq);
2253 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2255 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2256 return (struct rx_call *)0;
2259 } while (!(call = sq->newcall)
2260 && !(socketp && *socketp != OSI_NULLSOCKET));
2262 MUTEX_EXIT(&sq->lock);
2264 MUTEX_ENTER(&freeSQEList_lock);
2265 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2266 rx_FreeSQEList = sq;
2267 MUTEX_EXIT(&freeSQEList_lock);
2270 clock_GetTime(&call->startTime);
2271 call->state = RX_STATE_ACTIVE;
2272 call->mode = RX_MODE_RECEIVING;
2273 #ifdef RX_KERNEL_TRACE
2274 if (ICL_SETACTIVE(afs_iclSetp)) {
2275 int glockOwner = ISAFS_GLOCK();
2278 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2279 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2286 rxi_calltrace(RX_CALL_START, call);
2287 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2288 call->conn->service->servicePort, call->conn->service->serviceId,
2291 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2298 #endif /* RX_ENABLE_LOCKS */
2302 /* Establish a procedure to be called when a packet arrives for a
2303 * call. This routine will be called at most once after each call,
2304 * and will also be called if there is an error condition on the or
2305 * the call is complete. Used by multi rx to build a selection
2306 * function which determines which of several calls is likely to be a
2307 * good one to read from.
2308 * NOTE: the way this is currently implemented it is probably only a
2309 * good idea to (1) use it immediately after a newcall (clients only)
2310 * and (2) only use it once. Other uses currently void your warranty
2313 rx_SetArrivalProc(struct rx_call *call,
2314 void (*proc) (struct rx_call * call,
2317 void * handle, int arg)
2319 call->arrivalProc = proc;
2320 call->arrivalProcHandle = handle;
2321 call->arrivalProcArg = arg;
2324 /* Call is finished (possibly prematurely). Return rc to the peer, if
2325 * appropriate, and return the final error code from the conversation
2329 rx_EndCall(struct rx_call *call, afs_int32 rc)
2331 struct rx_connection *conn = call->conn;
2335 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2336 call, rc, call->error, call->abortCode));
2339 MUTEX_ENTER(&call->lock);
2341 if (rc == 0 && call->error == 0) {
2342 call->abortCode = 0;
2343 call->abortCount = 0;
2346 call->arrivalProc = (void (*)())0;
2347 if (rc && call->error == 0) {
2348 rxi_CallError(call, rc);
2349 call->mode = RX_MODE_ERROR;
2350 /* Send an abort message to the peer if this error code has
2351 * only just been set. If it was set previously, assume the
2352 * peer has already been sent the error code or will request it
2354 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2356 if (conn->type == RX_SERVER_CONNECTION) {
2357 /* Make sure reply or at least dummy reply is sent */
2358 if (call->mode == RX_MODE_RECEIVING) {
2359 MUTEX_EXIT(&call->lock);
2360 rxi_WriteProc(call, 0, 0);
2361 MUTEX_ENTER(&call->lock);
2363 if (call->mode == RX_MODE_SENDING) {
2364 MUTEX_EXIT(&call->lock);
2365 rxi_FlushWrite(call);
2366 MUTEX_ENTER(&call->lock);
2368 rxi_calltrace(RX_CALL_END, call);
2369 /* Call goes to hold state until reply packets are acknowledged */
2370 if (call->tfirst + call->nSoftAcked < call->tnext) {
2371 call->state = RX_STATE_HOLD;
2373 call->state = RX_STATE_DALLY;
2374 rxi_ClearTransmitQueue(call, 0);
2375 rxi_rto_cancel(call);
2376 rxevent_Cancel(&call->keepAliveEvent, call,
2377 RX_CALL_REFCOUNT_ALIVE);
2379 } else { /* Client connection */
2381 /* Make sure server receives input packets, in the case where
2382 * no reply arguments are expected */
2383 if ((call->mode == RX_MODE_SENDING)
2384 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2385 MUTEX_EXIT(&call->lock);
2386 (void)rxi_ReadProc(call, &dummy, 1);
2387 MUTEX_ENTER(&call->lock);
2390 /* If we had an outstanding delayed ack, be nice to the server
2391 * and force-send it now.
2393 if (call->delayedAckEvent) {
2394 rxevent_Cancel(&call->delayedAckEvent, call,
2395 RX_CALL_REFCOUNT_DELAY);
2396 rxi_SendDelayedAck(NULL, call, NULL, 0);
2399 /* We need to release the call lock since it's lower than the
2400 * conn_call_lock and we don't want to hold the conn_call_lock
2401 * over the rx_ReadProc call. The conn_call_lock needs to be held
2402 * here for the case where rx_NewCall is perusing the calls on
2403 * the connection structure. We don't want to signal until
2404 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2405 * have checked this call, found it active and by the time it
2406 * goes to sleep, will have missed the signal.
2408 MUTEX_EXIT(&call->lock);
2409 MUTEX_ENTER(&conn->conn_call_lock);
2410 MUTEX_ENTER(&call->lock);
2412 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2413 conn->lastBusy[call->channel] = 0;
2416 MUTEX_ENTER(&conn->conn_data_lock);
2417 conn->flags |= RX_CONN_BUSY;
2418 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2419 MUTEX_EXIT(&conn->conn_data_lock);
2420 #ifdef RX_ENABLE_LOCKS
2421 CV_BROADCAST(&conn->conn_call_cv);
2426 #ifdef RX_ENABLE_LOCKS
2428 MUTEX_EXIT(&conn->conn_data_lock);
2430 #endif /* RX_ENABLE_LOCKS */
2431 call->state = RX_STATE_DALLY;
2433 error = call->error;
2435 /* currentPacket, nLeft, and NFree must be zeroed here, because
2436 * ResetCall cannot: ResetCall may be called at splnet(), in the
2437 * kernel version, and may interrupt the macros rx_Read or
2438 * rx_Write, which run at normal priority for efficiency. */
2439 if (call->currentPacket) {
2440 #ifdef RX_TRACK_PACKETS
2441 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2443 rxi_FreePacket(call->currentPacket);
2444 call->currentPacket = (struct rx_packet *)0;
2447 call->nLeft = call->nFree = call->curlen = 0;
2449 /* Free any packets from the last call to ReadvProc/WritevProc */
2450 #ifdef RXDEBUG_PACKET
2452 #endif /* RXDEBUG_PACKET */
2453 rxi_FreePackets(0, &call->iovq);
2454 MUTEX_EXIT(&call->lock);
2456 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2457 if (conn->type == RX_CLIENT_CONNECTION) {
2458 MUTEX_ENTER(&conn->conn_data_lock);
2459 conn->flags &= ~RX_CONN_BUSY;
2460 MUTEX_EXIT(&conn->conn_data_lock);
2461 MUTEX_EXIT(&conn->conn_call_lock);
2465 * Map errors to the local host's errno.h format.
2467 error = ntoh_syserr_conv(error);
2471 #if !defined(KERNEL)
2473 /* Call this routine when shutting down a server or client (especially
2474 * clients). This will allow Rx to gracefully garbage collect server
2475 * connections, and reduce the number of retries that a server might
2476 * make to a dead client.
2477 * This is not quite right, since some calls may still be ongoing and
2478 * we can't lock them to destroy them. */
2482 struct rx_connection **conn_ptr, **conn_end;
2486 if (rxinit_status == 1) {
2488 return; /* Already shutdown. */
2490 rxi_DeleteCachedConnections();
2491 if (rx_connHashTable) {
2492 MUTEX_ENTER(&rx_connHashTable_lock);
2493 for (conn_ptr = &rx_connHashTable[0], conn_end =
2494 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2496 struct rx_connection *conn, *next;
2497 for (conn = *conn_ptr; conn; conn = next) {
2499 if (conn->type == RX_CLIENT_CONNECTION) {
2500 MUTEX_ENTER(&rx_refcnt_mutex);
2502 MUTEX_EXIT(&rx_refcnt_mutex);
2503 #ifdef RX_ENABLE_LOCKS
2504 rxi_DestroyConnectionNoLock(conn);
2505 #else /* RX_ENABLE_LOCKS */
2506 rxi_DestroyConnection(conn);
2507 #endif /* RX_ENABLE_LOCKS */
2511 #ifdef RX_ENABLE_LOCKS
2512 while (rx_connCleanup_list) {
2513 struct rx_connection *conn;
2514 conn = rx_connCleanup_list;
2515 rx_connCleanup_list = rx_connCleanup_list->next;
2516 MUTEX_EXIT(&rx_connHashTable_lock);
2517 rxi_CleanupConnection(conn);
2518 MUTEX_ENTER(&rx_connHashTable_lock);
2520 MUTEX_EXIT(&rx_connHashTable_lock);
2521 #endif /* RX_ENABLE_LOCKS */
2526 afs_winsockCleanup();
2534 /* if we wakeup packet waiter too often, can get in loop with two
2535 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2537 rxi_PacketsUnWait(void)
2539 if (!rx_waitingForPackets) {
2543 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2544 return; /* still over quota */
2547 rx_waitingForPackets = 0;
2548 #ifdef RX_ENABLE_LOCKS
2549 CV_BROADCAST(&rx_waitingForPackets_cv);
2551 osi_rxWakeup(&rx_waitingForPackets);
2557 /* ------------------Internal interfaces------------------------- */
2559 /* Return this process's service structure for the
2560 * specified socket and service */
2561 static struct rx_service *
2562 rxi_FindService(osi_socket socket, u_short serviceId)
2564 struct rx_service **sp;
2565 for (sp = &rx_services[0]; *sp; sp++) {
2566 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2572 #ifdef RXDEBUG_PACKET
2573 #ifdef KDUMP_RX_LOCK
2574 static struct rx_call_rx_lock *rx_allCallsp = 0;
2576 static struct rx_call *rx_allCallsp = 0;
2578 #endif /* RXDEBUG_PACKET */
2580 /* Allocate a call structure, for the indicated channel of the
2581 * supplied connection. The mode and state of the call must be set by
2582 * the caller. Returns the call with mutex locked. */
2583 static struct rx_call *
2584 rxi_NewCall(struct rx_connection *conn, int channel)
2586 struct rx_call *call;
2587 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2588 struct rx_call *cp; /* Call pointer temp */
2589 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2590 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2592 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2594 /* Grab an existing call structure, or allocate a new one.
2595 * Existing call structures are assumed to have been left reset by
2597 MUTEX_ENTER(&rx_freeCallQueue_lock);
2599 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2601 * EXCEPT that the TQ might not yet be cleared out.
2602 * Skip over those with in-use TQs.
2605 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2606 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2612 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2613 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2614 call = queue_First(&rx_freeCallQueue, rx_call);
2615 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2617 if (rx_stats_active)
2618 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2619 MUTEX_EXIT(&rx_freeCallQueue_lock);
2620 MUTEX_ENTER(&call->lock);
2621 CLEAR_CALL_QUEUE_LOCK(call);
2622 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2623 /* Now, if TQ wasn't cleared earlier, do it now. */
2624 rxi_WaitforTQBusy(call);
2625 if (call->flags & RX_CALL_TQ_CLEARME) {
2626 rxi_ClearTransmitQueue(call, 1);
2627 /*queue_Init(&call->tq);*/
2629 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2630 /* Bind the call to its connection structure */
2632 rxi_ResetCall(call, 1);
2635 call = rxi_Alloc(sizeof(struct rx_call));
2636 #ifdef RXDEBUG_PACKET
2637 call->allNextp = rx_allCallsp;
2638 rx_allCallsp = call;
2640 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2641 #else /* RXDEBUG_PACKET */
2642 rx_atomic_inc(&rx_stats.nCallStructs);
2643 #endif /* RXDEBUG_PACKET */
2645 MUTEX_EXIT(&rx_freeCallQueue_lock);
2646 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2647 MUTEX_ENTER(&call->lock);
2648 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2649 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2650 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2652 /* Initialize once-only items */
2653 queue_Init(&call->tq);
2654 queue_Init(&call->rq);
2655 queue_Init(&call->iovq);
2656 #ifdef RXDEBUG_PACKET
2657 call->rqc = call->tqc = call->iovqc = 0;
2658 #endif /* RXDEBUG_PACKET */
2659 /* Bind the call to its connection structure (prereq for reset) */
2661 rxi_ResetCall(call, 1);
2663 call->channel = channel;
2664 call->callNumber = &conn->callNumber[channel];
2665 call->rwind = conn->rwind[channel];
2666 call->twind = conn->twind[channel];
2667 /* Note that the next expected call number is retained (in
2668 * conn->callNumber[i]), even if we reallocate the call structure
2670 conn->call[channel] = call;
2671 /* if the channel's never been used (== 0), we should start at 1, otherwise
2672 * the call number is valid from the last time this channel was used */
2673 if (*call->callNumber == 0)
2674 *call->callNumber = 1;
2679 /* A call has been inactive long enough that so we can throw away
2680 * state, including the call structure, which is placed on the call
2683 * call->lock amd rx_refcnt_mutex are held upon entry.
2684 * haveCTLock is set when called from rxi_ReapConnections.
2686 * return 1 if the call is freed, 0 if not.
2689 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2691 int channel = call->channel;
2692 struct rx_connection *conn = call->conn;
2693 u_char state = call->state;
2696 * We are setting the state to RX_STATE_RESET to
2697 * ensure that no one else will attempt to use this
2698 * call once we drop the refcnt lock. We must drop
2699 * the refcnt lock before calling rxi_ResetCall
2700 * because it cannot be held across acquiring the
2701 * freepktQ lock. NewCall does the same.
2703 call->state = RX_STATE_RESET;
2704 MUTEX_EXIT(&rx_refcnt_mutex);
2705 rxi_ResetCall(call, 0);
2707 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2709 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2710 (*call->callNumber)++;
2712 if (call->conn->call[channel] == call)
2713 call->conn->call[channel] = 0;
2714 MUTEX_EXIT(&conn->conn_call_lock);
2717 * We couldn't obtain the conn_call_lock so we can't
2718 * disconnect the call from the connection. Set the
2719 * call state to dally so that the call can be reused.
2721 MUTEX_ENTER(&rx_refcnt_mutex);
2722 call->state = RX_STATE_DALLY;
2726 MUTEX_ENTER(&rx_freeCallQueue_lock);
2727 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2728 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2729 /* A call may be free even though its transmit queue is still in use.
2730 * Since we search the call list from head to tail, put busy calls at
2731 * the head of the list, and idle calls at the tail.
2733 if (call->flags & RX_CALL_TQ_BUSY)
2734 queue_Prepend(&rx_freeCallQueue, call);
2736 queue_Append(&rx_freeCallQueue, call);
2737 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2738 queue_Append(&rx_freeCallQueue, call);
2739 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2740 if (rx_stats_active)
2741 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2742 MUTEX_EXIT(&rx_freeCallQueue_lock);
2744 /* Destroy the connection if it was previously slated for
2745 * destruction, i.e. the Rx client code previously called
2746 * rx_DestroyConnection (client connections), or
2747 * rxi_ReapConnections called the same routine (server
2748 * connections). Only do this, however, if there are no
2749 * outstanding calls. Note that for fine grain locking, there appears
2750 * to be a deadlock in that rxi_FreeCall has a call locked and
2751 * DestroyConnectionNoLock locks each call in the conn. But note a
2752 * few lines up where we have removed this call from the conn.
2753 * If someone else destroys a connection, they either have no
2754 * call lock held or are going through this section of code.
2756 MUTEX_ENTER(&conn->conn_data_lock);
2757 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2758 MUTEX_ENTER(&rx_refcnt_mutex);
2760 MUTEX_EXIT(&rx_refcnt_mutex);
2761 MUTEX_EXIT(&conn->conn_data_lock);
2762 #ifdef RX_ENABLE_LOCKS
2764 rxi_DestroyConnectionNoLock(conn);
2766 rxi_DestroyConnection(conn);
2767 #else /* RX_ENABLE_LOCKS */
2768 rxi_DestroyConnection(conn);
2769 #endif /* RX_ENABLE_LOCKS */
2771 MUTEX_EXIT(&conn->conn_data_lock);
2773 MUTEX_ENTER(&rx_refcnt_mutex);
2777 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2778 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2781 rxi_Alloc(size_t size)
2785 if (rx_stats_active) {
2786 rx_atomic_add(&rxi_Allocsize, (int) size);
2787 rx_atomic_inc(&rxi_Alloccnt);
2791 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2792 afs_osi_Alloc_NoSleep(size);
2797 osi_Panic("rxi_Alloc error");
2803 rxi_Free(void *addr, size_t size)
2805 if (rx_stats_active) {
2806 rx_atomic_sub(&rxi_Allocsize, (int) size);
2807 rx_atomic_dec(&rxi_Alloccnt);
2809 osi_Free(addr, size);
2813 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2815 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2816 struct rx_peer *next = NULL;
2820 MUTEX_ENTER(&rx_peerHashTable_lock);
2822 peer_ptr = &rx_peerHashTable[0];
2823 peer_end = &rx_peerHashTable[rx_hashTableSize];
2826 for ( ; peer_ptr < peer_end; peer_ptr++) {
2829 for ( ; peer; peer = next) {
2831 if (host == peer->host)
2836 hashIndex = PEER_HASH(host, port);
2837 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2838 if ((peer->host == host) && (peer->port == port))
2843 MUTEX_ENTER(&rx_peerHashTable_lock);
2848 MUTEX_EXIT(&rx_peerHashTable_lock);
2850 MUTEX_ENTER(&peer->peer_lock);
2851 /* We don't handle dropping below min, so don't */
2852 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2853 peer->ifMTU=MIN(mtu, peer->ifMTU);
2854 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2855 /* if we tweaked this down, need to tune our peer MTU too */
2856 peer->MTU = MIN(peer->MTU, peer->natMTU);
2857 /* if we discovered a sub-1500 mtu, degrade */
2858 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2859 peer->maxDgramPackets = 1;
2860 /* We no longer have valid peer packet information */
2861 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2862 peer->maxPacketSize = 0;
2863 MUTEX_EXIT(&peer->peer_lock);
2865 MUTEX_ENTER(&rx_peerHashTable_lock);
2867 if (host && !port) {
2869 /* pick up where we left off */
2873 MUTEX_EXIT(&rx_peerHashTable_lock);
2876 /* Find the peer process represented by the supplied (host,port)
2877 * combination. If there is no appropriate active peer structure, a
2878 * new one will be allocated and initialized
2879 * The origPeer, if set, is a pointer to a peer structure on which the
2880 * refcount will be be decremented. This is used to replace the peer
2881 * structure hanging off a connection structure */
2883 rxi_FindPeer(afs_uint32 host, u_short port,
2884 struct rx_peer *origPeer, int create)
2888 hashIndex = PEER_HASH(host, port);
2889 MUTEX_ENTER(&rx_peerHashTable_lock);
2890 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2891 if ((pp->host == host) && (pp->port == port))
2896 pp = rxi_AllocPeer(); /* This bzero's *pp */
2897 pp->host = host; /* set here or in InitPeerParams is zero */
2899 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2900 queue_Init(&pp->congestionQueue);
2901 queue_Init(&pp->rpcStats);
2902 pp->next = rx_peerHashTable[hashIndex];
2903 rx_peerHashTable[hashIndex] = pp;
2904 rxi_InitPeerParams(pp);
2905 if (rx_stats_active)
2906 rx_atomic_inc(&rx_stats.nPeerStructs);
2913 origPeer->refCount--;
2914 MUTEX_EXIT(&rx_peerHashTable_lock);
2919 /* Find the connection at (host, port) started at epoch, and with the
2920 * given connection id. Creates the server connection if necessary.
2921 * The type specifies whether a client connection or a server
2922 * connection is desired. In both cases, (host, port) specify the
2923 * peer's (host, pair) pair. Client connections are not made
2924 * automatically by this routine. The parameter socket gives the
2925 * socket descriptor on which the packet was received. This is used,
2926 * in the case of server connections, to check that *new* connections
2927 * come via a valid (port, serviceId). Finally, the securityIndex
2928 * parameter must match the existing index for the connection. If a
2929 * server connection is created, it will be created using the supplied
2930 * index, if the index is valid for this service */
2931 struct rx_connection *
2932 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2933 u_short port, u_short serviceId, afs_uint32 cid,
2934 afs_uint32 epoch, int type, u_int securityIndex)
2936 int hashindex, flag, i;
2937 struct rx_connection *conn;
2938 hashindex = CONN_HASH(host, port, cid, epoch, type);
2939 MUTEX_ENTER(&rx_connHashTable_lock);
2940 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2941 rx_connHashTable[hashindex],
2944 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2945 && (epoch == conn->epoch)) {
2946 struct rx_peer *pp = conn->peer;
2947 if (securityIndex != conn->securityIndex) {
2948 /* this isn't supposed to happen, but someone could forge a packet
2949 * like this, and there seems to be some CM bug that makes this
2950 * happen from time to time -- in which case, the fileserver
2952 MUTEX_EXIT(&rx_connHashTable_lock);
2953 return (struct rx_connection *)0;
2955 if (pp->host == host && pp->port == port)
2957 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2959 /* So what happens when it's a callback connection? */
2960 if ( /*type == RX_CLIENT_CONNECTION && */
2961 (conn->epoch & 0x80000000))
2965 /* the connection rxLastConn that was used the last time is not the
2966 ** one we are looking for now. Hence, start searching in the hash */
2968 conn = rx_connHashTable[hashindex];
2973 struct rx_service *service;
2974 if (type == RX_CLIENT_CONNECTION) {
2975 MUTEX_EXIT(&rx_connHashTable_lock);
2976 return (struct rx_connection *)0;
2978 service = rxi_FindService(socket, serviceId);
2979 if (!service || (securityIndex >= service->nSecurityObjects)
2980 || (service->securityObjects[securityIndex] == 0)) {
2981 MUTEX_EXIT(&rx_connHashTable_lock);
2982 return (struct rx_connection *)0;
2984 conn = rxi_AllocConnection(); /* This bzero's the connection */
2985 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2986 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2987 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2988 conn->next = rx_connHashTable[hashindex];
2989 rx_connHashTable[hashindex] = conn;
2990 conn->peer = rxi_FindPeer(host, port, 0, 1);
2991 conn->type = RX_SERVER_CONNECTION;
2992 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2993 conn->epoch = epoch;
2994 conn->cid = cid & RX_CIDMASK;
2995 /* conn->serial = conn->lastSerial = 0; */
2996 /* conn->timeout = 0; */
2997 conn->ackRate = RX_FAST_ACK_RATE;
2998 conn->service = service;
2999 conn->serviceId = serviceId;
3000 conn->securityIndex = securityIndex;
3001 conn->securityObject = service->securityObjects[securityIndex];
3002 conn->nSpecific = 0;
3003 conn->specific = NULL;
3004 rx_SetConnDeadTime(conn, service->connDeadTime);
3005 conn->idleDeadTime = service->idleDeadTime;
3006 conn->idleDeadDetection = service->idleDeadErr ? 1 : 0;
3007 for (i = 0; i < RX_MAXCALLS; i++) {
3008 conn->twind[i] = rx_initSendWindow;
3009 conn->rwind[i] = rx_initReceiveWindow;
3011 /* Notify security object of the new connection */
3012 RXS_NewConnection(conn->securityObject, conn);
3013 /* XXXX Connection timeout? */
3014 if (service->newConnProc)
3015 (*service->newConnProc) (conn);
3016 if (rx_stats_active)
3017 rx_atomic_inc(&rx_stats.nServerConns);
3020 MUTEX_ENTER(&rx_refcnt_mutex);
3022 MUTEX_EXIT(&rx_refcnt_mutex);
3024 rxLastConn = conn; /* store this connection as the last conn used */
3025 MUTEX_EXIT(&rx_connHashTable_lock);
3030 * Timeout a call on a busy call channel if appropriate.
3032 * @param[in] call The busy call.
3034 * @pre 'call' is marked as busy (namely,
3035 * call->conn->lastBusy[call->channel] != 0)
3037 * @pre call->lock is held
3038 * @pre rxi_busyChannelError is nonzero
3040 * @note call->lock is dropped and reacquired
3043 rxi_CheckBusy(struct rx_call *call)
3045 struct rx_connection *conn = call->conn;
3046 int channel = call->channel;
3047 int freechannel = 0;
3049 afs_uint32 callNumber;
3051 MUTEX_EXIT(&call->lock);
3053 MUTEX_ENTER(&conn->conn_call_lock);
3054 callNumber = *call->callNumber;
3056 /* Are there any other call slots on this conn that we should try? Look for
3057 * slots that are empty and are either non-busy, or were marked as busy
3058 * longer than conn->secondsUntilDead seconds before this call started. */
3060 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
3062 /* only look at channels that aren't us */
3066 if (conn->lastBusy[i]) {
3067 /* if this channel looked busy too recently, don't look at it */
3068 if (conn->lastBusy[i] >= call->startTime.sec) {
3071 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
3076 if (conn->call[i]) {
3077 struct rx_call *tcall = conn->call[i];
3078 MUTEX_ENTER(&tcall->lock);
3079 if (tcall->state == RX_STATE_DALLY) {
3082 MUTEX_EXIT(&tcall->lock);
3088 MUTEX_ENTER(&call->lock);
3090 /* Since the call->lock and conn->conn_call_lock have been released it is
3091 * possible that (1) the call may no longer be busy and/or (2) the call may
3092 * have been reused by another waiting thread. Therefore, we must confirm
3093 * that the call state has not changed when deciding whether or not to
3094 * force this application thread to retry by forcing a Timeout error. */
3096 if (freechannel && *call->callNumber == callNumber &&
3097 (call->flags & RX_CALL_PEER_BUSY)) {
3098 /* Since 'freechannel' is set, there exists another channel in this
3099 * rx_conn that the application thread might be able to use. We know
3100 * that we have the correct call since callNumber is unchanged, and we
3101 * know that the call is still busy. So, set the call error state to
3102 * rxi_busyChannelError so the application can retry the request,
3103 * presumably on a less-busy call channel. */
3105 rxi_CallError(call, RX_CALL_BUSY);
3107 MUTEX_EXIT(&conn->conn_call_lock);
3110 /* There are two packet tracing routines available for testing and monitoring
3111 * Rx. One is called just after every packet is received and the other is
3112 * called just before every packet is sent. Received packets, have had their
3113 * headers decoded, and packets to be sent have not yet had their headers
3114 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3115 * containing the network address. Both can be modified. The return value, if
3116 * non-zero, indicates that the packet should be dropped. */
3118 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3119 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3121 /* A packet has been received off the interface. Np is the packet, socket is
3122 * the socket number it was received from (useful in determining which service
3123 * this packet corresponds to), and (host, port) reflect the host,port of the
3124 * sender. This call returns the packet to the caller if it is finished with
3125 * it, rather than de-allocating it, just as a small performance hack */
3128 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3129 afs_uint32 host, u_short port, int *tnop,
3130 struct rx_call **newcallp)
3132 struct rx_call *call;
3133 struct rx_connection *conn;
3135 afs_uint32 currentCallNumber;
3141 struct rx_packet *tnp;
3144 /* We don't print out the packet until now because (1) the time may not be
3145 * accurate enough until now in the lwp implementation (rx_Listener only gets
3146 * the time after the packet is read) and (2) from a protocol point of view,
3147 * this is the first time the packet has been seen */
3148 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3149 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3150 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3151 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3152 np->header.epoch, np->header.cid, np->header.callNumber,
3153 np->header.seq, np->header.flags, np));
3156 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3157 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3160 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3161 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3164 /* If an input tracer function is defined, call it with the packet and
3165 * network address. Note this function may modify its arguments. */
3166 if (rx_justReceived) {
3167 struct sockaddr_in addr;
3169 addr.sin_family = AF_INET;
3170 addr.sin_port = port;
3171 addr.sin_addr.s_addr = host;
3172 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3173 addr.sin_len = sizeof(addr);
3174 #endif /* AFS_OSF_ENV */
3175 drop = (*rx_justReceived) (np, &addr);
3176 /* drop packet if return value is non-zero */
3179 port = addr.sin_port; /* in case fcn changed addr */
3180 host = addr.sin_addr.s_addr;
3184 /* If packet was not sent by the client, then *we* must be the client */
3185 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3186 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3188 /* Find the connection (or fabricate one, if we're the server & if
3189 * necessary) associated with this packet */
3191 rxi_FindConnection(socket, host, port, np->header.serviceId,
3192 np->header.cid, np->header.epoch, type,
3193 np->header.securityIndex);
3196 /* If no connection found or fabricated, just ignore the packet.
3197 * (An argument could be made for sending an abort packet for
3202 /* If the connection is in an error state, send an abort packet and ignore
3203 * the incoming packet */
3205 /* Don't respond to an abort packet--we don't want loops! */
3206 MUTEX_ENTER(&conn->conn_data_lock);
3207 if (np->header.type != RX_PACKET_TYPE_ABORT)
3208 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3209 putConnection(conn);
3210 MUTEX_EXIT(&conn->conn_data_lock);
3214 /* Check for connection-only requests (i.e. not call specific). */
3215 if (np->header.callNumber == 0) {
3216 switch (np->header.type) {
3217 case RX_PACKET_TYPE_ABORT: {
3218 /* What if the supplied error is zero? */
3219 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3220 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3221 rxi_ConnectionError(conn, errcode);
3222 putConnection(conn);
3225 case RX_PACKET_TYPE_CHALLENGE:
3226 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3227 putConnection(conn);
3229 case RX_PACKET_TYPE_RESPONSE:
3230 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3231 putConnection(conn);
3233 case RX_PACKET_TYPE_PARAMS:
3234 case RX_PACKET_TYPE_PARAMS + 1:
3235 case RX_PACKET_TYPE_PARAMS + 2:
3236 /* ignore these packet types for now */
3237 putConnection(conn);
3241 /* Should not reach here, unless the peer is broken: send an
3243 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3244 MUTEX_ENTER(&conn->conn_data_lock);
3245 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3246 putConnection(conn);
3247 MUTEX_EXIT(&conn->conn_data_lock);
3252 channel = np->header.cid & RX_CHANNELMASK;
3253 MUTEX_ENTER(&conn->conn_call_lock);
3254 call = conn->call[channel];
3257 MUTEX_ENTER(&call->lock);
3258 currentCallNumber = conn->callNumber[channel];
3259 MUTEX_EXIT(&conn->conn_call_lock);
3260 } else if (type == RX_SERVER_CONNECTION) { /* No call allocated */
3261 call = conn->call[channel];
3263 MUTEX_ENTER(&call->lock);
3264 currentCallNumber = conn->callNumber[channel];
3265 MUTEX_EXIT(&conn->conn_call_lock);
3267 call = rxi_NewCall(conn, channel); /* returns locked call */
3268 *call->callNumber = currentCallNumber = np->header.callNumber;
3269 MUTEX_EXIT(&conn->conn_call_lock);
3271 if (np->header.callNumber == 0)
3272 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3273 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3274 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3275 np->header.flags, np, np->length));
3277 call->state = RX_STATE_PRECALL;
3278 clock_GetTime(&call->queueTime);
3279 hzero(call->bytesSent);
3280 hzero(call->bytesRcvd);
3282 * If the number of queued calls exceeds the overload
3283 * threshold then abort this call.
3285 if ((rx_BusyThreshold > 0) &&
3286 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3287 struct rx_packet *tp;
3289 rxi_CallError(call, rx_BusyError);
3290 tp = rxi_SendCallAbort(call, np, 1, 0);
3291 MUTEX_EXIT(&call->lock);
3292 putConnection(conn);
3293 if (rx_stats_active)
3294 rx_atomic_inc(&rx_stats.nBusies);
3297 rxi_KeepAliveOn(call);
3299 } else { /* RX_CLIENT_CONNECTION and No call allocated */
3300 /* This packet can't be for this call. If the new call address is
3301 * 0 then no call is running on this channel. If there is a call
3302 * then, since this is a client connection we're getting data for
3303 * it must be for the previous call.
3305 if (rx_stats_active)
3306 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3307 putConnection(conn);
3311 /* There is a non-NULL locked call at this point */
3312 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3313 if (np->header.callNumber < currentCallNumber) {
3314 MUTEX_EXIT(&call->lock);
3315 if (rx_stats_active)
3316 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3317 putConnection(conn);
3319 } else if (np->header.callNumber != currentCallNumber) {
3320 /* Wait until the transmit queue is idle before deciding
3321 * whether to reset the current call. Chances are that the
3322 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3325 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3326 if (call->state == RX_STATE_ACTIVE) {
3327 rxi_WaitforTQBusy(call);
3329 * If we entered error state while waiting,
3330 * must call rxi_CallError to permit rxi_ResetCall
3331 * to processed when the tqWaiter count hits zero.
3334 rxi_CallError(call, call->error);
3335 MUTEX_EXIT(&call->lock);
3336 putConnection(conn);
3340 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3341 /* If the new call cannot be taken right now send a busy and set
3342 * the error condition in this call, so that it terminates as
3343 * quickly as possible */
3344 if (call->state == RX_STATE_ACTIVE) {
3345 struct rx_packet *tp;
3347 rxi_CallError(call, RX_CALL_DEAD);
3348 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3350 MUTEX_EXIT(&call->lock);
3351 putConnection(conn);
3354 rxi_ResetCall(call, 0);
3356 * The conn_call_lock is not held but no one else should be
3357 * using this call channel while we are processing this incoming
3358 * packet. This assignment should be safe.
3360 *call->callNumber = np->header.callNumber;
3362 if (np->header.callNumber == 0)
3363 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3364 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3365 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3366 np->header.flags, np, np->length));
3368 call->state = RX_STATE_PRECALL;
3369 clock_GetTime(&call->queueTime);
3370 hzero(call->bytesSent);
3371 hzero(call->bytesRcvd);
3373 * If the number of queued calls exceeds the overload
3374 * threshold then abort this call.
3376 if ((rx_BusyThreshold > 0) &&
3377 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3378 struct rx_packet *tp;
3380 rxi_CallError(call, rx_BusyError);
3381 tp = rxi_SendCallAbort(call, np, 1, 0);
3382 MUTEX_EXIT(&call->lock);
3383 putConnection(conn);
3384 if (rx_stats_active)
3385 rx_atomic_inc(&rx_stats.nBusies);
3388 rxi_KeepAliveOn(call);
3390 /* Continuing call; do nothing here. */
3392 } else { /* we're the client */
3393 /* Ignore all incoming acknowledgements for calls in DALLY state */
3394 if ((call->state == RX_STATE_DALLY)
3395 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3396 if (rx_stats_active)
3397 rx_atomic_inc(&rx_stats.ignorePacketDally);
3398 MUTEX_EXIT(&call->lock);
3399 putConnection(conn);
3403 /* Ignore anything that's not relevant to the current call. If there
3404 * isn't a current call, then no packet is relevant. */
3405 if (np->header.callNumber != currentCallNumber) {
3406 if (rx_stats_active)
3407 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3408 MUTEX_EXIT(&call->lock);
3409 putConnection(conn);
3412 /* If the service security object index stamped in the packet does not
3413 * match the connection's security index, ignore the packet */
3414 if (np->header.securityIndex != conn->securityIndex) {
3415 MUTEX_EXIT(&call->lock);
3416 putConnection(conn);
3420 /* If we're receiving the response, then all transmit packets are
3421 * implicitly acknowledged. Get rid of them. */
3422 if (np->header.type == RX_PACKET_TYPE_DATA) {
3423 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3424 /* XXX Hack. Because we must release the global rx lock when
3425 * sending packets (osi_NetSend) we drop all acks while we're
3426 * traversing the tq in rxi_Start sending packets out because
3427 * packets may move to the freePacketQueue as result of being here!
3428 * So we drop these packets until we're safely out of the
3429 * traversing. Really ugly!
3430 * For fine grain RX locking, we set the acked field in the
3431 * packets and let rxi_Start remove them from the transmit queue.
3433 if (call->flags & RX_CALL_TQ_BUSY) {
3434 #ifdef RX_ENABLE_LOCKS
3435 rxi_SetAcksInTransmitQueue(call);
3437 putConnection(conn);
3438 return np; /* xmitting; drop packet */
3441 rxi_ClearTransmitQueue(call, 0);
3443 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3444 rxi_ClearTransmitQueue(call, 0);
3445 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3447 if (np->header.type == RX_PACKET_TYPE_ACK) {
3448 /* now check to see if this is an ack packet acknowledging that the
3449 * server actually *lost* some hard-acked data. If this happens we
3450 * ignore this packet, as it may indicate that the server restarted in
3451 * the middle of a call. It is also possible that this is an old ack
3452 * packet. We don't abort the connection in this case, because this
3453 * *might* just be an old ack packet. The right way to detect a server
3454 * restart in the midst of a call is to notice that the server epoch
3456 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3457 * XXX unacknowledged. I think that this is off-by-one, but
3458 * XXX I don't dare change it just yet, since it will
3459 * XXX interact badly with the server-restart detection
3460 * XXX code in receiveackpacket. */
3461 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3462 if (rx_stats_active)
3463 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3464 MUTEX_EXIT(&call->lock);
3465 putConnection(conn);
3469 } /* else not a data packet */
3472 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3473 /* Set remote user defined status from packet */
3474 call->remoteStatus = np->header.userStatus;
3476 /* Note the gap between the expected next packet and the actual
3477 * packet that arrived, when the new packet has a smaller serial number
3478 * than expected. Rioses frequently reorder packets all by themselves,
3479 * so this will be quite important with very large window sizes.
3480 * Skew is checked against 0 here to avoid any dependence on the type of
3481 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3483 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3484 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3485 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3487 MUTEX_ENTER(&conn->conn_data_lock);
3488 skew = conn->lastSerial - np->header.serial;
3489 conn->lastSerial = np->header.serial;
3490 MUTEX_EXIT(&conn->conn_data_lock);
3492 struct rx_peer *peer;
3494 if (skew > peer->inPacketSkew) {
3495 dpf(("*** In skew changed from %d to %d\n",
3496 peer->inPacketSkew, skew));
3497 peer->inPacketSkew = skew;
3501 /* Now do packet type-specific processing */
3502 switch (np->header.type) {
3503 case RX_PACKET_TYPE_DATA:
3504 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3507 case RX_PACKET_TYPE_ACK:
3508 /* Respond immediately to ack packets requesting acknowledgement
3510 if (np->header.flags & RX_REQUEST_ACK) {
3512 (void)rxi_SendCallAbort(call, 0, 1, 0);
3514 (void)rxi_SendAck(call, 0, np->header.serial,
3515 RX_ACK_PING_RESPONSE, 1);
3517 np = rxi_ReceiveAckPacket(call, np, 1);
3519 case RX_PACKET_TYPE_ABORT: {
3520 /* An abort packet: reset the call, passing the error up to the user. */
3521 /* What if error is zero? */
3522 /* What if the error is -1? the application will treat it as a timeout. */
3523 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3524 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3525 rxi_CallError(call, errdata);
3526 MUTEX_EXIT(&call->lock);
3527 putConnection(conn);
3528 return np; /* xmitting; drop packet */
3530 case RX_PACKET_TYPE_BUSY: {
3531 struct clock busyTime;
3533 clock_GetTime(&busyTime);
3535 MUTEX_EXIT(&call->lock);
3537 MUTEX_ENTER(&conn->conn_call_lock);
3538 MUTEX_ENTER(&call->lock);
3539 conn->lastBusy[call->channel] = busyTime.sec;
3540 call->flags |= RX_CALL_PEER_BUSY;
3541 MUTEX_EXIT(&call->lock);
3542 MUTEX_EXIT(&conn->conn_call_lock);
3544 putConnection(conn);
3548 case RX_PACKET_TYPE_ACKALL:
3549 /* All packets acknowledged, so we can drop all packets previously
3550 * readied for sending */
3551 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3552 /* XXX Hack. We because we can't release the global rx lock when
3553 * sending packets (osi_NetSend) we drop all ack pkts while we're
3554 * traversing the tq in rxi_Start sending packets out because
3555 * packets may move to the freePacketQueue as result of being
3556 * here! So we drop these packets until we're safely out of the
3557 * traversing. Really ugly!
3558 * For fine grain RX locking, we set the acked field in the packets
3559 * and let rxi_Start remove the packets from the transmit queue.
3561 if (call->flags & RX_CALL_TQ_BUSY) {
3562 #ifdef RX_ENABLE_LOCKS
3563 rxi_SetAcksInTransmitQueue(call);
3565 #else /* RX_ENABLE_LOCKS */
3566 MUTEX_EXIT(&call->lock);
3567 putConnection(conn);
3568 return np; /* xmitting; drop packet */
3569 #endif /* RX_ENABLE_LOCKS */
3571 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3572 rxi_ClearTransmitQueue(call, 0);
3575 /* Should not reach here, unless the peer is broken: send an abort
3577 rxi_CallError(call, RX_PROTOCOL_ERROR);
3578 np = rxi_SendCallAbort(call, np, 1, 0);
3581 /* Note when this last legitimate packet was received, for keep-alive
3582 * processing. Note, we delay getting the time until now in the hope that
3583 * the packet will be delivered to the user before any get time is required
3584 * (if not, then the time won't actually be re-evaluated here). */
3585 call->lastReceiveTime = clock_Sec();
3586 /* we've received a legit packet, so the channel is not busy */
3587 call->flags &= ~RX_CALL_PEER_BUSY;
3588 MUTEX_EXIT(&call->lock);
3589 putConnection(conn);
3593 /* return true if this is an "interesting" connection from the point of view
3594 of someone trying to debug the system */
3596 rxi_IsConnInteresting(struct rx_connection *aconn)
3599 struct rx_call *tcall;
3601 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3604 for (i = 0; i < RX_MAXCALLS; i++) {
3605 tcall = aconn->call[i];
3607 if ((tcall->state == RX_STATE_PRECALL)
3608 || (tcall->state == RX_STATE_ACTIVE))
3610 if ((tcall->mode == RX_MODE_SENDING)
3611 || (tcall->mode == RX_MODE_RECEIVING))
3619 /* if this is one of the last few packets AND it wouldn't be used by the
3620 receiving call to immediately satisfy a read request, then drop it on
3621 the floor, since accepting it might prevent a lock-holding thread from
3622 making progress in its reading. If a call has been cleared while in
3623 the precall state then ignore all subsequent packets until the call
3624 is assigned to a thread. */
3627 TooLow(struct rx_packet *ap, struct rx_call *acall)
3631 MUTEX_ENTER(&rx_quota_mutex);
3632 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3633 && (acall->state == RX_STATE_PRECALL))
3634 || ((rx_nFreePackets < rxi_dataQuota + 2)
3635 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3636 && (acall->flags & RX_CALL_READER_WAIT)))) {
3639 MUTEX_EXIT(&rx_quota_mutex);
3645 * Clear the attach wait flag on a connection and proceed.
3647 * Any processing waiting for a connection to be attached should be
3648 * unblocked. We clear the flag and do any other needed tasks.
3651 * the conn to unmark waiting for attach
3653 * @pre conn's conn_data_lock must be locked before calling this function
3657 rxi_ConnClearAttachWait(struct rx_connection *conn)
3659 /* Indicate that rxi_CheckReachEvent is no longer running by
3660 * clearing the flag. Must be atomic under conn_data_lock to
3661 * avoid a new call slipping by: rxi_CheckConnReach holds
3662 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3664 conn->flags &= ~RX_CONN_ATTACHWAIT;
3665 if (conn->flags & RX_CONN_NAT_PING) {
3666 conn->flags &= ~RX_CONN_NAT_PING;
3667 rxi_ScheduleNatKeepAliveEvent(conn);
3672 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3674 struct rx_connection *conn = arg1;
3675 struct rx_call *acall = arg2;
3676 struct rx_call *call = acall;
3677 struct clock when, now;
3680 MUTEX_ENTER(&conn->conn_data_lock);
3683 rxevent_Put(conn->checkReachEvent);
3684 conn->checkReachEvent = NULL;
3687 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3689 putConnection(conn);
3691 MUTEX_EXIT(&conn->conn_data_lock);
3695 MUTEX_ENTER(&conn->conn_call_lock);
3696 MUTEX_ENTER(&conn->conn_data_lock);
3697 for (i = 0; i < RX_MAXCALLS; i++) {
3698 struct rx_call *tc = conn->call[i];
3699 if (tc && tc->state == RX_STATE_PRECALL) {
3705 rxi_ConnClearAttachWait(conn);
3706 MUTEX_EXIT(&conn->conn_data_lock);
3707 MUTEX_EXIT(&conn->conn_call_lock);
3712 MUTEX_ENTER(&call->lock);
3713 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3715 MUTEX_EXIT(&call->lock);
3717 clock_GetTime(&now);
3719 when.sec += RX_CHECKREACH_TIMEOUT;
3720 MUTEX_ENTER(&conn->conn_data_lock);
3721 if (!conn->checkReachEvent) {
3722 MUTEX_ENTER(&rx_refcnt_mutex);
3724 MUTEX_EXIT(&rx_refcnt_mutex);
3725 conn->checkReachEvent = rxevent_Post(&when, &now,
3726 rxi_CheckReachEvent, conn,
3729 MUTEX_EXIT(&conn->conn_data_lock);
3735 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3737 struct rx_service *service = conn->service;
3738 struct rx_peer *peer = conn->peer;
3739 afs_uint32 now, lastReach;
3741 if (service->checkReach == 0)
3745 MUTEX_ENTER(&peer->peer_lock);
3746 lastReach = peer->lastReachTime;
3747 MUTEX_EXIT(&peer->peer_lock);
3748 if (now - lastReach < RX_CHECKREACH_TTL)
3751 MUTEX_ENTER(&conn->conn_data_lock);
3752 if (conn->flags & RX_CONN_ATTACHWAIT) {
3753 MUTEX_EXIT(&conn->conn_data_lock);
3756 conn->flags |= RX_CONN_ATTACHWAIT;
3757 MUTEX_EXIT(&conn->conn_data_lock);
3758 if (!conn->checkReachEvent)
3759 rxi_CheckReachEvent(NULL, conn, call, 0);
3764 /* try to attach call, if authentication is complete */
3766 TryAttach(struct rx_call *acall, osi_socket socket,
3767 int *tnop, struct rx_call **newcallp,
3770 struct rx_connection *conn = acall->conn;
3772 if (conn->type == RX_SERVER_CONNECTION
3773 && acall->state == RX_STATE_PRECALL) {
3774 /* Don't attach until we have any req'd. authentication. */
3775 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3776 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3777 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3778 /* Note: this does not necessarily succeed; there
3779 * may not any proc available
3782 rxi_ChallengeOn(acall->conn);
3787 /* A data packet has been received off the interface. This packet is
3788 * appropriate to the call (the call is in the right state, etc.). This
3789 * routine can return a packet to the caller, for re-use */
3792 rxi_ReceiveDataPacket(struct rx_call *call,
3793 struct rx_packet *np, int istack,
3794 osi_socket socket, afs_uint32 host, u_short port,
3795 int *tnop, struct rx_call **newcallp)
3797 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3802 afs_uint32 serial=0, flags=0;
3804 struct rx_packet *tnp;
3805 if (rx_stats_active)
3806 rx_atomic_inc(&rx_stats.dataPacketsRead);
3809 /* If there are no packet buffers, drop this new packet, unless we can find
3810 * packet buffers from inactive calls */
3812 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3813 MUTEX_ENTER(&rx_freePktQ_lock);
3814 rxi_NeedMorePackets = TRUE;
3815 MUTEX_EXIT(&rx_freePktQ_lock);
3816 if (rx_stats_active)
3817 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3818 call->rprev = np->header.serial;
3819 rxi_calltrace(RX_TRACE_DROP, call);
3820 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3821 /* We used to clear the receive queue here, in an attempt to free
3822 * packets. However this is unsafe if the queue has received a
3823 * soft ACK for the final packet */
3824 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3826 /* we've damaged this call already, might as well do it in. */
3832 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3833 * packet is one of several packets transmitted as a single
3834 * datagram. Do not send any soft or hard acks until all packets
3835 * in a jumbogram have been processed. Send negative acks right away.
3837 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3838 /* tnp is non-null when there are more packets in the
3839 * current jumbo gram */
3846 seq = np->header.seq;
3847 serial = np->header.serial;
3848 flags = np->header.flags;
3850 /* If the call is in an error state, send an abort message */
3852 return rxi_SendCallAbort(call, np, istack, 0);
3854 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3855 * AFS 3.5 jumbogram. */
3856 if (flags & RX_JUMBO_PACKET) {
3857 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3862 if (np->header.spare != 0) {
3863 MUTEX_ENTER(&call->conn->conn_data_lock);
3864 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3865 MUTEX_EXIT(&call->conn->conn_data_lock);
3868 /* The usual case is that this is the expected next packet */
3869 if (seq == call->rnext) {
3871 /* Check to make sure it is not a duplicate of one already queued */
3872 if (queue_IsNotEmpty(&call->rq)
3873 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3874 if (rx_stats_active)
3875 rx_atomic_inc(&rx_stats.dupPacketsRead);
3876 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3877 rxevent_Cancel(&call->delayedAckEvent, call,
3878 RX_CALL_REFCOUNT_DELAY);
3879 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3885 /* It's the next packet. Stick it on the receive queue
3886 * for this call. Set newPackets to make sure we wake
3887 * the reader once all packets have been processed */
3888 #ifdef RX_TRACK_PACKETS
3889 np->flags |= RX_PKTFLAG_RQ;
3891 queue_Prepend(&call->rq, np);
3892 #ifdef RXDEBUG_PACKET
3894 #endif /* RXDEBUG_PACKET */
3896 np = NULL; /* We can't use this anymore */
3899 /* If an ack is requested then set a flag to make sure we
3900 * send an acknowledgement for this packet */
3901 if (flags & RX_REQUEST_ACK) {
3902 ackNeeded = RX_ACK_REQUESTED;
3905 /* Keep track of whether we have received the last packet */
3906 if (flags & RX_LAST_PACKET) {
3907 call->flags |= RX_CALL_HAVE_LAST;
3911 /* Check whether we have all of the packets for this call */
3912 if (call->flags & RX_CALL_HAVE_LAST) {
3913 afs_uint32 tseq; /* temporary sequence number */
3914 struct rx_packet *tp; /* Temporary packet pointer */
3915 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3917 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3918 if (tseq != tp->header.seq)
3920 if (tp->header.flags & RX_LAST_PACKET) {
3921 call->flags |= RX_CALL_RECEIVE_DONE;
3928 /* Provide asynchronous notification for those who want it
3929 * (e.g. multi rx) */
3930 if (call->arrivalProc) {
3931 (*call->arrivalProc) (call, call->arrivalProcHandle,
3932 call->arrivalProcArg);
3933 call->arrivalProc = (void (*)())0;
3936 /* Update last packet received */
3939 /* If there is no server process serving this call, grab
3940 * one, if available. We only need to do this once. If a
3941 * server thread is available, this thread becomes a server
3942 * thread and the server thread becomes a listener thread. */
3944 TryAttach(call, socket, tnop, newcallp, 0);
3947 /* This is not the expected next packet. */
3949 /* Determine whether this is a new or old packet, and if it's
3950 * a new one, whether it fits into the current receive window.
3951 * Also figure out whether the packet was delivered in sequence.
3952 * We use the prev variable to determine whether the new packet
3953 * is the successor of its immediate predecessor in the
3954 * receive queue, and the missing flag to determine whether
3955 * any of this packets predecessors are missing. */
3957 afs_uint32 prev; /* "Previous packet" sequence number */
3958 struct rx_packet *tp; /* Temporary packet pointer */
3959 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3960 int missing; /* Are any predecessors missing? */
3962 /* If the new packet's sequence number has been sent to the
3963 * application already, then this is a duplicate */
3964 if (seq < call->rnext) {
3965 if (rx_stats_active)
3966 rx_atomic_inc(&rx_stats.dupPacketsRead);
3967 rxevent_Cancel(&call->delayedAckEvent, call,
3968 RX_CALL_REFCOUNT_DELAY);
3969 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3975 /* If the sequence number is greater than what can be
3976 * accomodated by the current window, then send a negative
3977 * acknowledge and drop the packet */
3978 if ((call->rnext + call->rwind) <= seq) {
3979 rxevent_Cancel(&call->delayedAckEvent, call,
3980 RX_CALL_REFCOUNT_DELAY);
3981 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3988 /* Look for the packet in the queue of old received packets */
3989 for (prev = call->rnext - 1, missing =
3990 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3991 /*Check for duplicate packet */
3992 if (seq == tp->header.seq) {
3993 if (rx_stats_active)
3994 rx_atomic_inc(&rx_stats.dupPacketsRead);
3995 rxevent_Cancel(&call->delayedAckEvent, call,
3996 RX_CALL_REFCOUNT_DELAY);
3997 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4003 /* If we find a higher sequence packet, break out and
4004 * insert the new packet here. */
4005 if (seq < tp->header.seq)
4007 /* Check for missing packet */
4008 if (tp->header.seq != prev + 1) {
4012 prev = tp->header.seq;
4015 /* Keep track of whether we have received the last packet. */
4016 if (flags & RX_LAST_PACKET) {
4017 call->flags |= RX_CALL_HAVE_LAST;
4020 /* It's within the window: add it to the the receive queue.
4021 * tp is left by the previous loop either pointing at the
4022 * packet before which to insert the new packet, or at the
4023 * queue head if the queue is empty or the packet should be
4025 #ifdef RX_TRACK_PACKETS
4026 np->flags |= RX_PKTFLAG_RQ;
4028 #ifdef RXDEBUG_PACKET
4030 #endif /* RXDEBUG_PACKET */
4031 queue_InsertBefore(tp, np);
4035 /* Check whether we have all of the packets for this call */
4036 if ((call->flags & RX_CALL_HAVE_LAST)
4037 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4038 afs_uint32 tseq; /* temporary sequence number */
4041 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4042 if (tseq != tp->header.seq)
4044 if (tp->header.flags & RX_LAST_PACKET) {
4045 call->flags |= RX_CALL_RECEIVE_DONE;
4052 /* We need to send an ack of the packet is out of sequence,
4053 * or if an ack was requested by the peer. */
4054 if (seq != prev + 1 || missing) {
4055 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4056 } else if (flags & RX_REQUEST_ACK) {
4057 ackNeeded = RX_ACK_REQUESTED;
4060 /* Acknowledge the last packet for each call */
4061 if (flags & RX_LAST_PACKET) {
4072 * If the receiver is waiting for an iovec, fill the iovec
4073 * using the data from the receive queue */
4074 if (call->flags & RX_CALL_IOVEC_WAIT) {
4075 didHardAck = rxi_FillReadVec(call, serial);
4076 /* the call may have been aborted */
4085 /* Wakeup the reader if any */
4086 if ((call->flags & RX_CALL_READER_WAIT)
4087 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4088 || (call->iovNext >= call->iovMax)
4089 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4090 call->flags &= ~RX_CALL_READER_WAIT;
4091 #ifdef RX_ENABLE_LOCKS
4092 CV_BROADCAST(&call->cv_rq);
4094 osi_rxWakeup(&call->rq);
4100 * Send an ack when requested by the peer, or once every
4101 * rxi_SoftAckRate packets until the last packet has been
4102 * received. Always send a soft ack for the last packet in
4103 * the server's reply. */
4105 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4106 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4107 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4108 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4109 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4110 } else if (call->nSoftAcks) {
4111 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4112 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4114 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4115 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4116 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4123 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4125 struct rx_peer *peer = conn->peer;
4127 MUTEX_ENTER(&peer->peer_lock);
4128 peer->lastReachTime = clock_Sec();
4129 MUTEX_EXIT(&peer->peer_lock);
4131 MUTEX_ENTER(&conn->conn_data_lock);
4132 if (conn->flags & RX_CONN_ATTACHWAIT) {
4135 rxi_ConnClearAttachWait(conn);
4136 MUTEX_EXIT(&conn->conn_data_lock);
4138 for (i = 0; i < RX_MAXCALLS; i++) {
4139 struct rx_call *call = conn->call[i];
4142 MUTEX_ENTER(&call->lock);
4143 /* tnop can be null if newcallp is null */
4144 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4146 MUTEX_EXIT(&call->lock);
4150 MUTEX_EXIT(&conn->conn_data_lock);
4153 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4155 rx_ack_reason(int reason)
4158 case RX_ACK_REQUESTED:
4160 case RX_ACK_DUPLICATE:
4162 case RX_ACK_OUT_OF_SEQUENCE:
4164 case RX_ACK_EXCEEDS_WINDOW:
4166 case RX_ACK_NOSPACE:
4170 case RX_ACK_PING_RESPONSE:
4183 /* The real smarts of the whole thing. */
4185 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4188 struct rx_ackPacket *ap;
4190 struct rx_packet *tp;
4191 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4192 struct rx_connection *conn = call->conn;
4193 struct rx_peer *peer = conn->peer;
4194 struct clock now; /* Current time, for RTT calculations */
4198 /* because there are CM's that are bogus, sending weird values for this. */
4199 afs_uint32 skew = 0;
4204 int newAckCount = 0;
4205 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4206 int pktsize = 0; /* Set if we need to update the peer mtu */
4207 int conn_data_locked = 0;
4209 if (rx_stats_active)
4210 rx_atomic_inc(&rx_stats.ackPacketsRead);
4211 ap = (struct rx_ackPacket *)rx_DataOf(np);
4212 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4214 return np; /* truncated ack packet */
4216 /* depends on ack packet struct */
4217 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4218 first = ntohl(ap->firstPacket);
4219 prev = ntohl(ap->previousPacket);
4220 serial = ntohl(ap->serial);
4221 /* temporarily disabled -- needs to degrade over time
4222 * skew = ntohs(ap->maxSkew); */
4224 /* Ignore ack packets received out of order */
4225 if (first < call->tfirst ||
4226 (first == call->tfirst && prev < call->tprev)) {
4232 if (np->header.flags & RX_SLOW_START_OK) {
4233 call->flags |= RX_CALL_SLOW_START_OK;
4236 if (ap->reason == RX_ACK_PING_RESPONSE)
4237 rxi_UpdatePeerReach(conn, call);
4239 if (conn->lastPacketSizeSeq) {
4240 MUTEX_ENTER(&conn->conn_data_lock);
4241 conn_data_locked = 1;
4242 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4243 pktsize = conn->lastPacketSize;
4244 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4247 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4248 if (!conn_data_locked) {
4249 MUTEX_ENTER(&conn->conn_data_lock);
4250 conn_data_locked = 1;
4252 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4253 /* process mtu ping ack */
4254 pktsize = conn->lastPingSize;
4255 conn->lastPingSizeSer = conn->lastPingSize = 0;
4259 if (conn_data_locked) {
4260 MUTEX_EXIT(&conn->conn_data_lock);
4261 conn_data_locked = 0;
4265 if (rxdebug_active) {
4269 len = _snprintf(msg, sizeof(msg),
4270 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4271 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4272 ntohl(ap->serial), ntohl(ap->previousPacket),
4273 (unsigned int)np->header.seq, (unsigned int)skew,
4274 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4278 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4279 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4283 OutputDebugString(msg);
4285 #else /* AFS_NT40_ENV */
4288 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4289 ap->reason, ntohl(ap->previousPacket),
4290 (unsigned int)np->header.seq, (unsigned int)serial,
4291 (unsigned int)skew, ntohl(ap->firstPacket));
4294 for (offset = 0; offset < nAcks; offset++)
4295 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4300 #endif /* AFS_NT40_ENV */
4303 MUTEX_ENTER(&peer->peer_lock);
4306 * Start somewhere. Can't assume we can send what we can receive,
4307 * but we are clearly receiving.
4309 if (!peer->maxPacketSize)
4310 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4312 if (pktsize > peer->maxPacketSize) {
4313 peer->maxPacketSize = pktsize;
4314 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4315 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4316 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4317 rxi_ScheduleGrowMTUEvent(call, 1);
4322 /* Update the outgoing packet skew value to the latest value of
4323 * the peer's incoming packet skew value. The ack packet, of
4324 * course, could arrive out of order, but that won't affect things
4326 peer->outPacketSkew = skew;
4329 clock_GetTime(&now);
4331 /* The transmit queue splits into 4 sections.
4333 * The first section is packets which have now been acknowledged
4334 * by a window size change in the ack. These have reached the
4335 * application layer, and may be discarded. These are packets
4336 * with sequence numbers < ap->firstPacket.
4338 * The second section is packets which have sequence numbers in
4339 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4340 * contents of the packet's ack array determines whether these
4341 * packets are acknowledged or not.
4343 * The third section is packets which fall above the range
4344 * addressed in the ack packet. These have not yet been received
4347 * The four section is packets which have not yet been transmitted.
4348 * These packets will have a header.serial of 0.
4351 /* First section - implicitly acknowledged packets that can be
4355 tp = queue_First(&call->tq, rx_packet);
4356 while(!queue_IsEnd(&call->tq, tp) && tp->header.seq < first) {
4357 struct rx_packet *next;
4359 next = queue_Next(tp, rx_packet);
4360 call->tfirst = tp->header.seq + 1;
4362 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4364 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4367 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4368 /* XXX Hack. Because we have to release the global rx lock when sending
4369 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4370 * in rxi_Start sending packets out because packets may move to the
4371 * freePacketQueue as result of being here! So we drop these packets until
4372 * we're safely out of the traversing. Really ugly!
4373 * To make it even uglier, if we're using fine grain locking, we can
4374 * set the ack bits in the packets and have rxi_Start remove the packets
4375 * when it's done transmitting.
4377 if (call->flags & RX_CALL_TQ_BUSY) {
4378 #ifdef RX_ENABLE_LOCKS
4379 tp->flags |= RX_PKTFLAG_ACKED;
4380 call->flags |= RX_CALL_TQ_SOME_ACKED;
4381 #else /* RX_ENABLE_LOCKS */
4383 #endif /* RX_ENABLE_LOCKS */
4385 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4388 #ifdef RX_TRACK_PACKETS
4389 tp->flags &= ~RX_PKTFLAG_TQ;
4391 #ifdef RXDEBUG_PACKET
4393 #endif /* RXDEBUG_PACKET */
4394 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4399 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4401 /* Second section of the queue - packets for which we are receiving
4404 * Go through the explicit acks/nacks and record the results in
4405 * the waiting packets. These are packets that can't be released
4406 * yet, even with a positive acknowledge. This positive
4407 * acknowledge only means the packet has been received by the
4408 * peer, not that it will be retained long enough to be sent to
4409 * the peer's upper level. In addition, reset the transmit timers
4410 * of any missing packets (those packets that must be missing
4411 * because this packet was out of sequence) */
4413 call->nSoftAcked = 0;
4415 while (!queue_IsEnd(&call->tq, tp) && tp->header.seq < first + nAcks) {
4416 /* Set the acknowledge flag per packet based on the
4417 * information in the ack packet. An acknowlegded packet can
4418 * be downgraded when the server has discarded a packet it
4419 * soacked previously, or when an ack packet is received
4420 * out of sequence. */
4421 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4422 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4424 tp->flags |= RX_PKTFLAG_ACKED;
4425 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4432 } else /* RX_ACK_TYPE_NACK */ {
4433 tp->flags &= ~RX_PKTFLAG_ACKED;
4437 tp = queue_Next(tp, rx_packet);
4440 /* We don't need to take any action with the 3rd or 4th section in the
4441 * queue - they're not addressed by the contents of this ACK packet.
4444 /* If the window has been extended by this acknowledge packet,
4445 * then wakeup a sender waiting in alloc for window space, or try
4446 * sending packets now, if he's been sitting on packets due to
4447 * lack of window space */
4448 if (call->tnext < (call->tfirst + call->twind)) {
4449 #ifdef RX_ENABLE_LOCKS
4450 CV_SIGNAL(&call->cv_twind);
4452 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4453 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4454 osi_rxWakeup(&call->twind);
4457 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4458 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4462 /* if the ack packet has a receivelen field hanging off it,
4463 * update our state */
4464 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4467 /* If the ack packet has a "recommended" size that is less than
4468 * what I am using now, reduce my size to match */
4469 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4470 (int)sizeof(afs_int32), &tSize);
4471 tSize = (afs_uint32) ntohl(tSize);
4472 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4474 /* Get the maximum packet size to send to this peer */
4475 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4477 tSize = (afs_uint32) ntohl(tSize);
4478 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4479 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4481 /* sanity check - peer might have restarted with different params.
4482 * If peer says "send less", dammit, send less... Peer should never
4483 * be unable to accept packets of the size that prior AFS versions would
4484 * send without asking. */
4485 if (peer->maxMTU != tSize) {
4486 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4488 peer->maxMTU = tSize;
4489 peer->MTU = MIN(tSize, peer->MTU);
4490 call->MTU = MIN(call->MTU, tSize);
4493 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4496 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4497 (int)sizeof(afs_int32), &tSize);
4498 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4499 if (tSize < call->twind) { /* smaller than our send */
4500 call->twind = tSize; /* window, we must send less... */
4501 call->ssthresh = MIN(call->twind, call->ssthresh);
4502 call->conn->twind[call->channel] = call->twind;
4505 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4506 * network MTU confused with the loopback MTU. Calculate the
4507 * maximum MTU here for use in the slow start code below.
4509 /* Did peer restart with older RX version? */
4510 if (peer->maxDgramPackets > 1) {
4511 peer->maxDgramPackets = 1;
4513 } else if (np->length >=
4514 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4517 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4518 sizeof(afs_int32), &tSize);
4519 tSize = (afs_uint32) ntohl(tSize);
4521 * As of AFS 3.5 we set the send window to match the receive window.
4523 if (tSize < call->twind) {
4524 call->twind = tSize;
4525 call->conn->twind[call->channel] = call->twind;
4526 call->ssthresh = MIN(call->twind, call->ssthresh);
4527 } else if (tSize > call->twind) {
4528 call->twind = tSize;
4529 call->conn->twind[call->channel] = call->twind;
4533 * As of AFS 3.5, a jumbogram is more than one fixed size
4534 * packet transmitted in a single UDP datagram. If the remote
4535 * MTU is smaller than our local MTU then never send a datagram
4536 * larger than the natural MTU.
4539 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4540 (int)sizeof(afs_int32), &tSize);
4541 maxDgramPackets = (afs_uint32) ntohl(tSize);
4542 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4544 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4545 if (maxDgramPackets > 1) {
4546 peer->maxDgramPackets = maxDgramPackets;
4547 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4549 peer->maxDgramPackets = 1;
4550 call->MTU = peer->natMTU;
4552 } else if (peer->maxDgramPackets > 1) {
4553 /* Restarted with lower version of RX */
4554 peer->maxDgramPackets = 1;
4556 } else if (peer->maxDgramPackets > 1
4557 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4558 /* Restarted with lower version of RX */
4559 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4560 peer->natMTU = OLD_MAX_PACKET_SIZE;
4561 peer->MTU = OLD_MAX_PACKET_SIZE;
4562 peer->maxDgramPackets = 1;
4563 peer->nDgramPackets = 1;
4565 call->MTU = OLD_MAX_PACKET_SIZE;
4570 * Calculate how many datagrams were successfully received after
4571 * the first missing packet and adjust the negative ack counter
4576 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4577 if (call->nNacks < nNacked) {
4578 call->nNacks = nNacked;
4581 call->nAcks += newAckCount;
4585 /* If the packet contained new acknowledgements, rather than just
4586 * being a duplicate of one we have previously seen, then we can restart
4589 if (newAckCount > 0)
4590 rxi_rto_packet_acked(call, istack);
4592 if (call->flags & RX_CALL_FAST_RECOVER) {
4593 if (newAckCount == 0) {
4594 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4596 call->flags &= ~RX_CALL_FAST_RECOVER;
4597 call->cwind = call->nextCwind;
4598 call->nextCwind = 0;
4601 call->nCwindAcks = 0;
4602 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4603 /* Three negative acks in a row trigger congestion recovery */
4604 call->flags |= RX_CALL_FAST_RECOVER;
4605 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4607 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4608 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4609 call->nextCwind = call->ssthresh;
4612 peer->MTU = call->MTU;
4613 peer->cwind = call->nextCwind;
4614 peer->nDgramPackets = call->nDgramPackets;
4616 call->congestSeq = peer->congestSeq;
4618 /* Reset the resend times on the packets that were nacked
4619 * so we will retransmit as soon as the window permits
4622 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4624 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4625 tp->flags &= ~RX_PKTFLAG_SENT;
4627 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4632 /* If cwind is smaller than ssthresh, then increase
4633 * the window one packet for each ack we receive (exponential
4635 * If cwind is greater than or equal to ssthresh then increase
4636 * the congestion window by one packet for each cwind acks we
4637 * receive (linear growth). */
4638 if (call->cwind < call->ssthresh) {
4640 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4641 call->nCwindAcks = 0;
4643 call->nCwindAcks += newAckCount;
4644 if (call->nCwindAcks >= call->cwind) {
4645 call->nCwindAcks = 0;
4646 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4650 * If we have received several acknowledgements in a row then
4651 * it is time to increase the size of our datagrams
4653 if ((int)call->nAcks > rx_nDgramThreshold) {
4654 if (peer->maxDgramPackets > 1) {
4655 if (call->nDgramPackets < peer->maxDgramPackets) {
4656 call->nDgramPackets++;
4658 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4659 } else if (call->MTU < peer->maxMTU) {
4660 /* don't upgrade if we can't handle it */
4661 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4662 call->MTU = peer->ifMTU;
4664 call->MTU += peer->natMTU;
4665 call->MTU = MIN(call->MTU, peer->maxMTU);
4672 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4674 /* Servers need to hold the call until all response packets have
4675 * been acknowledged. Soft acks are good enough since clients
4676 * are not allowed to clear their receive queues. */
4677 if (call->state == RX_STATE_HOLD
4678 && call->tfirst + call->nSoftAcked >= call->tnext) {
4679 call->state = RX_STATE_DALLY;
4680 rxi_ClearTransmitQueue(call, 0);
4681 rxevent_Cancel(&call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4682 } else if (!queue_IsEmpty(&call->tq)) {
4683 rxi_Start(call, istack);
4688 /* Received a response to a challenge packet */
4690 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4691 struct rx_packet *np, int istack)
4695 /* Ignore the packet if we're the client */
4696 if (conn->type == RX_CLIENT_CONNECTION)
4699 /* If already authenticated, ignore the packet (it's probably a retry) */
4700 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4703 /* Otherwise, have the security object evaluate the response packet */
4704 error = RXS_CheckResponse(conn->securityObject, conn, np);
4706 /* If the response is invalid, reset the connection, sending
4707 * an abort to the peer */
4711 rxi_ConnectionError(conn, error);
4712 MUTEX_ENTER(&conn->conn_data_lock);
4713 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4714 MUTEX_EXIT(&conn->conn_data_lock);
4717 /* If the response is valid, any calls waiting to attach
4718 * servers can now do so */
4721 for (i = 0; i < RX_MAXCALLS; i++) {
4722 struct rx_call *call = conn->call[i];
4724 MUTEX_ENTER(&call->lock);
4725 if (call->state == RX_STATE_PRECALL)
4726 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4727 /* tnop can be null if newcallp is null */
4728 MUTEX_EXIT(&call->lock);
4732 /* Update the peer reachability information, just in case
4733 * some calls went into attach-wait while we were waiting
4734 * for authentication..
4736 rxi_UpdatePeerReach(conn, NULL);
4741 /* A client has received an authentication challenge: the security
4742 * object is asked to cough up a respectable response packet to send
4743 * back to the server. The server is responsible for retrying the
4744 * challenge if it fails to get a response. */
4747 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4748 struct rx_packet *np, int istack)
4752 /* Ignore the challenge if we're the server */
4753 if (conn->type == RX_SERVER_CONNECTION)
4756 /* Ignore the challenge if the connection is otherwise idle; someone's
4757 * trying to use us as an oracle. */
4758 if (!rxi_HasActiveCalls(conn))
4761 /* Send the security object the challenge packet. It is expected to fill
4762 * in the response. */
4763 error = RXS_GetResponse(conn->securityObject, conn, np);
4765 /* If the security object is unable to return a valid response, reset the
4766 * connection and send an abort to the peer. Otherwise send the response
4767 * packet to the peer connection. */
4769 rxi_ConnectionError(conn, error);
4770 MUTEX_ENTER(&conn->conn_data_lock);
4771 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4772 MUTEX_EXIT(&conn->conn_data_lock);
4774 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4775 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4781 /* Find an available server process to service the current request in
4782 * the given call structure. If one isn't available, queue up this
4783 * call so it eventually gets one */
4785 rxi_AttachServerProc(struct rx_call *call,
4786 osi_socket socket, int *tnop,
4787 struct rx_call **newcallp)
4789 struct rx_serverQueueEntry *sq;
4790 struct rx_service *service = call->conn->service;
4793 /* May already be attached */
4794 if (call->state == RX_STATE_ACTIVE)
4797 MUTEX_ENTER(&rx_serverPool_lock);
4799 haveQuota = QuotaOK(service);
4800 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4801 /* If there are no processes available to service this call,
4802 * put the call on the incoming call queue (unless it's
4803 * already on the queue).
4805 #ifdef RX_ENABLE_LOCKS
4807 ReturnToServerPool(service);
4808 #endif /* RX_ENABLE_LOCKS */
4810 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4811 call->flags |= RX_CALL_WAIT_PROC;
4812 rx_atomic_inc(&rx_nWaiting);
4813 rx_atomic_inc(&rx_nWaited);
4814 rxi_calltrace(RX_CALL_ARRIVAL, call);
4815 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4816 queue_Append(&rx_incomingCallQueue, call);
4819 sq = queue_Last(&rx_idleServerQueue, rx_serverQueueEntry);
4821 /* If hot threads are enabled, and both newcallp and sq->socketp
4822 * are non-null, then this thread will process the call, and the
4823 * idle server thread will start listening on this threads socket.
4826 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4829 *sq->socketp = socket;
4830 clock_GetTime(&call->startTime);
4831 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4835 if (call->flags & RX_CALL_WAIT_PROC) {
4836 /* Conservative: I don't think this should happen */
4837 call->flags &= ~RX_CALL_WAIT_PROC;
4838 if (queue_IsOnQueue(call)) {
4841 rx_atomic_dec(&rx_nWaiting);
4844 call->state = RX_STATE_ACTIVE;
4845 call->mode = RX_MODE_RECEIVING;
4846 #ifdef RX_KERNEL_TRACE
4848 int glockOwner = ISAFS_GLOCK();
4851 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4852 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4858 if (call->flags & RX_CALL_CLEARED) {
4859 /* send an ack now to start the packet flow up again */
4860 call->flags &= ~RX_CALL_CLEARED;
4861 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4863 #ifdef RX_ENABLE_LOCKS
4866 service->nRequestsRunning++;
4867 MUTEX_ENTER(&rx_quota_mutex);
4868 if (service->nRequestsRunning <= service->minProcs)
4871 MUTEX_EXIT(&rx_quota_mutex);
4875 MUTEX_EXIT(&rx_serverPool_lock);
4878 /* Delay the sending of an acknowledge event for a short while, while
4879 * a new call is being prepared (in the case of a client) or a reply
4880 * is being prepared (in the case of a server). Rather than sending
4881 * an ack packet, an ACKALL packet is sent. */
4883 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4885 #ifdef RX_ENABLE_LOCKS
4887 MUTEX_ENTER(&call->lock);
4888 rxevent_Put(call->delayedAckEvent);
4889 call->delayedAckEvent = NULL;
4890 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4892 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4893 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4894 call->flags |= RX_CALL_ACKALL_SENT;
4896 MUTEX_EXIT(&call->lock);
4897 #else /* RX_ENABLE_LOCKS */
4899 rxevent_Put(call->delayedAckEvent);
4900 call->delayedAckEvent = NULL;
4902 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4903 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4904 call->flags |= RX_CALL_ACKALL_SENT;
4905 #endif /* RX_ENABLE_LOCKS */
4909 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4912 struct rx_call *call = arg1;
4913 #ifdef RX_ENABLE_LOCKS
4915 MUTEX_ENTER(&call->lock);
4916 if (event == call->delayedAckEvent) {
4917 rxevent_Put(call->delayedAckEvent);
4918 call->delayedAckEvent = NULL;
4920 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4922 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4924 MUTEX_EXIT(&call->lock);
4925 #else /* RX_ENABLE_LOCKS */
4927 rxevent_Put(call->delayedAckEvent);
4928 call->delayedAckEvent = NULL;
4930 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4931 #endif /* RX_ENABLE_LOCKS */
4935 #ifdef RX_ENABLE_LOCKS
4936 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4937 * clearing them out.
4940 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4942 struct rx_packet *p, *tp;
4945 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4946 p->flags |= RX_PKTFLAG_ACKED;
4950 call->flags |= RX_CALL_TQ_CLEARME;
4951 call->flags |= RX_CALL_TQ_SOME_ACKED;
4954 rxi_rto_cancel(call);
4956 call->tfirst = call->tnext;
4957 call->nSoftAcked = 0;
4959 if (call->flags & RX_CALL_FAST_RECOVER) {
4960 call->flags &= ~RX_CALL_FAST_RECOVER;
4961 call->cwind = call->nextCwind;
4962 call->nextCwind = 0;
4965 CV_SIGNAL(&call->cv_twind);
4967 #endif /* RX_ENABLE_LOCKS */
4969 /* Clear out the transmit queue for the current call (all packets have
4970 * been received by peer) */
4972 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4974 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4975 struct rx_packet *p, *tp;
4977 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4979 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4980 p->flags |= RX_PKTFLAG_ACKED;
4984 call->flags |= RX_CALL_TQ_CLEARME;
4985 call->flags |= RX_CALL_TQ_SOME_ACKED;
4988 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4989 #ifdef RXDEBUG_PACKET
4991 #endif /* RXDEBUG_PACKET */
4992 rxi_FreePackets(0, &call->tq);
4993 rxi_WakeUpTransmitQueue(call);
4994 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4995 call->flags &= ~RX_CALL_TQ_CLEARME;
4997 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4999 rxi_rto_cancel(call);
5000 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5001 call->nSoftAcked = 0;
5003 if (call->flags & RX_CALL_FAST_RECOVER) {
5004 call->flags &= ~RX_CALL_FAST_RECOVER;
5005 call->cwind = call->nextCwind;
5007 #ifdef RX_ENABLE_LOCKS
5008 CV_SIGNAL(&call->cv_twind);
5010 osi_rxWakeup(&call->twind);
5015 rxi_ClearReceiveQueue(struct rx_call *call)
5017 if (queue_IsNotEmpty(&call->rq)) {
5020 count = rxi_FreePackets(0, &call->rq);
5021 rx_packetReclaims += count;
5022 #ifdef RXDEBUG_PACKET
5024 if ( call->rqc != 0 )
5025 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5027 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5029 if (call->state == RX_STATE_PRECALL) {
5030 call->flags |= RX_CALL_CLEARED;
5034 /* Send an abort packet for the specified call */
5036 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5037 int istack, int force)
5039 afs_int32 error, cerror;
5040 struct clock when, now;
5045 switch (call->error) {
5048 cerror = RX_CALL_TIMEOUT;
5051 cerror = call->error;
5054 /* Clients should never delay abort messages */
5055 if (rx_IsClientConn(call->conn))
5058 if (call->abortCode != cerror) {
5059 call->abortCode = cerror;
5060 call->abortCount = 0;
5063 if (force || rxi_callAbortThreshhold == 0
5064 || call->abortCount < rxi_callAbortThreshhold) {
5065 if (call->delayedAbortEvent) {
5066 rxevent_Cancel(&call->delayedAbortEvent, call,
5067 RX_CALL_REFCOUNT_ABORT);
5069 error = htonl(cerror);
5072 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5073 (char *)&error, sizeof(error), istack);
5074 } else if (!call->delayedAbortEvent) {
5075 clock_GetTime(&now);
5077 clock_Addmsec(&when, rxi_callAbortDelay);
5078 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5079 call->delayedAbortEvent =
5080 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5085 /* Send an abort packet for the specified connection. Packet is an
5086 * optional pointer to a packet that can be used to send the abort.
5087 * Once the number of abort messages reaches the threshhold, an
5088 * event is scheduled to send the abort. Setting the force flag
5089 * overrides sending delayed abort messages.
5091 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5092 * to send the abort packet.
5095 rxi_SendConnectionAbort(struct rx_connection *conn,
5096 struct rx_packet *packet, int istack, int force)
5099 struct clock when, now;
5104 /* Clients should never delay abort messages */
5105 if (rx_IsClientConn(conn))
5108 if (force || rxi_connAbortThreshhold == 0
5109 || conn->abortCount < rxi_connAbortThreshhold) {
5111 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
5112 error = htonl(conn->error);
5114 MUTEX_EXIT(&conn->conn_data_lock);
5116 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5117 RX_PACKET_TYPE_ABORT, (char *)&error,
5118 sizeof(error), istack);
5119 MUTEX_ENTER(&conn->conn_data_lock);
5120 } else if (!conn->delayedAbortEvent) {
5121 clock_GetTime(&now);
5123 clock_Addmsec(&when, rxi_connAbortDelay);
5124 conn->delayedAbortEvent =
5125 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
5130 /* Associate an error all of the calls owned by a connection. Called
5131 * with error non-zero. This is only for really fatal things, like
5132 * bad authentication responses. The connection itself is set in
5133 * error at this point, so that future packets received will be
5136 rxi_ConnectionError(struct rx_connection *conn,
5142 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5144 MUTEX_ENTER(&conn->conn_data_lock);
5145 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
5146 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
5147 if (conn->checkReachEvent) {
5148 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
5149 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5150 putConnection(conn);
5152 MUTEX_EXIT(&conn->conn_data_lock);
5153 for (i = 0; i < RX_MAXCALLS; i++) {
5154 struct rx_call *call = conn->call[i];
5156 MUTEX_ENTER(&call->lock);
5157 rxi_CallError(call, error);
5158 MUTEX_EXIT(&call->lock);
5161 conn->error = error;
5162 if (rx_stats_active)
5163 rx_atomic_inc(&rx_stats.fatalErrors);
5168 * Interrupt an in-progress call with the specified error and wakeup waiters.
5170 * @param[in] call The call to interrupt
5171 * @param[in] error The error code to send to the peer
5174 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5176 MUTEX_ENTER(&call->lock);
5177 rxi_CallError(call, error);
5178 rxi_SendCallAbort(call, NULL, 0, 1);
5179 MUTEX_EXIT(&call->lock);
5183 rxi_CallError(struct rx_call *call, afs_int32 error)
5186 osirx_AssertMine(&call->lock, "rxi_CallError");
5188 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5190 error = call->error;
5192 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5193 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5194 rxi_ResetCall(call, 0);
5197 rxi_ResetCall(call, 0);
5199 call->error = error;
5202 /* Reset various fields in a call structure, and wakeup waiting
5203 * processes. Some fields aren't changed: state & mode are not
5204 * touched (these must be set by the caller), and bufptr, nLeft, and
5205 * nFree are not reset, since these fields are manipulated by
5206 * unprotected macros, and may only be reset by non-interrupting code.
5210 rxi_ResetCall(struct rx_call *call, int newcall)
5213 struct rx_peer *peer;
5214 struct rx_packet *packet;
5216 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5218 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5220 /* Notify anyone who is waiting for asynchronous packet arrival */
5221 if (call->arrivalProc) {
5222 (*call->arrivalProc) (call, call->arrivalProcHandle,
5223 call->arrivalProcArg);
5224 call->arrivalProc = (void (*)())0;
5228 rxevent_Cancel(&call->growMTUEvent, call, RX_CALL_REFCOUNT_MTU);
5230 if (call->delayedAbortEvent) {
5231 rxevent_Cancel(&call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5232 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5234 rxi_SendCallAbort(call, packet, 0, 1);
5235 rxi_FreePacket(packet);
5240 * Update the peer with the congestion information in this call
5241 * so other calls on this connection can pick up where this call
5242 * left off. If the congestion sequence numbers don't match then
5243 * another call experienced a retransmission.
5245 peer = call->conn->peer;
5246 MUTEX_ENTER(&peer->peer_lock);
5248 if (call->congestSeq == peer->congestSeq) {
5249 peer->cwind = MAX(peer->cwind, call->cwind);
5250 peer->MTU = MAX(peer->MTU, call->MTU);
5251 peer->nDgramPackets =
5252 MAX(peer->nDgramPackets, call->nDgramPackets);
5255 call->abortCode = 0;
5256 call->abortCount = 0;
5258 if (peer->maxDgramPackets > 1) {
5259 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5261 call->MTU = peer->MTU;
5263 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5264 call->ssthresh = rx_maxSendWindow;
5265 call->nDgramPackets = peer->nDgramPackets;
5266 call->congestSeq = peer->congestSeq;
5267 call->rtt = peer->rtt;
5268 call->rtt_dev = peer->rtt_dev;
5269 clock_Zero(&call->rto);
5270 clock_Addmsec(&call->rto,
5271 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5272 MUTEX_EXIT(&peer->peer_lock);
5274 flags = call->flags;
5275 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5276 rxi_WaitforTQBusy(call);
5277 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5279 rxi_ClearTransmitQueue(call, 1);
5280 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5281 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5285 if (!newcall && (flags & RX_CALL_PEER_BUSY)) {
5286 /* The call channel is still busy; resetting the call doesn't change
5287 * that. However, if 'newcall' is set, we are processing a call
5288 * structure that has either been recycled from the free list, or has
5289 * been newly allocated. So, RX_CALL_PEER_BUSY is not relevant if
5290 * 'newcall' is set, since it describes a completely different call
5291 * channel which we do not care about. */
5292 call->flags |= RX_CALL_PEER_BUSY;
5295 rxi_ClearReceiveQueue(call);
5296 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5300 call->twind = call->conn->twind[call->channel];
5301 call->rwind = call->conn->rwind[call->channel];
5302 call->nSoftAcked = 0;
5303 call->nextCwind = 0;
5306 call->nCwindAcks = 0;
5307 call->nSoftAcks = 0;
5308 call->nHardAcks = 0;
5310 call->tfirst = call->rnext = call->tnext = 1;
5313 call->lastAcked = 0;
5314 call->localStatus = call->remoteStatus = 0;
5316 if (flags & RX_CALL_READER_WAIT) {
5317 #ifdef RX_ENABLE_LOCKS
5318 CV_BROADCAST(&call->cv_rq);
5320 osi_rxWakeup(&call->rq);
5323 if (flags & RX_CALL_WAIT_PACKETS) {
5324 MUTEX_ENTER(&rx_freePktQ_lock);
5325 rxi_PacketsUnWait(); /* XXX */
5326 MUTEX_EXIT(&rx_freePktQ_lock);
5328 #ifdef RX_ENABLE_LOCKS
5329 CV_SIGNAL(&call->cv_twind);
5331 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5332 osi_rxWakeup(&call->twind);
5335 #ifdef RX_ENABLE_LOCKS
5336 /* The following ensures that we don't mess with any queue while some
5337 * other thread might also be doing so. The call_queue_lock field is
5338 * is only modified under the call lock. If the call is in the process
5339 * of being removed from a queue, the call is not locked until the
5340 * the queue lock is dropped and only then is the call_queue_lock field
5341 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5342 * Note that any other routine which removes a call from a queue has to
5343 * obtain the queue lock before examing the queue and removing the call.
5345 if (call->call_queue_lock) {
5346 MUTEX_ENTER(call->call_queue_lock);
5347 if (queue_IsOnQueue(call)) {
5349 if (flags & RX_CALL_WAIT_PROC) {
5350 rx_atomic_dec(&rx_nWaiting);
5353 MUTEX_EXIT(call->call_queue_lock);
5354 CLEAR_CALL_QUEUE_LOCK(call);
5356 #else /* RX_ENABLE_LOCKS */
5357 if (queue_IsOnQueue(call)) {
5359 if (flags & RX_CALL_WAIT_PROC)
5360 rx_atomic_dec(&rx_nWaiting);
5362 #endif /* RX_ENABLE_LOCKS */
5364 rxi_KeepAliveOff(call);
5365 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5368 /* Send an acknowledge for the indicated packet (seq,serial) of the
5369 * indicated call, for the indicated reason (reason). This
5370 * acknowledge will specifically acknowledge receiving the packet, and
5371 * will also specify which other packets for this call have been
5372 * received. This routine returns the packet that was used to the
5373 * caller. The caller is responsible for freeing it or re-using it.
5374 * This acknowledgement also returns the highest sequence number
5375 * actually read out by the higher level to the sender; the sender
5376 * promises to keep around packets that have not been read by the
5377 * higher level yet (unless, of course, the sender decides to abort
5378 * the call altogether). Any of p, seq, serial, pflags, or reason may
5379 * be set to zero without ill effect. That is, if they are zero, they
5380 * will not convey any information.
5381 * NOW there is a trailer field, after the ack where it will safely be
5382 * ignored by mundanes, which indicates the maximum size packet this
5383 * host can swallow. */
5385 struct rx_packet *optionalPacket; use to send ack (or null)
5386 int seq; Sequence number of the packet we are acking
5387 int serial; Serial number of the packet
5388 int pflags; Flags field from packet header
5389 int reason; Reason an acknowledge was prompted
5393 rxi_SendAck(struct rx_call *call,
5394 struct rx_packet *optionalPacket, int serial, int reason,
5397 struct rx_ackPacket *ap;
5398 struct rx_packet *rqp;
5399 struct rx_packet *nxp; /* For queue_Scan */
5400 struct rx_packet *p;
5403 afs_uint32 padbytes = 0;
5404 #ifdef RX_ENABLE_TSFPQ
5405 struct rx_ts_info_t * rx_ts_info;
5409 * Open the receive window once a thread starts reading packets
5411 if (call->rnext > 1) {
5412 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5415 /* Don't attempt to grow MTU if this is a critical ping */
5416 if (reason == RX_ACK_MTU) {
5417 /* keep track of per-call attempts, if we're over max, do in small
5418 * otherwise in larger? set a size to increment by, decrease
5421 if (call->conn->peer->maxPacketSize &&
5422 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5424 padbytes = call->conn->peer->maxPacketSize+16;
5426 padbytes = call->conn->peer->maxMTU + 128;
5428 /* do always try a minimum size ping */
5429 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5431 /* subtract the ack payload */
5432 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5433 reason = RX_ACK_PING;
5436 call->nHardAcks = 0;
5437 call->nSoftAcks = 0;
5438 if (call->rnext > call->lastAcked)
5439 call->lastAcked = call->rnext;
5443 rx_computelen(p, p->length); /* reset length, you never know */
5444 } /* where that's been... */
5445 #ifdef RX_ENABLE_TSFPQ
5447 RX_TS_INFO_GET(rx_ts_info);
5448 if ((p = rx_ts_info->local_special_packet)) {
5449 rx_computelen(p, p->length);
5450 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5451 rx_ts_info->local_special_packet = p;
5452 } else { /* We won't send the ack, but don't panic. */
5453 return optionalPacket;
5457 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5458 /* We won't send the ack, but don't panic. */
5459 return optionalPacket;
5464 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5467 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5468 #ifndef RX_ENABLE_TSFPQ
5469 if (!optionalPacket)
5472 return optionalPacket;
5474 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5475 if (rx_Contiguous(p) < templ) {
5476 #ifndef RX_ENABLE_TSFPQ
5477 if (!optionalPacket)
5480 return optionalPacket;
5485 /* MTUXXX failing to send an ack is very serious. We should */
5486 /* try as hard as possible to send even a partial ack; it's */
5487 /* better than nothing. */
5488 ap = (struct rx_ackPacket *)rx_DataOf(p);
5489 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5490 ap->reason = reason;
5492 /* The skew computation used to be bogus, I think it's better now. */
5493 /* We should start paying attention to skew. XXX */
5494 ap->serial = htonl(serial);
5495 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5498 * First packet not yet forwarded to reader. When ACKALL has been
5499 * sent the peer has been told that all received packets will be
5500 * delivered to the reader. The value 'rnext' is used internally
5501 * to refer to the next packet in the receive queue that must be
5502 * delivered to the reader. From the perspective of the peer it
5503 * already has so report the last sequence number plus one if there
5504 * are packets in the receive queue awaiting processing.
5506 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5507 !queue_IsEmpty(&call->rq)) {
5508 ap->firstPacket = htonl(queue_Last(&call->rq, rx_packet)->header.seq + 1);
5510 ap->firstPacket = htonl(call->rnext);
5512 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5514 /* No fear of running out of ack packet here because there can only be at most
5515 * one window full of unacknowledged packets. The window size must be constrained
5516 * to be less than the maximum ack size, of course. Also, an ack should always
5517 * fit into a single packet -- it should not ever be fragmented. */
5518 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5519 if (!rqp || !call->rq.next
5520 || (rqp->header.seq > (call->rnext + call->rwind))) {
5521 #ifndef RX_ENABLE_TSFPQ
5522 if (!optionalPacket)
5525 rxi_CallError(call, RX_CALL_DEAD);
5526 return optionalPacket;
5529 while (rqp->header.seq > call->rnext + offset)
5530 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5531 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5533 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5534 #ifndef RX_ENABLE_TSFPQ
5535 if (!optionalPacket)
5538 rxi_CallError(call, RX_CALL_DEAD);
5539 return optionalPacket;
5545 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5547 /* these are new for AFS 3.3 */
5548 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5549 templ = htonl(templ);
5550 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5551 templ = htonl(call->conn->peer->ifMTU);
5552 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5553 sizeof(afs_int32), &templ);
5555 /* new for AFS 3.4 */
5556 templ = htonl(call->rwind);
5557 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5558 sizeof(afs_int32), &templ);
5560 /* new for AFS 3.5 */
5561 templ = htonl(call->conn->peer->ifDgramPackets);
5562 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5563 sizeof(afs_int32), &templ);
5565 p->header.serviceId = call->conn->serviceId;
5566 p->header.cid = (call->conn->cid | call->channel);
5567 p->header.callNumber = *call->callNumber;
5569 p->header.securityIndex = call->conn->securityIndex;
5570 p->header.epoch = call->conn->epoch;
5571 p->header.type = RX_PACKET_TYPE_ACK;
5572 p->header.flags = RX_SLOW_START_OK;
5573 if (reason == RX_ACK_PING) {
5574 p->header.flags |= RX_REQUEST_ACK;
5576 p->length = padbytes +
5577 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5580 /* not fast but we can potentially use this if truncated
5581 * fragments are delivered to figure out the mtu.
5583 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5584 sizeof(afs_int32), sizeof(afs_int32),
5588 if (call->conn->type == RX_CLIENT_CONNECTION)
5589 p->header.flags |= RX_CLIENT_INITIATED;
5593 if (rxdebug_active) {
5597 len = _snprintf(msg, sizeof(msg),
5598 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5599 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5600 ntohl(ap->serial), ntohl(ap->previousPacket),
5601 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5602 ap->nAcks, ntohs(ap->bufferSpace) );
5606 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5607 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5611 OutputDebugString(msg);
5613 #else /* AFS_NT40_ENV */
5615 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5616 ap->reason, ntohl(ap->previousPacket),
5617 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5619 for (offset = 0; offset < ap->nAcks; offset++)
5620 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5625 #endif /* AFS_NT40_ENV */
5628 int i, nbytes = p->length;
5630 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5631 if (nbytes <= p->wirevec[i].iov_len) {
5634 savelen = p->wirevec[i].iov_len;
5636 p->wirevec[i].iov_len = nbytes;
5638 rxi_Send(call, p, istack);
5639 p->wirevec[i].iov_len = savelen;
5643 nbytes -= p->wirevec[i].iov_len;
5646 if (rx_stats_active)
5647 rx_atomic_inc(&rx_stats.ackPacketsSent);
5648 #ifndef RX_ENABLE_TSFPQ
5649 if (!optionalPacket)
5652 return optionalPacket; /* Return packet for re-use by caller */
5656 struct rx_packet **list;
5661 /* Send all of the packets in the list in single datagram */
5663 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5664 int istack, int moreFlag)
5670 struct rx_connection *conn = call->conn;
5671 struct rx_peer *peer = conn->peer;
5673 MUTEX_ENTER(&peer->peer_lock);
5674 peer->nSent += xmit->len;
5675 if (xmit->resending)
5676 peer->reSends += xmit->len;
5677 MUTEX_EXIT(&peer->peer_lock);
5679 if (rx_stats_active) {
5680 if (xmit->resending)
5681 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5683 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5686 clock_GetTime(&now);
5688 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5692 /* Set the packet flags and schedule the resend events */
5693 /* Only request an ack for the last packet in the list */
5694 for (i = 0; i < xmit->len; i++) {
5695 struct rx_packet *packet = xmit->list[i];
5697 /* Record the time sent */
5698 packet->timeSent = now;
5699 packet->flags |= RX_PKTFLAG_SENT;
5701 /* Ask for an ack on retransmitted packets, on every other packet
5702 * if the peer doesn't support slow start. Ask for an ack on every
5703 * packet until the congestion window reaches the ack rate. */
5704 if (packet->header.serial) {
5707 packet->firstSent = now;
5708 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5709 || (!(call->flags & RX_CALL_SLOW_START_OK)
5710 && (packet->header.seq & 1)))) {
5715 /* Tag this packet as not being the last in this group,
5716 * for the receiver's benefit */
5717 if (i < xmit->len - 1 || moreFlag) {
5718 packet->header.flags |= RX_MORE_PACKETS;
5723 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5726 /* Since we're about to send a data packet to the peer, it's
5727 * safe to nuke any scheduled end-of-packets ack */
5728 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5730 MUTEX_EXIT(&call->lock);
5731 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5732 if (xmit->len > 1) {
5733 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5735 rxi_SendPacket(call, conn, xmit->list[0], istack);
5737 MUTEX_ENTER(&call->lock);
5738 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5740 /* Tell the RTO calculation engine that we have sent a packet, and
5741 * if it was the last one */
5742 rxi_rto_packet_sent(call, lastPacket, istack);
5744 /* Update last send time for this call (for keep-alive
5745 * processing), and for the connection (so that we can discover
5746 * idle connections) */
5747 conn->lastSendTime = call->lastSendTime = clock_Sec();
5748 /* Let a set of retransmits trigger an idle timeout */
5749 if (!xmit->resending)
5750 call->lastSendData = call->lastSendTime;
5753 /* When sending packets we need to follow these rules:
5754 * 1. Never send more than maxDgramPackets in a jumbogram.
5755 * 2. Never send a packet with more than two iovecs in a jumbogram.
5756 * 3. Never send a retransmitted packet in a jumbogram.
5757 * 4. Never send more than cwind/4 packets in a jumbogram
5758 * We always keep the last list we should have sent so we
5759 * can set the RX_MORE_PACKETS flags correctly.
5763 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5768 struct xmitlist working;
5769 struct xmitlist last;
5771 struct rx_peer *peer = call->conn->peer;
5772 int morePackets = 0;
5774 memset(&last, 0, sizeof(struct xmitlist));
5775 working.list = &list[0];
5777 working.resending = 0;
5779 recovery = call->flags & RX_CALL_FAST_RECOVER;
5781 for (i = 0; i < len; i++) {
5782 /* Does the current packet force us to flush the current list? */
5784 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5785 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5787 /* This sends the 'last' list and then rolls the current working
5788 * set into the 'last' one, and resets the working set */
5791 rxi_SendList(call, &last, istack, 1);
5792 /* If the call enters an error state stop sending, or if
5793 * we entered congestion recovery mode, stop sending */
5795 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5800 working.resending = 0;
5801 working.list = &list[i];
5803 /* Add the current packet to the list if it hasn't been acked.
5804 * Otherwise adjust the list pointer to skip the current packet. */
5805 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5808 if (list[i]->header.serial)
5809 working.resending = 1;
5811 /* Do we need to flush the list? */
5812 if (working.len >= (int)peer->maxDgramPackets
5813 || working.len >= (int)call->nDgramPackets
5814 || working.len >= (int)call->cwind
5815 || list[i]->header.serial
5816 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5818 rxi_SendList(call, &last, istack, 1);
5819 /* If the call enters an error state stop sending, or if
5820 * we entered congestion recovery mode, stop sending */
5822 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5827 working.resending = 0;
5828 working.list = &list[i + 1];
5831 if (working.len != 0) {
5832 osi_Panic("rxi_SendList error");
5834 working.list = &list[i + 1];
5838 /* Send the whole list when the call is in receive mode, when
5839 * the call is in eof mode, when we are in fast recovery mode,
5840 * and when we have the last packet */
5841 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5842 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5843 || (call->flags & RX_CALL_FAST_RECOVER)) {
5844 /* Check for the case where the current list contains
5845 * an acked packet. Since we always send retransmissions
5846 * in a separate packet, we only need to check the first
5847 * packet in the list */
5848 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5852 rxi_SendList(call, &last, istack, morePackets);
5853 /* If the call enters an error state stop sending, or if
5854 * we entered congestion recovery mode, stop sending */
5856 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5860 rxi_SendList(call, &working, istack, 0);
5862 } else if (last.len > 0) {
5863 rxi_SendList(call, &last, istack, 0);
5864 /* Packets which are in 'working' are not sent by this call */
5869 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5871 struct rx_call *call = arg0;
5872 struct rx_peer *peer;
5873 struct rx_packet *p, *nxp;
5874 struct clock maxTimeout = { 60, 0 };
5876 MUTEX_ENTER(&call->lock);
5878 peer = call->conn->peer;
5880 /* Make sure that the event pointer is removed from the call
5881 * structure, since there is no longer a per-call retransmission
5883 if (event == call->resendEvent) {
5884 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5885 rxevent_Put(call->resendEvent);
5886 call->resendEvent = NULL;
5889 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5890 rxi_CheckBusy(call);
5893 if (queue_IsEmpty(&call->tq)) {
5894 /* Nothing to do. This means that we've been raced, and that an
5895 * ACK has come in between when we were triggered, and when we
5896 * actually got to run. */
5900 /* We're in loss recovery */
5901 call->flags |= RX_CALL_FAST_RECOVER;
5903 /* Mark all of the pending packets in the queue as being lost */
5904 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5905 if (!(p->flags & RX_PKTFLAG_ACKED))
5906 p->flags &= ~RX_PKTFLAG_SENT;
5909 /* We're resending, so we double the timeout of the call. This will be
5910 * dropped back down by the first successful ACK that we receive.
5912 * We apply a maximum value here of 60 seconds
5914 clock_Add(&call->rto, &call->rto);
5915 if (clock_Gt(&call->rto, &maxTimeout))
5916 call->rto = maxTimeout;
5918 /* Packet loss is most likely due to congestion, so drop our window size
5919 * and start again from the beginning */
5920 if (peer->maxDgramPackets >1) {
5921 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5922 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5924 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5925 call->nDgramPackets = 1;
5927 call->nextCwind = 1;
5930 MUTEX_ENTER(&peer->peer_lock);
5931 peer->MTU = call->MTU;
5932 peer->cwind = call->cwind;
5933 peer->nDgramPackets = 1;
5935 call->congestSeq = peer->congestSeq;
5936 MUTEX_EXIT(&peer->peer_lock);
5938 rxi_Start(call, istack);
5941 MUTEX_EXIT(&call->lock);
5944 /* This routine is called when new packets are readied for
5945 * transmission and when retransmission may be necessary, or when the
5946 * transmission window or burst count are favourable. This should be
5947 * better optimized for new packets, the usual case, now that we've
5948 * got rid of queues of send packets. XXXXXXXXXXX */
5950 rxi_Start(struct rx_call *call, int istack)
5953 struct rx_packet *p;
5954 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5959 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5960 if (rx_stats_active)
5961 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5966 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5968 /* Send (or resend) any packets that need it, subject to
5969 * window restrictions and congestion burst control
5970 * restrictions. Ask for an ack on the last packet sent in
5971 * this burst. For now, we're relying upon the window being
5972 * considerably bigger than the largest number of packets that
5973 * are typically sent at once by one initial call to
5974 * rxi_Start. This is probably bogus (perhaps we should ask
5975 * for an ack when we're half way through the current
5976 * window?). Also, for non file transfer applications, this
5977 * may end up asking for an ack for every packet. Bogus. XXXX
5980 * But check whether we're here recursively, and let the other guy
5983 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5984 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5985 call->flags |= RX_CALL_TQ_BUSY;
5987 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5989 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5990 call->flags &= ~RX_CALL_NEED_START;
5991 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5993 maxXmitPackets = MIN(call->twind, call->cwind);
5994 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5995 #ifdef RX_TRACK_PACKETS
5996 if ((p->flags & RX_PKTFLAG_FREE)
5997 || (!queue_IsEnd(&call->tq, nxp)
5998 && (nxp->flags & RX_PKTFLAG_FREE))
5999 || (p == (struct rx_packet *)&rx_freePacketQueue)
6000 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
6001 osi_Panic("rxi_Start: xmit queue clobbered");
6004 if (p->flags & RX_PKTFLAG_ACKED) {
6005 /* Since we may block, don't trust this */
6006 if (rx_stats_active)
6007 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6008 continue; /* Ignore this packet if it has been acknowledged */
6011 /* Turn off all flags except these ones, which are the same
6012 * on each transmission */
6013 p->header.flags &= RX_PRESET_FLAGS;
6015 if (p->header.seq >=
6016 call->tfirst + MIN((int)call->twind,
6017 (int)(call->nSoftAcked +
6019 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6020 /* Note: if we're waiting for more window space, we can
6021 * still send retransmits; hence we don't return here, but
6022 * break out to schedule a retransmit event */
6023 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6024 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6029 /* Transmit the packet if it needs to be sent. */
6030 if (!(p->flags & RX_PKTFLAG_SENT)) {
6031 if (nXmitPackets == maxXmitPackets) {
6032 rxi_SendXmitList(call, call->xmitList,
6033 nXmitPackets, istack);
6036 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6037 *(call->callNumber), p));
6038 call->xmitList[nXmitPackets++] = p;
6042 /* xmitList now hold pointers to all of the packets that are
6043 * ready to send. Now we loop to send the packets */
6044 if (nXmitPackets > 0) {
6045 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6049 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6051 /* We went into the error state while sending packets. Now is
6052 * the time to reset the call. This will also inform the using
6053 * process that the call is in an error state.
6055 if (rx_stats_active)
6056 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6057 call->flags &= ~RX_CALL_TQ_BUSY;
6058 rxi_WakeUpTransmitQueue(call);
6059 rxi_CallError(call, call->error);
6062 #ifdef RX_ENABLE_LOCKS
6063 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6065 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6066 /* Some packets have received acks. If they all have, we can clear
6067 * the transmit queue.
6070 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
6071 if (p->header.seq < call->tfirst
6072 && (p->flags & RX_PKTFLAG_ACKED)) {
6074 #ifdef RX_TRACK_PACKETS
6075 p->flags &= ~RX_PKTFLAG_TQ;
6077 #ifdef RXDEBUG_PACKET
6085 call->flags |= RX_CALL_TQ_CLEARME;
6087 #endif /* RX_ENABLE_LOCKS */
6088 if (call->flags & RX_CALL_TQ_CLEARME)
6089 rxi_ClearTransmitQueue(call, 1);
6090 } while (call->flags & RX_CALL_NEED_START);
6092 * TQ references no longer protected by this flag; they must remain
6093 * protected by the global lock.
6095 call->flags &= ~RX_CALL_TQ_BUSY;
6096 rxi_WakeUpTransmitQueue(call);
6098 call->flags |= RX_CALL_NEED_START;
6100 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6102 rxi_rto_cancel(call);
6106 /* Also adjusts the keep alive parameters for the call, to reflect
6107 * that we have just sent a packet (so keep alives aren't sent
6110 rxi_Send(struct rx_call *call, struct rx_packet *p,
6113 struct rx_connection *conn = call->conn;
6115 /* Stamp each packet with the user supplied status */
6116 p->header.userStatus = call->localStatus;
6118 /* Allow the security object controlling this call's security to
6119 * make any last-minute changes to the packet */
6120 RXS_SendPacket(conn->securityObject, call, p);
6122 /* Since we're about to send SOME sort of packet to the peer, it's
6123 * safe to nuke any scheduled end-of-packets ack */
6124 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6126 /* Actually send the packet, filling in more connection-specific fields */
6127 MUTEX_EXIT(&call->lock);
6128 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6129 rxi_SendPacket(call, conn, p, istack);
6130 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6131 MUTEX_ENTER(&call->lock);
6133 /* Update last send time for this call (for keep-alive
6134 * processing), and for the connection (so that we can discover
6135 * idle connections) */
6136 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6137 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6138 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6140 conn->lastSendTime = call->lastSendTime = clock_Sec();
6141 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6142 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6143 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6144 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6145 RX_ACK_PING_RESPONSE)))
6146 call->lastSendData = call->lastSendTime;
6150 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6151 * that things are fine. Also called periodically to guarantee that nothing
6152 * falls through the cracks (e.g. (error + dally) connections have keepalive
6153 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6155 * haveCTLock Set if calling from rxi_ReapConnections
6157 #ifdef RX_ENABLE_LOCKS
6159 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6160 #else /* RX_ENABLE_LOCKS */
6162 rxi_CheckCall(struct rx_call *call)
6163 #endif /* RX_ENABLE_LOCKS */
6165 struct rx_connection *conn = call->conn;
6167 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6168 afs_uint32 fudgeFactor;
6171 int idle_timeout = 0;
6172 afs_int32 clock_diff = 0;
6176 /* Large swings in the clock can have a significant impact on
6177 * the performance of RX call processing. Forward clock shifts
6178 * will result in premature event triggering or timeouts.
6179 * Backward shifts can result in calls not completing until
6180 * the clock catches up with the original start clock value.
6182 * If a backward clock shift of more than five minutes is noticed,
6183 * just fail the call.
6185 if (now < call->lastSendTime)
6186 clock_diff = call->lastSendTime - now;
6187 if (now < call->startWait)
6188 clock_diff = MAX(clock_diff, call->startWait - now);
6189 if (now < call->lastReceiveTime)
6190 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6191 if (clock_diff > 5 * 60)
6193 if (call->state == RX_STATE_ACTIVE)
6194 rxi_CallError(call, RX_CALL_TIMEOUT);
6198 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6199 if (call->flags & RX_CALL_TQ_BUSY) {
6200 /* Call is active and will be reset by rxi_Start if it's
6201 * in an error state.
6206 /* RTT + 8*MDEV, rounded up to the next second. */
6207 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6208 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6210 deadTime = conn->secondsUntilDead + fudgeFactor;
6211 /* These are computed to the second (+- 1 second). But that's
6212 * good enough for these values, which should be a significant
6213 * number of seconds. */
6214 if (now > (call->lastReceiveTime + deadTime)) {
6215 if (call->state == RX_STATE_ACTIVE) {
6217 #if defined(KERNEL) && defined(AFS_SUN5_ENV)
6219 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6220 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6221 ip_stack_t *ipst = ns->netstack_ip;
6223 ire = ire_cache_lookup(conn->peer->host
6224 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6226 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6228 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6235 if (ire && ire->ire_max_frag > 0)
6236 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6238 #if defined(GLOBAL_NETSTACKID)
6242 #endif /* ADAPT_PMTU */
6243 cerror = RX_CALL_DEAD;
6246 #ifdef RX_ENABLE_LOCKS
6247 /* Cancel pending events */
6248 rxevent_Cancel(&call->delayedAckEvent, call,
6249 RX_CALL_REFCOUNT_DELAY);
6250 rxi_rto_cancel(call);
6251 rxevent_Cancel(&call->keepAliveEvent, call,
6252 RX_CALL_REFCOUNT_ALIVE);
6253 rxevent_Cancel(&call->growMTUEvent, call,
6254 RX_CALL_REFCOUNT_MTU);
6255 MUTEX_ENTER(&rx_refcnt_mutex);
6256 /* if rxi_FreeCall returns 1 it has freed the call */
6257 if (call->refCount == 0 &&
6258 rxi_FreeCall(call, haveCTLock))
6260 MUTEX_EXIT(&rx_refcnt_mutex);
6263 MUTEX_EXIT(&rx_refcnt_mutex);
6265 #else /* RX_ENABLE_LOCKS */
6266 rxi_FreeCall(call, 0);
6268 #endif /* RX_ENABLE_LOCKS */
6270 /* Non-active calls are destroyed if they are not responding
6271 * to pings; active calls are simply flagged in error, so the
6272 * attached process can die reasonably gracefully. */
6275 if (conn->idleDeadDetection) {
6276 if (conn->idleDeadTime) {
6277 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6281 /* see if we have a non-activity timeout */
6282 if (call->startWait && ((call->startWait + idleDeadTime) < now) &&
6283 (call->flags & RX_CALL_READER_WAIT)) {
6284 if (call->state == RX_STATE_ACTIVE) {
6285 cerror = RX_CALL_TIMEOUT;
6290 if (call->lastSendData && ((call->lastSendData + idleDeadTime) < now)) {
6291 if (call->state == RX_STATE_ACTIVE) {
6292 cerror = conn->service ? conn->service->idleDeadErr : RX_CALL_IDLE;
6300 if (conn->hardDeadTime) {
6301 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6304 /* see if we have a hard timeout */
6306 && (now > (hardDeadTime + call->startTime.sec))) {
6307 if (call->state == RX_STATE_ACTIVE)
6308 rxi_CallError(call, RX_CALL_TIMEOUT);
6313 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6314 call->lastReceiveTime) {
6315 int oldMTU = conn->peer->ifMTU;
6317 /* if we thought we could send more, perhaps things got worse */
6318 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6319 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6320 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6321 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6323 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6325 /* minimum capped in SetPeerMtu */
6326 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6329 conn->lastPacketSize = 0;
6331 /* needed so ResetCall doesn't clobber us. */
6332 call->MTU = conn->peer->ifMTU;
6334 /* if we never succeeded, let the error pass out as-is */
6335 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6336 cerror = conn->msgsizeRetryErr;
6339 rxi_CallError(call, cerror);
6344 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6345 void *dummy, int dummy2)
6347 struct rx_connection *conn = arg1;
6348 struct rx_header theader;
6349 char tbuffer[1 + sizeof(struct rx_header)];
6350 struct sockaddr_in taddr;
6353 struct iovec tmpiov[2];
6356 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6359 tp = &tbuffer[sizeof(struct rx_header)];
6360 taddr.sin_family = AF_INET;
6361 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6362 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6363 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6364 taddr.sin_len = sizeof(struct sockaddr_in);
6366 memset(&theader, 0, sizeof(theader));
6367 theader.epoch = htonl(999);
6369 theader.callNumber = 0;
6372 theader.type = RX_PACKET_TYPE_VERSION;
6373 theader.flags = RX_LAST_PACKET;
6374 theader.serviceId = 0;
6376 memcpy(tbuffer, &theader, sizeof(theader));
6377 memcpy(tp, &a, sizeof(a));
6378 tmpiov[0].iov_base = tbuffer;
6379 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6381 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6383 MUTEX_ENTER(&conn->conn_data_lock);
6384 MUTEX_ENTER(&rx_refcnt_mutex);
6385 /* Only reschedule ourselves if the connection would not be destroyed */
6386 if (conn->refCount <= 1) {
6387 rxevent_Put(conn->natKeepAliveEvent);
6388 conn->natKeepAliveEvent = NULL;
6389 MUTEX_EXIT(&rx_refcnt_mutex);
6390 MUTEX_EXIT(&conn->conn_data_lock);
6391 rx_DestroyConnection(conn); /* drop the reference for this */
6393 conn->refCount--; /* drop the reference for this */
6394 MUTEX_EXIT(&rx_refcnt_mutex);
6395 rxevent_Put(conn->natKeepAliveEvent);
6396 conn->natKeepAliveEvent = NULL;
6397 rxi_ScheduleNatKeepAliveEvent(conn);
6398 MUTEX_EXIT(&conn->conn_data_lock);
6403 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6405 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6406 struct clock when, now;
6407 clock_GetTime(&now);
6409 when.sec += conn->secondsUntilNatPing;
6410 MUTEX_ENTER(&rx_refcnt_mutex);
6411 conn->refCount++; /* hold a reference for this */
6412 MUTEX_EXIT(&rx_refcnt_mutex);
6413 conn->natKeepAliveEvent =
6414 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6419 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6421 MUTEX_ENTER(&conn->conn_data_lock);
6422 conn->secondsUntilNatPing = seconds;
6424 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6425 rxi_ScheduleNatKeepAliveEvent(conn);
6427 conn->flags |= RX_CONN_NAT_PING;
6429 MUTEX_EXIT(&conn->conn_data_lock);
6433 rxi_NatKeepAliveOn(struct rx_connection *conn)
6435 MUTEX_ENTER(&conn->conn_data_lock);
6436 /* if it's already attached */
6437 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6438 rxi_ScheduleNatKeepAliveEvent(conn);
6440 conn->flags |= RX_CONN_NAT_PING;
6441 MUTEX_EXIT(&conn->conn_data_lock);
6444 /* When a call is in progress, this routine is called occasionally to
6445 * make sure that some traffic has arrived (or been sent to) the peer.
6446 * If nothing has arrived in a reasonable amount of time, the call is
6447 * declared dead; if nothing has been sent for a while, we send a
6448 * keep-alive packet (if we're actually trying to keep the call alive)
6451 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6454 struct rx_call *call = arg1;
6455 struct rx_connection *conn;
6458 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6459 MUTEX_ENTER(&call->lock);
6461 if (event == call->keepAliveEvent) {
6462 rxevent_Put(call->keepAliveEvent);
6463 call->keepAliveEvent = NULL;
6468 #ifdef RX_ENABLE_LOCKS
6469 if (rxi_CheckCall(call, 0)) {
6470 MUTEX_EXIT(&call->lock);
6473 #else /* RX_ENABLE_LOCKS */
6474 if (rxi_CheckCall(call))
6476 #endif /* RX_ENABLE_LOCKS */
6478 /* Don't try to keep alive dallying calls */
6479 if (call->state == RX_STATE_DALLY) {
6480 MUTEX_EXIT(&call->lock);
6485 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6486 /* Don't try to send keepalives if there is unacknowledged data */
6487 /* the rexmit code should be good enough, this little hack
6488 * doesn't quite work XXX */
6489 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6491 rxi_ScheduleKeepAliveEvent(call);
6492 MUTEX_EXIT(&call->lock);
6495 /* Does what's on the nameplate. */
6497 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6499 struct rx_call *call = arg1;
6500 struct rx_connection *conn;
6502 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6503 MUTEX_ENTER(&call->lock);
6505 if (event == call->growMTUEvent) {
6506 rxevent_Put(call->growMTUEvent);
6507 call->growMTUEvent = NULL;
6510 #ifdef RX_ENABLE_LOCKS
6511 if (rxi_CheckCall(call, 0)) {
6512 MUTEX_EXIT(&call->lock);
6515 #else /* RX_ENABLE_LOCKS */
6516 if (rxi_CheckCall(call))
6518 #endif /* RX_ENABLE_LOCKS */
6520 /* Don't bother with dallying calls */
6521 if (call->state == RX_STATE_DALLY) {
6522 MUTEX_EXIT(&call->lock);
6529 * keep being scheduled, just don't do anything if we're at peak,
6530 * or we're not set up to be properly handled (idle timeout required)
6532 if ((conn->peer->maxPacketSize != 0) &&
6533 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6534 conn->idleDeadDetection)
6535 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6536 rxi_ScheduleGrowMTUEvent(call, 0);
6537 MUTEX_EXIT(&call->lock);
6541 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6543 if (!call->keepAliveEvent) {
6544 struct clock when, now;
6545 clock_GetTime(&now);
6547 when.sec += call->conn->secondsUntilPing;
6548 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6549 call->keepAliveEvent =
6550 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6555 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6557 if (!call->growMTUEvent) {
6558 struct clock when, now;
6560 clock_GetTime(&now);
6563 if (call->conn->secondsUntilPing)
6564 secs = (6*call->conn->secondsUntilPing)-1;
6566 if (call->conn->secondsUntilDead)
6567 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6571 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6572 call->growMTUEvent =
6573 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6577 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6579 rxi_KeepAliveOn(struct rx_call *call)
6581 /* Pretend last packet received was received now--i.e. if another
6582 * packet isn't received within the keep alive time, then the call
6583 * will die; Initialize last send time to the current time--even
6584 * if a packet hasn't been sent yet. This will guarantee that a
6585 * keep-alive is sent within the ping time */
6586 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6587 rxi_ScheduleKeepAliveEvent(call);
6591 * Solely in order that callers not need to include rx_call.h
6594 rx_KeepAliveOff(struct rx_call *call)
6596 rxi_KeepAliveOff(call);
6599 rx_KeepAliveOn(struct rx_call *call)
6601 rxi_KeepAliveOn(call);
6605 rxi_GrowMTUOn(struct rx_call *call)
6607 struct rx_connection *conn = call->conn;
6608 MUTEX_ENTER(&conn->conn_data_lock);
6609 conn->lastPingSizeSer = conn->lastPingSize = 0;
6610 MUTEX_EXIT(&conn->conn_data_lock);
6611 rxi_ScheduleGrowMTUEvent(call, 1);
6614 /* This routine is called to send connection abort messages
6615 * that have been delayed to throttle looping clients. */
6617 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6620 struct rx_connection *conn = arg1;
6623 struct rx_packet *packet;
6625 MUTEX_ENTER(&conn->conn_data_lock);
6626 rxevent_Put(conn->delayedAbortEvent);
6627 conn->delayedAbortEvent = NULL;
6628 error = htonl(conn->error);
6630 MUTEX_EXIT(&conn->conn_data_lock);
6631 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6634 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6635 RX_PACKET_TYPE_ABORT, (char *)&error,
6637 rxi_FreePacket(packet);
6641 /* This routine is called to send call abort messages
6642 * that have been delayed to throttle looping clients. */
6644 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6647 struct rx_call *call = arg1;
6650 struct rx_packet *packet;
6652 MUTEX_ENTER(&call->lock);
6653 rxevent_Put(call->delayedAbortEvent);
6654 call->delayedAbortEvent = NULL;
6655 error = htonl(call->error);
6657 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6660 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6661 (char *)&error, sizeof(error), 0);
6662 rxi_FreePacket(packet);
6664 MUTEX_EXIT(&call->lock);
6665 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6668 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6669 * seconds) to ask the client to authenticate itself. The routine
6670 * issues a challenge to the client, which is obtained from the
6671 * security object associated with the connection */
6673 rxi_ChallengeEvent(struct rxevent *event,
6674 void *arg0, void *arg1, int tries)
6676 struct rx_connection *conn = arg0;
6679 rxevent_Put(conn->challengeEvent);
6680 conn->challengeEvent = NULL;
6683 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6684 struct rx_packet *packet;
6685 struct clock when, now;
6688 /* We've failed to authenticate for too long.
6689 * Reset any calls waiting for authentication;
6690 * they are all in RX_STATE_PRECALL.
6694 MUTEX_ENTER(&conn->conn_call_lock);
6695 for (i = 0; i < RX_MAXCALLS; i++) {
6696 struct rx_call *call = conn->call[i];
6698 MUTEX_ENTER(&call->lock);
6699 if (call->state == RX_STATE_PRECALL) {
6700 rxi_CallError(call, RX_CALL_DEAD);
6701 rxi_SendCallAbort(call, NULL, 0, 0);
6703 MUTEX_EXIT(&call->lock);
6706 MUTEX_EXIT(&conn->conn_call_lock);
6710 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6712 /* If there's no packet available, do this later. */
6713 RXS_GetChallenge(conn->securityObject, conn, packet);
6714 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6715 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6716 rxi_FreePacket(packet);
6718 clock_GetTime(&now);
6720 when.sec += RX_CHALLENGE_TIMEOUT;
6721 conn->challengeEvent =
6722 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6727 /* Call this routine to start requesting the client to authenticate
6728 * itself. This will continue until authentication is established,
6729 * the call times out, or an invalid response is returned. The
6730 * security object associated with the connection is asked to create
6731 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6732 * defined earlier. */
6734 rxi_ChallengeOn(struct rx_connection *conn)
6736 if (!conn->challengeEvent) {
6737 RXS_CreateChallenge(conn->securityObject, conn);
6738 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6743 /* rxi_ComputeRoundTripTime is called with peer locked. */
6744 /* peer may be null */
6746 rxi_ComputeRoundTripTime(struct rx_packet *p,
6747 struct rx_ackPacket *ack,
6748 struct rx_call *call,
6749 struct rx_peer *peer,
6752 struct clock thisRtt, *sentp;
6756 /* If the ACK is delayed, then do nothing */
6757 if (ack->reason == RX_ACK_DELAY)
6760 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6761 * their RTT multiple times, so only include the RTT of the last packet
6763 if (p->flags & RX_JUMBO_PACKET)
6766 /* Use the serial number to determine which transmission the ACK is for,
6767 * and set the sent time to match this. If we have no serial number, then
6768 * only use the ACK for RTT calculations if the packet has not been
6772 serial = ntohl(ack->serial);
6774 if (serial == p->header.serial) {
6775 sentp = &p->timeSent;
6776 } else if (serial == p->firstSerial) {
6777 sentp = &p->firstSent;
6778 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6779 sentp = &p->firstSent;
6783 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6784 sentp = &p->firstSent;
6791 if (clock_Lt(&thisRtt, sentp))
6792 return; /* somebody set the clock back, don't count this time. */
6794 clock_Sub(&thisRtt, sentp);
6795 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6796 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6798 if (clock_IsZero(&thisRtt)) {
6800 * The actual round trip time is shorter than the
6801 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6802 * Since we can't tell which at the moment we will assume 1ms.
6804 thisRtt.usec = 1000;
6807 if (rx_stats_active) {
6808 MUTEX_ENTER(&rx_stats_mutex);
6809 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6810 rx_stats.minRtt = thisRtt;
6811 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6812 if (thisRtt.sec > 60) {
6813 MUTEX_EXIT(&rx_stats_mutex);
6814 return; /* somebody set the clock ahead */
6816 rx_stats.maxRtt = thisRtt;
6818 clock_Add(&rx_stats.totalRtt, &thisRtt);
6819 rx_atomic_inc(&rx_stats.nRttSamples);
6820 MUTEX_EXIT(&rx_stats_mutex);
6823 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6825 /* Apply VanJacobson round-trip estimations */
6830 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6831 * srtt is stored as fixed point with 3 bits after the binary
6832 * point (i.e., scaled by 8). The following magic is
6833 * equivalent to the smoothing algorithm in rfc793 with an
6834 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6835 * srtt'*8 = rtt + srtt*7
6836 * srtt'*8 = srtt*8 + rtt - srtt
6837 * srtt' = srtt + rtt/8 - srtt/8
6838 * srtt' = srtt + (rtt - srtt)/8
6841 delta = _8THMSEC(&thisRtt) - call->rtt;
6842 call->rtt += (delta >> 3);
6845 * We accumulate a smoothed rtt variance (actually, a smoothed
6846 * mean difference), then set the retransmit timer to smoothed
6847 * rtt + 4 times the smoothed variance (was 2x in van's original
6848 * paper, but 4x works better for me, and apparently for him as
6850 * rttvar is stored as
6851 * fixed point with 2 bits after the binary point (scaled by
6852 * 4). The following is equivalent to rfc793 smoothing with
6853 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6854 * rttvar'*4 = rttvar*3 + |delta|
6855 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6856 * rttvar' = rttvar + |delta|/4 - rttvar/4
6857 * rttvar' = rttvar + (|delta| - rttvar)/4
6858 * This replaces rfc793's wired-in beta.
6859 * dev*4 = dev*4 + (|actual - expected| - dev)
6865 delta -= (call->rtt_dev << 1);
6866 call->rtt_dev += (delta >> 3);
6868 /* I don't have a stored RTT so I start with this value. Since I'm
6869 * probably just starting a call, and will be pushing more data down
6870 * this, I expect congestion to increase rapidly. So I fudge a
6871 * little, and I set deviance to half the rtt. In practice,
6872 * deviance tends to approach something a little less than
6873 * half the smoothed rtt. */
6874 call->rtt = _8THMSEC(&thisRtt) + 8;
6875 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6877 /* the smoothed RTT time is RTT + 4*MDEV
6879 * We allow a user specified minimum to be set for this, to allow clamping
6880 * at a minimum value in the same way as TCP. In addition, we have to allow
6881 * for the possibility that this packet is answered by a delayed ACK, so we
6882 * add on a fixed 200ms to account for that timer expiring.
6885 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6886 rx_minPeerTimeout) + 200;
6887 clock_Zero(&call->rto);
6888 clock_Addmsec(&call->rto, rtt_timeout);
6890 /* Update the peer, so any new calls start with our values */
6891 peer->rtt_dev = call->rtt_dev;
6892 peer->rtt = call->rtt;
6894 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6895 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6899 /* Find all server connections that have not been active for a long time, and
6902 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6905 struct clock now, when;
6906 clock_GetTime(&now);
6908 /* Find server connection structures that haven't been used for
6909 * greater than rx_idleConnectionTime */
6911 struct rx_connection **conn_ptr, **conn_end;
6912 int i, havecalls = 0;
6913 MUTEX_ENTER(&rx_connHashTable_lock);
6914 for (conn_ptr = &rx_connHashTable[0], conn_end =
6915 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6917 struct rx_connection *conn, *next;
6918 struct rx_call *call;
6922 for (conn = *conn_ptr; conn; conn = next) {
6923 /* XXX -- Shouldn't the connection be locked? */
6926 for (i = 0; i < RX_MAXCALLS; i++) {
6927 call = conn->call[i];
6931 code = MUTEX_TRYENTER(&call->lock);
6934 #ifdef RX_ENABLE_LOCKS
6935 result = rxi_CheckCall(call, 1);
6936 #else /* RX_ENABLE_LOCKS */
6937 result = rxi_CheckCall(call);
6938 #endif /* RX_ENABLE_LOCKS */
6939 MUTEX_EXIT(&call->lock);
6941 /* If CheckCall freed the call, it might
6942 * have destroyed the connection as well,
6943 * which screws up the linked lists.
6949 if (conn->type == RX_SERVER_CONNECTION) {
6950 /* This only actually destroys the connection if
6951 * there are no outstanding calls */
6952 MUTEX_ENTER(&conn->conn_data_lock);
6953 MUTEX_ENTER(&rx_refcnt_mutex);
6954 if (!havecalls && !conn->refCount
6955 && ((conn->lastSendTime + rx_idleConnectionTime) <
6957 conn->refCount++; /* it will be decr in rx_DestroyConn */
6958 MUTEX_EXIT(&rx_refcnt_mutex);
6959 MUTEX_EXIT(&conn->conn_data_lock);
6960 #ifdef RX_ENABLE_LOCKS
6961 rxi_DestroyConnectionNoLock(conn);
6962 #else /* RX_ENABLE_LOCKS */
6963 rxi_DestroyConnection(conn);
6964 #endif /* RX_ENABLE_LOCKS */
6966 #ifdef RX_ENABLE_LOCKS
6968 MUTEX_EXIT(&rx_refcnt_mutex);
6969 MUTEX_EXIT(&conn->conn_data_lock);
6971 #endif /* RX_ENABLE_LOCKS */
6975 #ifdef RX_ENABLE_LOCKS
6976 while (rx_connCleanup_list) {
6977 struct rx_connection *conn;
6978 conn = rx_connCleanup_list;
6979 rx_connCleanup_list = rx_connCleanup_list->next;
6980 MUTEX_EXIT(&rx_connHashTable_lock);
6981 rxi_CleanupConnection(conn);
6982 MUTEX_ENTER(&rx_connHashTable_lock);
6984 MUTEX_EXIT(&rx_connHashTable_lock);
6985 #endif /* RX_ENABLE_LOCKS */
6988 /* Find any peer structures that haven't been used (haven't had an
6989 * associated connection) for greater than rx_idlePeerTime */
6991 struct rx_peer **peer_ptr, **peer_end;
6995 * Why do we need to hold the rx_peerHashTable_lock across
6996 * the incrementing of peer_ptr since the rx_peerHashTable
6997 * array is not changing? We don't.
6999 * By dropping the lock periodically we can permit other
7000 * activities to be performed while a rxi_ReapConnections
7001 * call is in progress. The goal of reap connections
7002 * is to clean up quickly without causing large amounts
7003 * of contention. Therefore, it is important that global
7004 * mutexes not be held for extended periods of time.
7006 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7007 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7009 struct rx_peer *peer, *next, *prev;
7011 MUTEX_ENTER(&rx_peerHashTable_lock);
7012 for (prev = peer = *peer_ptr; peer; peer = next) {
7014 code = MUTEX_TRYENTER(&peer->peer_lock);
7015 if ((code) && (peer->refCount == 0)
7016 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7017 rx_interface_stat_p rpc_stat, nrpc_stat;
7021 * now know that this peer object is one to be
7022 * removed from the hash table. Once it is removed
7023 * it can't be referenced by other threads.
7024 * Lets remove it first and decrement the struct
7025 * nPeerStructs count.
7027 if (peer == *peer_ptr) {
7033 if (rx_stats_active)
7034 rx_atomic_dec(&rx_stats.nPeerStructs);
7037 * Now if we hold references on 'prev' and 'next'
7038 * we can safely drop the rx_peerHashTable_lock
7039 * while we destroy this 'peer' object.
7045 MUTEX_EXIT(&rx_peerHashTable_lock);
7047 MUTEX_EXIT(&peer->peer_lock);
7048 MUTEX_DESTROY(&peer->peer_lock);
7050 (&peer->rpcStats, rpc_stat, nrpc_stat,
7051 rx_interface_stat)) {
7052 unsigned int num_funcs;
7055 queue_Remove(&rpc_stat->queue_header);
7056 queue_Remove(&rpc_stat->all_peers);
7057 num_funcs = rpc_stat->stats[0].func_total;
7059 sizeof(rx_interface_stat_t) +
7060 rpc_stat->stats[0].func_total *
7061 sizeof(rx_function_entry_v1_t);
7063 rxi_Free(rpc_stat, space);
7065 MUTEX_ENTER(&rx_rpc_stats);
7066 rxi_rpc_peer_stat_cnt -= num_funcs;
7067 MUTEX_EXIT(&rx_rpc_stats);
7072 * Regain the rx_peerHashTable_lock and
7073 * decrement the reference count on 'prev'
7076 MUTEX_ENTER(&rx_peerHashTable_lock);
7083 MUTEX_EXIT(&peer->peer_lock);
7088 MUTEX_EXIT(&rx_peerHashTable_lock);
7092 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7093 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7094 * GC, just below. Really, we shouldn't have to keep moving packets from
7095 * one place to another, but instead ought to always know if we can
7096 * afford to hold onto a packet in its particular use. */
7097 MUTEX_ENTER(&rx_freePktQ_lock);
7098 if (rx_waitingForPackets) {
7099 rx_waitingForPackets = 0;
7100 #ifdef RX_ENABLE_LOCKS
7101 CV_BROADCAST(&rx_waitingForPackets_cv);
7103 osi_rxWakeup(&rx_waitingForPackets);
7106 MUTEX_EXIT(&rx_freePktQ_lock);
7109 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7110 rxevent_Put(rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0));
7114 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7115 * rx.h is sort of strange this is better. This is called with a security
7116 * object before it is discarded. Each connection using a security object has
7117 * its own refcount to the object so it won't actually be freed until the last
7118 * connection is destroyed.
7120 * This is the only rxs module call. A hold could also be written but no one
7124 rxs_Release(struct rx_securityClass *aobj)
7126 return RXS_Close(aobj);
7134 #define TRACE_OPTION_RX_DEBUG 16
7142 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7143 0, KEY_QUERY_VALUE, &parmKey);
7144 if (code != ERROR_SUCCESS)
7147 dummyLen = sizeof(TraceOption);
7148 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7149 (BYTE *) &TraceOption, &dummyLen);
7150 if (code == ERROR_SUCCESS) {
7151 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7153 RegCloseKey (parmKey);
7154 #endif /* AFS_NT40_ENV */
7159 rx_DebugOnOff(int on)
7163 rxdebug_active = on;
7169 rx_StatsOnOff(int on)
7171 rx_stats_active = on;
7175 /* Don't call this debugging routine directly; use dpf */
7177 rxi_DebugPrint(char *format, ...)
7186 va_start(ap, format);
7188 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7191 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7193 OutputDebugString(msg);
7199 va_start(ap, format);
7201 clock_GetTime(&now);
7202 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7203 (unsigned int)now.usec);
7204 vfprintf(rx_Log, format, ap);
7212 * This function is used to process the rx_stats structure that is local
7213 * to a process as well as an rx_stats structure received from a remote
7214 * process (via rxdebug). Therefore, it needs to do minimal version
7218 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7219 afs_int32 freePackets, char version)
7223 if (size != sizeof(struct rx_statistics)) {
7225 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7226 size, sizeof(struct rx_statistics));
7229 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7232 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7233 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7234 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7235 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7236 s->specialPktAllocFailures);
7238 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7239 s->receivePktAllocFailures, s->sendPktAllocFailures,
7240 s->specialPktAllocFailures);
7244 " greedy %u, " "bogusReads %u (last from host %x), "
7245 "noPackets %u, " "noBuffers %u, " "selects %u, "
7246 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7247 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7248 s->selects, s->sendSelects);
7250 fprintf(file, " packets read: ");
7251 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7252 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7254 fprintf(file, "\n");
7257 " other read counters: data %u, " "ack %u, " "dup %u "
7258 "spurious %u " "dally %u\n", s->dataPacketsRead,
7259 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7260 s->ignorePacketDally);
7262 fprintf(file, " packets sent: ");
7263 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7264 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7266 fprintf(file, "\n");
7269 " other send counters: ack %u, " "data %u (not resends), "
7270 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7271 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7272 s->dataPacketsPushed, s->ignoreAckedPacket);
7275 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7276 s->netSendFailures, (int)s->fatalErrors);
7278 if (s->nRttSamples) {
7279 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7280 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7282 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7283 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7287 " %d server connections, " "%d client connections, "
7288 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7289 s->nServerConns, s->nClientConns, s->nPeerStructs,
7290 s->nCallStructs, s->nFreeCallStructs);
7292 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7293 fprintf(file, " %d clock updates\n", clock_nUpdates);
7297 /* for backward compatibility */
7299 rx_PrintStats(FILE * file)
7301 MUTEX_ENTER(&rx_stats_mutex);
7302 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7303 sizeof(rx_stats), rx_nFreePackets,
7305 MUTEX_EXIT(&rx_stats_mutex);
7309 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7311 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7312 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7313 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7316 " Rtt %d, " "total sent %d, " "resent %d\n",
7317 peer->rtt, peer->nSent, peer->reSends);
7320 " Packet size %d, " "max in packet skew %d, "
7321 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7322 (int)peer->outPacketSkew);
7326 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7328 * This mutex protects the following static variables:
7332 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7333 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7335 #define LOCK_RX_DEBUG
7336 #define UNLOCK_RX_DEBUG
7337 #endif /* AFS_PTHREAD_ENV */
7339 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7341 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7342 u_char type, void *inputData, size_t inputLength,
7343 void *outputData, size_t outputLength)
7345 static afs_int32 counter = 100;
7346 time_t waitTime, waitCount;
7347 struct rx_header theader;
7350 struct timeval tv_now, tv_wake, tv_delta;
7351 struct sockaddr_in taddr, faddr;
7365 tp = &tbuffer[sizeof(struct rx_header)];
7366 taddr.sin_family = AF_INET;
7367 taddr.sin_port = remotePort;
7368 taddr.sin_addr.s_addr = remoteAddr;
7369 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7370 taddr.sin_len = sizeof(struct sockaddr_in);
7373 memset(&theader, 0, sizeof(theader));
7374 theader.epoch = htonl(999);
7376 theader.callNumber = htonl(counter);
7379 theader.type = type;
7380 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7381 theader.serviceId = 0;
7383 memcpy(tbuffer, &theader, sizeof(theader));
7384 memcpy(tp, inputData, inputLength);
7386 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7387 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7389 /* see if there's a packet available */
7390 gettimeofday(&tv_wake, NULL);
7391 tv_wake.tv_sec += waitTime;
7394 FD_SET(socket, &imask);
7395 tv_delta.tv_sec = tv_wake.tv_sec;
7396 tv_delta.tv_usec = tv_wake.tv_usec;
7397 gettimeofday(&tv_now, NULL);
7399 if (tv_delta.tv_usec < tv_now.tv_usec) {
7401 tv_delta.tv_usec += 1000000;
7404 tv_delta.tv_usec -= tv_now.tv_usec;
7406 if (tv_delta.tv_sec < tv_now.tv_sec) {
7410 tv_delta.tv_sec -= tv_now.tv_sec;
7413 code = select(0, &imask, 0, 0, &tv_delta);
7414 #else /* AFS_NT40_ENV */
7415 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7416 #endif /* AFS_NT40_ENV */
7417 if (code == 1 && FD_ISSET(socket, &imask)) {
7418 /* now receive a packet */
7419 faddrLen = sizeof(struct sockaddr_in);
7421 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7422 (struct sockaddr *)&faddr, &faddrLen);
7425 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7426 if (counter == ntohl(theader.callNumber))
7434 /* see if we've timed out */
7442 code -= sizeof(struct rx_header);
7443 if (code > outputLength)
7444 code = outputLength;
7445 memcpy(outputData, tp, code);
7448 #endif /* RXDEBUG */
7451 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7452 afs_uint16 remotePort, struct rx_debugStats * stat,
7453 afs_uint32 * supportedValues)
7455 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7457 struct rx_debugIn in;
7459 *supportedValues = 0;
7460 in.type = htonl(RX_DEBUGI_GETSTATS);
7463 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7464 &in, sizeof(in), stat, sizeof(*stat));
7467 * If the call was successful, fixup the version and indicate
7468 * what contents of the stat structure are valid.
7469 * Also do net to host conversion of fields here.
7473 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7474 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7476 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7477 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7479 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7480 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7482 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7483 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7485 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7486 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7488 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7489 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7491 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7492 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7494 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7495 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7497 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7498 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7500 stat->nFreePackets = ntohl(stat->nFreePackets);
7501 stat->packetReclaims = ntohl(stat->packetReclaims);
7502 stat->callsExecuted = ntohl(stat->callsExecuted);
7503 stat->nWaiting = ntohl(stat->nWaiting);
7504 stat->idleThreads = ntohl(stat->idleThreads);
7505 stat->nWaited = ntohl(stat->nWaited);
7506 stat->nPackets = ntohl(stat->nPackets);
7515 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7516 afs_uint16 remotePort, struct rx_statistics * stat,
7517 afs_uint32 * supportedValues)
7519 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7521 struct rx_debugIn in;
7522 afs_int32 *lp = (afs_int32 *) stat;
7526 * supportedValues is currently unused, but added to allow future
7527 * versioning of this function.
7530 *supportedValues = 0;
7531 in.type = htonl(RX_DEBUGI_RXSTATS);
7533 memset(stat, 0, sizeof(*stat));
7535 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7536 &in, sizeof(in), stat, sizeof(*stat));
7541 * Do net to host conversion here
7544 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7555 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7556 afs_uint16 remotePort, size_t version_length,
7559 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7561 return MakeDebugCall(socket, remoteAddr, remotePort,
7562 RX_PACKET_TYPE_VERSION, a, 1, version,
7570 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7571 afs_uint16 remotePort, afs_int32 * nextConnection,
7572 int allConnections, afs_uint32 debugSupportedValues,
7573 struct rx_debugConn * conn,
7574 afs_uint32 * supportedValues)
7576 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7578 struct rx_debugIn in;
7582 * supportedValues is currently unused, but added to allow future
7583 * versioning of this function.
7586 *supportedValues = 0;
7587 if (allConnections) {
7588 in.type = htonl(RX_DEBUGI_GETALLCONN);
7590 in.type = htonl(RX_DEBUGI_GETCONN);
7592 in.index = htonl(*nextConnection);
7593 memset(conn, 0, sizeof(*conn));
7595 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7596 &in, sizeof(in), conn, sizeof(*conn));
7599 *nextConnection += 1;
7602 * Convert old connection format to new structure.
7605 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7606 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7607 #define MOVEvL(a) (conn->a = vL->a)
7609 /* any old or unrecognized version... */
7610 for (i = 0; i < RX_MAXCALLS; i++) {
7611 MOVEvL(callState[i]);
7612 MOVEvL(callMode[i]);
7613 MOVEvL(callFlags[i]);
7614 MOVEvL(callOther[i]);
7616 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7617 MOVEvL(secStats.type);
7618 MOVEvL(secStats.level);
7619 MOVEvL(secStats.flags);
7620 MOVEvL(secStats.expires);
7621 MOVEvL(secStats.packetsReceived);
7622 MOVEvL(secStats.packetsSent);
7623 MOVEvL(secStats.bytesReceived);
7624 MOVEvL(secStats.bytesSent);
7629 * Do net to host conversion here
7631 * I don't convert host or port since we are most likely
7632 * going to want these in NBO.
7634 conn->cid = ntohl(conn->cid);
7635 conn->serial = ntohl(conn->serial);
7636 for (i = 0; i < RX_MAXCALLS; i++) {
7637 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7639 conn->error = ntohl(conn->error);
7640 conn->secStats.flags = ntohl(conn->secStats.flags);
7641 conn->secStats.expires = ntohl(conn->secStats.expires);
7642 conn->secStats.packetsReceived =
7643 ntohl(conn->secStats.packetsReceived);
7644 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7645 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7646 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7647 conn->epoch = ntohl(conn->epoch);
7648 conn->natMTU = ntohl(conn->natMTU);
7657 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7658 afs_uint16 remotePort, afs_int32 * nextPeer,
7659 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7660 afs_uint32 * supportedValues)
7662 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7664 struct rx_debugIn in;
7667 * supportedValues is currently unused, but added to allow future
7668 * versioning of this function.
7671 *supportedValues = 0;
7672 in.type = htonl(RX_DEBUGI_GETPEER);
7673 in.index = htonl(*nextPeer);
7674 memset(peer, 0, sizeof(*peer));
7676 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7677 &in, sizeof(in), peer, sizeof(*peer));
7683 * Do net to host conversion here
7685 * I don't convert host or port since we are most likely
7686 * going to want these in NBO.
7688 peer->ifMTU = ntohs(peer->ifMTU);
7689 peer->idleWhen = ntohl(peer->idleWhen);
7690 peer->refCount = ntohs(peer->refCount);
7691 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7692 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7693 peer->rtt = ntohl(peer->rtt);
7694 peer->rtt_dev = ntohl(peer->rtt_dev);
7695 peer->timeout.sec = 0;
7696 peer->timeout.usec = 0;
7697 peer->nSent = ntohl(peer->nSent);
7698 peer->reSends = ntohl(peer->reSends);
7699 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7700 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7701 peer->natMTU = ntohs(peer->natMTU);
7702 peer->maxMTU = ntohs(peer->maxMTU);
7703 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7704 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7705 peer->MTU = ntohs(peer->MTU);
7706 peer->cwind = ntohs(peer->cwind);
7707 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7708 peer->congestSeq = ntohs(peer->congestSeq);
7709 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7710 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7711 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7712 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7721 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7722 struct rx_debugPeer * peerStats)
7725 afs_int32 error = 1; /* default to "did not succeed" */
7726 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7728 MUTEX_ENTER(&rx_peerHashTable_lock);
7729 for(tp = rx_peerHashTable[hashValue];
7730 tp != NULL; tp = tp->next) {
7731 if (tp->host == peerHost)
7737 MUTEX_EXIT(&rx_peerHashTable_lock);
7741 MUTEX_ENTER(&tp->peer_lock);
7742 peerStats->host = tp->host;
7743 peerStats->port = tp->port;
7744 peerStats->ifMTU = tp->ifMTU;
7745 peerStats->idleWhen = tp->idleWhen;
7746 peerStats->refCount = tp->refCount;
7747 peerStats->burstSize = tp->burstSize;
7748 peerStats->burst = tp->burst;
7749 peerStats->burstWait.sec = tp->burstWait.sec;
7750 peerStats->burstWait.usec = tp->burstWait.usec;
7751 peerStats->rtt = tp->rtt;
7752 peerStats->rtt_dev = tp->rtt_dev;
7753 peerStats->timeout.sec = 0;
7754 peerStats->timeout.usec = 0;
7755 peerStats->nSent = tp->nSent;
7756 peerStats->reSends = tp->reSends;
7757 peerStats->inPacketSkew = tp->inPacketSkew;
7758 peerStats->outPacketSkew = tp->outPacketSkew;
7759 peerStats->natMTU = tp->natMTU;
7760 peerStats->maxMTU = tp->maxMTU;
7761 peerStats->maxDgramPackets = tp->maxDgramPackets;
7762 peerStats->ifDgramPackets = tp->ifDgramPackets;
7763 peerStats->MTU = tp->MTU;
7764 peerStats->cwind = tp->cwind;
7765 peerStats->nDgramPackets = tp->nDgramPackets;
7766 peerStats->congestSeq = tp->congestSeq;
7767 peerStats->bytesSent.high = tp->bytesSent.high;
7768 peerStats->bytesSent.low = tp->bytesSent.low;
7769 peerStats->bytesReceived.high = tp->bytesReceived.high;
7770 peerStats->bytesReceived.low = tp->bytesReceived.low;
7771 MUTEX_EXIT(&tp->peer_lock);
7773 MUTEX_ENTER(&rx_peerHashTable_lock);
7776 MUTEX_EXIT(&rx_peerHashTable_lock);
7784 struct rx_serverQueueEntry *np;
7787 struct rx_call *call;
7788 struct rx_serverQueueEntry *sq;
7792 if (rxinit_status == 1) {
7794 return; /* Already shutdown. */
7798 #ifndef AFS_PTHREAD_ENV
7799 FD_ZERO(&rx_selectMask);
7800 #endif /* AFS_PTHREAD_ENV */
7801 rxi_dataQuota = RX_MAX_QUOTA;
7802 #ifndef AFS_PTHREAD_ENV
7804 #endif /* AFS_PTHREAD_ENV */
7807 #ifndef AFS_PTHREAD_ENV
7808 #ifndef AFS_USE_GETTIMEOFDAY
7810 #endif /* AFS_USE_GETTIMEOFDAY */
7811 #endif /* AFS_PTHREAD_ENV */
7813 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7814 call = queue_First(&rx_freeCallQueue, rx_call);
7816 rxi_Free(call, sizeof(struct rx_call));
7819 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7820 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7826 struct rx_peer **peer_ptr, **peer_end;
7827 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7828 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7830 struct rx_peer *peer, *next;
7832 MUTEX_ENTER(&rx_peerHashTable_lock);
7833 for (peer = *peer_ptr; peer; peer = next) {
7834 rx_interface_stat_p rpc_stat, nrpc_stat;
7837 MUTEX_ENTER(&rx_rpc_stats);
7838 MUTEX_ENTER(&peer->peer_lock);
7840 (&peer->rpcStats, rpc_stat, nrpc_stat,
7841 rx_interface_stat)) {
7842 unsigned int num_funcs;
7845 queue_Remove(&rpc_stat->queue_header);
7846 queue_Remove(&rpc_stat->all_peers);
7847 num_funcs = rpc_stat->stats[0].func_total;
7849 sizeof(rx_interface_stat_t) +
7850 rpc_stat->stats[0].func_total *
7851 sizeof(rx_function_entry_v1_t);
7853 rxi_Free(rpc_stat, space);
7855 /* rx_rpc_stats must be held */
7856 rxi_rpc_peer_stat_cnt -= num_funcs;
7858 MUTEX_EXIT(&peer->peer_lock);
7859 MUTEX_EXIT(&rx_rpc_stats);
7863 if (rx_stats_active)
7864 rx_atomic_dec(&rx_stats.nPeerStructs);
7866 MUTEX_EXIT(&rx_peerHashTable_lock);
7869 for (i = 0; i < RX_MAX_SERVICES; i++) {
7871 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7873 for (i = 0; i < rx_hashTableSize; i++) {
7874 struct rx_connection *tc, *ntc;
7875 MUTEX_ENTER(&rx_connHashTable_lock);
7876 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7878 for (j = 0; j < RX_MAXCALLS; j++) {
7880 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7883 rxi_Free(tc, sizeof(*tc));
7885 MUTEX_EXIT(&rx_connHashTable_lock);
7888 MUTEX_ENTER(&freeSQEList_lock);
7890 while ((np = rx_FreeSQEList)) {
7891 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7892 MUTEX_DESTROY(&np->lock);
7893 rxi_Free(np, sizeof(*np));
7896 MUTEX_EXIT(&freeSQEList_lock);
7897 MUTEX_DESTROY(&freeSQEList_lock);
7898 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7899 MUTEX_DESTROY(&rx_connHashTable_lock);
7900 MUTEX_DESTROY(&rx_peerHashTable_lock);
7901 MUTEX_DESTROY(&rx_serverPool_lock);
7903 osi_Free(rx_connHashTable,
7904 rx_hashTableSize * sizeof(struct rx_connection *));
7905 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7907 UNPIN(rx_connHashTable,
7908 rx_hashTableSize * sizeof(struct rx_connection *));
7909 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7911 rxi_FreeAllPackets();
7913 MUTEX_ENTER(&rx_quota_mutex);
7914 rxi_dataQuota = RX_MAX_QUOTA;
7915 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7916 MUTEX_EXIT(&rx_quota_mutex);
7921 #ifdef RX_ENABLE_LOCKS
7923 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7925 if (!MUTEX_ISMINE(lockaddr))
7926 osi_Panic("Lock not held: %s", msg);
7928 #endif /* RX_ENABLE_LOCKS */
7933 * Routines to implement connection specific data.
7937 rx_KeyCreate(rx_destructor_t rtn)
7940 MUTEX_ENTER(&rxi_keyCreate_lock);
7941 key = rxi_keyCreate_counter++;
7942 rxi_keyCreate_destructor = (rx_destructor_t *)
7943 realloc((void *)rxi_keyCreate_destructor,
7944 (key + 1) * sizeof(rx_destructor_t));
7945 rxi_keyCreate_destructor[key] = rtn;
7946 MUTEX_EXIT(&rxi_keyCreate_lock);
7951 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7954 MUTEX_ENTER(&conn->conn_data_lock);
7955 if (!conn->specific) {
7956 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7957 for (i = 0; i < key; i++)
7958 conn->specific[i] = NULL;
7959 conn->nSpecific = key + 1;
7960 conn->specific[key] = ptr;
7961 } else if (key >= conn->nSpecific) {
7962 conn->specific = (void **)
7963 realloc(conn->specific, (key + 1) * sizeof(void *));
7964 for (i = conn->nSpecific; i < key; i++)
7965 conn->specific[i] = NULL;
7966 conn->nSpecific = key + 1;
7967 conn->specific[key] = ptr;
7969 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7970 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7971 conn->specific[key] = ptr;
7973 MUTEX_EXIT(&conn->conn_data_lock);
7977 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7980 MUTEX_ENTER(&svc->svc_data_lock);
7981 if (!svc->specific) {
7982 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7983 for (i = 0; i < key; i++)
7984 svc->specific[i] = NULL;
7985 svc->nSpecific = key + 1;
7986 svc->specific[key] = ptr;
7987 } else if (key >= svc->nSpecific) {
7988 svc->specific = (void **)
7989 realloc(svc->specific, (key + 1) * sizeof(void *));
7990 for (i = svc->nSpecific; i < key; i++)
7991 svc->specific[i] = NULL;
7992 svc->nSpecific = key + 1;
7993 svc->specific[key] = ptr;
7995 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7996 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7997 svc->specific[key] = ptr;
7999 MUTEX_EXIT(&svc->svc_data_lock);
8003 rx_GetSpecific(struct rx_connection *conn, int key)
8006 MUTEX_ENTER(&conn->conn_data_lock);
8007 if (key >= conn->nSpecific)
8010 ptr = conn->specific[key];
8011 MUTEX_EXIT(&conn->conn_data_lock);
8016 rx_GetServiceSpecific(struct rx_service *svc, int key)
8019 MUTEX_ENTER(&svc->svc_data_lock);
8020 if (key >= svc->nSpecific)
8023 ptr = svc->specific[key];
8024 MUTEX_EXIT(&svc->svc_data_lock);
8029 #endif /* !KERNEL */
8032 * processStats is a queue used to store the statistics for the local
8033 * process. Its contents are similar to the contents of the rpcStats
8034 * queue on a rx_peer structure, but the actual data stored within
8035 * this queue contains totals across the lifetime of the process (assuming
8036 * the stats have not been reset) - unlike the per peer structures
8037 * which can come and go based upon the peer lifetime.
8040 static struct rx_queue processStats = { &processStats, &processStats };
8043 * peerStats is a queue used to store the statistics for all peer structs.
8044 * Its contents are the union of all the peer rpcStats queues.
8047 static struct rx_queue peerStats = { &peerStats, &peerStats };
8050 * rxi_monitor_processStats is used to turn process wide stat collection
8054 static int rxi_monitor_processStats = 0;
8057 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8060 static int rxi_monitor_peerStats = 0;
8063 * rxi_AddRpcStat - given all of the information for a particular rpc
8064 * call, create (if needed) and update the stat totals for the rpc.
8068 * IN stats - the queue of stats that will be updated with the new value
8070 * IN rxInterface - a unique number that identifies the rpc interface
8072 * IN currentFunc - the index of the function being invoked
8074 * IN totalFunc - the total number of functions in this interface
8076 * IN queueTime - the amount of time this function waited for a thread
8078 * IN execTime - the amount of time this function invocation took to execute
8080 * IN bytesSent - the number bytes sent by this invocation
8082 * IN bytesRcvd - the number bytes received by this invocation
8084 * IN isServer - if true, this invocation was made to a server
8086 * IN remoteHost - the ip address of the remote host
8088 * IN remotePort - the port of the remote host
8090 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8092 * INOUT counter - if a new stats structure is allocated, the counter will
8093 * be updated with the new number of allocated stat structures
8101 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8102 afs_uint32 currentFunc, afs_uint32 totalFunc,
8103 struct clock *queueTime, struct clock *execTime,
8104 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8105 afs_uint32 remoteHost, afs_uint32 remotePort,
8106 int addToPeerList, unsigned int *counter)
8109 rx_interface_stat_p rpc_stat, nrpc_stat;
8112 * See if there's already a structure for this interface
8115 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8116 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8117 && (rpc_stat->stats[0].remote_is_server == isServer))
8122 * Didn't find a match so allocate a new structure and add it to the
8126 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8127 || (rpc_stat->stats[0].interfaceId != rxInterface)
8128 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8133 sizeof(rx_interface_stat_t) +
8134 totalFunc * sizeof(rx_function_entry_v1_t);
8136 rpc_stat = rxi_Alloc(space);
8137 if (rpc_stat == NULL) {
8141 *counter += totalFunc;
8142 for (i = 0; i < totalFunc; i++) {
8143 rpc_stat->stats[i].remote_peer = remoteHost;
8144 rpc_stat->stats[i].remote_port = remotePort;
8145 rpc_stat->stats[i].remote_is_server = isServer;
8146 rpc_stat->stats[i].interfaceId = rxInterface;
8147 rpc_stat->stats[i].func_total = totalFunc;
8148 rpc_stat->stats[i].func_index = i;
8149 hzero(rpc_stat->stats[i].invocations);
8150 hzero(rpc_stat->stats[i].bytes_sent);
8151 hzero(rpc_stat->stats[i].bytes_rcvd);
8152 rpc_stat->stats[i].queue_time_sum.sec = 0;
8153 rpc_stat->stats[i].queue_time_sum.usec = 0;
8154 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8155 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8156 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8157 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8158 rpc_stat->stats[i].queue_time_max.sec = 0;
8159 rpc_stat->stats[i].queue_time_max.usec = 0;
8160 rpc_stat->stats[i].execution_time_sum.sec = 0;
8161 rpc_stat->stats[i].execution_time_sum.usec = 0;
8162 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8163 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8164 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8165 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8166 rpc_stat->stats[i].execution_time_max.sec = 0;
8167 rpc_stat->stats[i].execution_time_max.usec = 0;
8169 queue_Prepend(stats, rpc_stat);
8170 if (addToPeerList) {
8171 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8176 * Increment the stats for this function
8179 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8180 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8181 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8182 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8183 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8184 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8185 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8187 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8188 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8190 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8191 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8193 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8194 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8196 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8197 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8205 * rx_IncrementTimeAndCount - increment the times and count for a particular
8210 * IN peer - the peer who invoked the rpc
8212 * IN rxInterface - a unique number that identifies the rpc interface
8214 * IN currentFunc - the index of the function being invoked
8216 * IN totalFunc - the total number of functions in this interface
8218 * IN queueTime - the amount of time this function waited for a thread
8220 * IN execTime - the amount of time this function invocation took to execute
8222 * IN bytesSent - the number bytes sent by this invocation
8224 * IN bytesRcvd - the number bytes received by this invocation
8226 * IN isServer - if true, this invocation was made to a server
8234 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8235 afs_uint32 currentFunc, afs_uint32 totalFunc,
8236 struct clock *queueTime, struct clock *execTime,
8237 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8241 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8244 MUTEX_ENTER(&rx_rpc_stats);
8246 if (rxi_monitor_peerStats) {
8247 MUTEX_ENTER(&peer->peer_lock);
8248 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8249 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8250 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8251 MUTEX_EXIT(&peer->peer_lock);
8254 if (rxi_monitor_processStats) {
8255 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8256 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8257 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8260 MUTEX_EXIT(&rx_rpc_stats);
8265 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8269 * IN callerVersion - the rpc stat version of the caller.
8271 * IN count - the number of entries to marshall.
8273 * IN stats - pointer to stats to be marshalled.
8275 * OUT ptr - Where to store the marshalled data.
8282 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8283 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8289 * We only support the first version
8291 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8292 *(ptr++) = stats->remote_peer;
8293 *(ptr++) = stats->remote_port;
8294 *(ptr++) = stats->remote_is_server;
8295 *(ptr++) = stats->interfaceId;
8296 *(ptr++) = stats->func_total;
8297 *(ptr++) = stats->func_index;
8298 *(ptr++) = hgethi(stats->invocations);
8299 *(ptr++) = hgetlo(stats->invocations);
8300 *(ptr++) = hgethi(stats->bytes_sent);
8301 *(ptr++) = hgetlo(stats->bytes_sent);
8302 *(ptr++) = hgethi(stats->bytes_rcvd);
8303 *(ptr++) = hgetlo(stats->bytes_rcvd);
8304 *(ptr++) = stats->queue_time_sum.sec;
8305 *(ptr++) = stats->queue_time_sum.usec;
8306 *(ptr++) = stats->queue_time_sum_sqr.sec;
8307 *(ptr++) = stats->queue_time_sum_sqr.usec;
8308 *(ptr++) = stats->queue_time_min.sec;
8309 *(ptr++) = stats->queue_time_min.usec;
8310 *(ptr++) = stats->queue_time_max.sec;
8311 *(ptr++) = stats->queue_time_max.usec;
8312 *(ptr++) = stats->execution_time_sum.sec;
8313 *(ptr++) = stats->execution_time_sum.usec;
8314 *(ptr++) = stats->execution_time_sum_sqr.sec;
8315 *(ptr++) = stats->execution_time_sum_sqr.usec;
8316 *(ptr++) = stats->execution_time_min.sec;
8317 *(ptr++) = stats->execution_time_min.usec;
8318 *(ptr++) = stats->execution_time_max.sec;
8319 *(ptr++) = stats->execution_time_max.usec;
8325 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8330 * IN callerVersion - the rpc stat version of the caller
8332 * OUT myVersion - the rpc stat version of this function
8334 * OUT clock_sec - local time seconds
8336 * OUT clock_usec - local time microseconds
8338 * OUT allocSize - the number of bytes allocated to contain stats
8340 * OUT statCount - the number stats retrieved from this process.
8342 * OUT stats - the actual stats retrieved from this process.
8346 * Returns void. If successful, stats will != NULL.
8350 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8351 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8352 size_t * allocSize, afs_uint32 * statCount,
8353 afs_uint32 ** stats)
8363 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8366 * Check to see if stats are enabled
8369 MUTEX_ENTER(&rx_rpc_stats);
8370 if (!rxi_monitor_processStats) {
8371 MUTEX_EXIT(&rx_rpc_stats);
8375 clock_GetTime(&now);
8376 *clock_sec = now.sec;
8377 *clock_usec = now.usec;
8380 * Allocate the space based upon the caller version
8382 * If the client is at an older version than we are,
8383 * we return the statistic data in the older data format, but
8384 * we still return our version number so the client knows we
8385 * are maintaining more data than it can retrieve.
8388 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8389 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8390 *statCount = rxi_rpc_process_stat_cnt;
8393 * This can't happen yet, but in the future version changes
8394 * can be handled by adding additional code here
8398 if (space > (size_t) 0) {
8400 ptr = *stats = rxi_Alloc(space);
8403 rx_interface_stat_p rpc_stat, nrpc_stat;
8407 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8409 * Copy the data based upon the caller version
8411 rx_MarshallProcessRPCStats(callerVersion,
8412 rpc_stat->stats[0].func_total,
8413 rpc_stat->stats, &ptr);
8419 MUTEX_EXIT(&rx_rpc_stats);
8424 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8428 * IN callerVersion - the rpc stat version of the caller
8430 * OUT myVersion - the rpc stat version of this function
8432 * OUT clock_sec - local time seconds
8434 * OUT clock_usec - local time microseconds
8436 * OUT allocSize - the number of bytes allocated to contain stats
8438 * OUT statCount - the number of stats retrieved from the individual
8441 * OUT stats - the actual stats retrieved from the individual peer structures.
8445 * Returns void. If successful, stats will != NULL.
8449 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8450 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8451 size_t * allocSize, afs_uint32 * statCount,
8452 afs_uint32 ** stats)
8462 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8465 * Check to see if stats are enabled
8468 MUTEX_ENTER(&rx_rpc_stats);
8469 if (!rxi_monitor_peerStats) {
8470 MUTEX_EXIT(&rx_rpc_stats);
8474 clock_GetTime(&now);
8475 *clock_sec = now.sec;
8476 *clock_usec = now.usec;
8479 * Allocate the space based upon the caller version
8481 * If the client is at an older version than we are,
8482 * we return the statistic data in the older data format, but
8483 * we still return our version number so the client knows we
8484 * are maintaining more data than it can retrieve.
8487 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8488 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8489 *statCount = rxi_rpc_peer_stat_cnt;
8492 * This can't happen yet, but in the future version changes
8493 * can be handled by adding additional code here
8497 if (space > (size_t) 0) {
8499 ptr = *stats = rxi_Alloc(space);
8502 rx_interface_stat_p rpc_stat, nrpc_stat;
8506 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8508 * We have to fix the offset of rpc_stat since we are
8509 * keeping this structure on two rx_queues. The rx_queue
8510 * package assumes that the rx_queue member is the first
8511 * member of the structure. That is, rx_queue assumes that
8512 * any one item is only on one queue at a time. We are
8513 * breaking that assumption and so we have to do a little
8514 * math to fix our pointers.
8517 fix_offset = (char *)rpc_stat;
8518 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8519 rpc_stat = (rx_interface_stat_p) fix_offset;
8522 * Copy the data based upon the caller version
8524 rx_MarshallProcessRPCStats(callerVersion,
8525 rpc_stat->stats[0].func_total,
8526 rpc_stat->stats, &ptr);
8532 MUTEX_EXIT(&rx_rpc_stats);
8537 * rx_FreeRPCStats - free memory allocated by
8538 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8542 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8543 * rx_RetrievePeerRPCStats
8545 * IN allocSize - the number of bytes in stats.
8553 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8555 rxi_Free(stats, allocSize);
8559 * rx_queryProcessRPCStats - see if process rpc stat collection is
8560 * currently enabled.
8566 * Returns 0 if stats are not enabled != 0 otherwise
8570 rx_queryProcessRPCStats(void)
8573 MUTEX_ENTER(&rx_rpc_stats);
8574 rc = rxi_monitor_processStats;
8575 MUTEX_EXIT(&rx_rpc_stats);
8580 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8586 * Returns 0 if stats are not enabled != 0 otherwise
8590 rx_queryPeerRPCStats(void)
8593 MUTEX_ENTER(&rx_rpc_stats);
8594 rc = rxi_monitor_peerStats;
8595 MUTEX_EXIT(&rx_rpc_stats);
8600 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8610 rx_enableProcessRPCStats(void)
8612 MUTEX_ENTER(&rx_rpc_stats);
8613 rx_enable_stats = 1;
8614 rxi_monitor_processStats = 1;
8615 MUTEX_EXIT(&rx_rpc_stats);
8619 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8629 rx_enablePeerRPCStats(void)
8631 MUTEX_ENTER(&rx_rpc_stats);
8632 rx_enable_stats = 1;
8633 rxi_monitor_peerStats = 1;
8634 MUTEX_EXIT(&rx_rpc_stats);
8638 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8648 rx_disableProcessRPCStats(void)
8650 rx_interface_stat_p rpc_stat, nrpc_stat;
8653 MUTEX_ENTER(&rx_rpc_stats);
8656 * Turn off process statistics and if peer stats is also off, turn
8660 rxi_monitor_processStats = 0;
8661 if (rxi_monitor_peerStats == 0) {
8662 rx_enable_stats = 0;
8665 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8666 unsigned int num_funcs = 0;
8669 queue_Remove(rpc_stat);
8670 num_funcs = rpc_stat->stats[0].func_total;
8672 sizeof(rx_interface_stat_t) +
8673 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8675 rxi_Free(rpc_stat, space);
8676 rxi_rpc_process_stat_cnt -= num_funcs;
8678 MUTEX_EXIT(&rx_rpc_stats);
8682 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8692 rx_disablePeerRPCStats(void)
8694 struct rx_peer **peer_ptr, **peer_end;
8698 * Turn off peer statistics and if process stats is also off, turn
8702 rxi_monitor_peerStats = 0;
8703 if (rxi_monitor_processStats == 0) {
8704 rx_enable_stats = 0;
8707 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8708 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8710 struct rx_peer *peer, *next, *prev;
8712 MUTEX_ENTER(&rx_peerHashTable_lock);
8713 MUTEX_ENTER(&rx_rpc_stats);
8714 for (prev = peer = *peer_ptr; peer; peer = next) {
8716 code = MUTEX_TRYENTER(&peer->peer_lock);
8718 rx_interface_stat_p rpc_stat, nrpc_stat;
8721 if (prev == *peer_ptr) {
8732 MUTEX_EXIT(&rx_peerHashTable_lock);
8735 (&peer->rpcStats, rpc_stat, nrpc_stat,
8736 rx_interface_stat)) {
8737 unsigned int num_funcs = 0;
8740 queue_Remove(&rpc_stat->queue_header);
8741 queue_Remove(&rpc_stat->all_peers);
8742 num_funcs = rpc_stat->stats[0].func_total;
8744 sizeof(rx_interface_stat_t) +
8745 rpc_stat->stats[0].func_total *
8746 sizeof(rx_function_entry_v1_t);
8748 rxi_Free(rpc_stat, space);
8749 rxi_rpc_peer_stat_cnt -= num_funcs;
8751 MUTEX_EXIT(&peer->peer_lock);
8753 MUTEX_ENTER(&rx_peerHashTable_lock);
8763 MUTEX_EXIT(&rx_rpc_stats);
8764 MUTEX_EXIT(&rx_peerHashTable_lock);
8769 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8774 * IN clearFlag - flag indicating which stats to clear
8782 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8784 rx_interface_stat_p rpc_stat, nrpc_stat;
8786 MUTEX_ENTER(&rx_rpc_stats);
8788 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8789 unsigned int num_funcs = 0, i;
8790 num_funcs = rpc_stat->stats[0].func_total;
8791 for (i = 0; i < num_funcs; i++) {
8792 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8793 hzero(rpc_stat->stats[i].invocations);
8795 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8796 hzero(rpc_stat->stats[i].bytes_sent);
8798 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8799 hzero(rpc_stat->stats[i].bytes_rcvd);
8801 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8802 rpc_stat->stats[i].queue_time_sum.sec = 0;
8803 rpc_stat->stats[i].queue_time_sum.usec = 0;
8805 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8806 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8807 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8809 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8810 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8811 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8813 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8814 rpc_stat->stats[i].queue_time_max.sec = 0;
8815 rpc_stat->stats[i].queue_time_max.usec = 0;
8817 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8818 rpc_stat->stats[i].execution_time_sum.sec = 0;
8819 rpc_stat->stats[i].execution_time_sum.usec = 0;
8821 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8822 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8823 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8825 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8826 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8827 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8829 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8830 rpc_stat->stats[i].execution_time_max.sec = 0;
8831 rpc_stat->stats[i].execution_time_max.usec = 0;
8836 MUTEX_EXIT(&rx_rpc_stats);
8840 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8845 * IN clearFlag - flag indicating which stats to clear
8853 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8855 rx_interface_stat_p rpc_stat, nrpc_stat;
8857 MUTEX_ENTER(&rx_rpc_stats);
8859 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8860 unsigned int num_funcs = 0, i;
8863 * We have to fix the offset of rpc_stat since we are
8864 * keeping this structure on two rx_queues. The rx_queue
8865 * package assumes that the rx_queue member is the first
8866 * member of the structure. That is, rx_queue assumes that
8867 * any one item is only on one queue at a time. We are
8868 * breaking that assumption and so we have to do a little
8869 * math to fix our pointers.
8872 fix_offset = (char *)rpc_stat;
8873 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8874 rpc_stat = (rx_interface_stat_p) fix_offset;
8876 num_funcs = rpc_stat->stats[0].func_total;
8877 for (i = 0; i < num_funcs; i++) {
8878 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8879 hzero(rpc_stat->stats[i].invocations);
8881 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8882 hzero(rpc_stat->stats[i].bytes_sent);
8884 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8885 hzero(rpc_stat->stats[i].bytes_rcvd);
8887 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8888 rpc_stat->stats[i].queue_time_sum.sec = 0;
8889 rpc_stat->stats[i].queue_time_sum.usec = 0;
8891 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8892 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8893 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8895 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8896 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8897 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8899 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8900 rpc_stat->stats[i].queue_time_max.sec = 0;
8901 rpc_stat->stats[i].queue_time_max.usec = 0;
8903 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8904 rpc_stat->stats[i].execution_time_sum.sec = 0;
8905 rpc_stat->stats[i].execution_time_sum.usec = 0;
8907 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8908 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8909 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8911 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8912 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8913 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8915 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8916 rpc_stat->stats[i].execution_time_max.sec = 0;
8917 rpc_stat->stats[i].execution_time_max.usec = 0;
8922 MUTEX_EXIT(&rx_rpc_stats);
8926 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8927 * is authorized to enable/disable/clear RX statistics.
8929 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8932 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8934 rxi_rxstat_userok = proc;
8938 rx_RxStatUserOk(struct rx_call *call)
8940 if (!rxi_rxstat_userok)
8942 return rxi_rxstat_userok(call);
8947 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8948 * function in the MSVC runtime DLL (msvcrt.dll).
8950 * Note: the system serializes calls to this function.
8953 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8954 DWORD reason, /* reason function is being called */
8955 LPVOID reserved) /* reserved for future use */
8958 case DLL_PROCESS_ATTACH:
8959 /* library is being attached to a process */
8963 case DLL_PROCESS_DETACH:
8970 #endif /* AFS_NT40_ENV */
8973 int rx_DumpCalls(FILE *outputFile, char *cookie)
8975 #ifdef RXDEBUG_PACKET
8976 #ifdef KDUMP_RX_LOCK
8977 struct rx_call_rx_lock *c;
8984 #define RXDPRINTF sprintf
8985 #define RXDPRINTOUT output
8987 #define RXDPRINTF fprintf
8988 #define RXDPRINTOUT outputFile
8991 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8993 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8996 for (c = rx_allCallsp; c; c = c->allNextp) {
8997 u_short rqc, tqc, iovqc;
8998 struct rx_packet *p, *np;
9000 MUTEX_ENTER(&c->lock);
9001 queue_Count(&c->rq, p, np, rx_packet, rqc);
9002 queue_Count(&c->tq, p, np, rx_packet, tqc);
9003 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9005 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, "
9006 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9007 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9008 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9009 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9010 #ifdef RX_ENABLE_LOCKS
9013 #ifdef RX_REFCOUNT_CHECK
9014 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9015 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9018 cookie, c, c->call_id, (afs_uint32)c->state, (afs_uint32)c->mode, c->conn, c->conn?c->conn->epoch:0, c->conn?c->conn->cid:0,
9019 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9020 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9021 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9022 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9023 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9024 #ifdef RX_ENABLE_LOCKS
9025 , (afs_uint32)c->refCount
9027 #ifdef RX_REFCOUNT_CHECK
9028 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9031 MUTEX_EXIT(&c->lock);
9034 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9037 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9039 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9041 #endif /* RXDEBUG_PACKET */