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 the error to return to the application when a call
167 * channel appears busy (inferred from the receipt of RX_PACKET_TYPE_BUSY
168 * packets on the channel), and there are other call channels in the
169 * connection that are not busy. If 0, we do not return errors upon receiving
170 * busy packets; we just keep trying on the same call channel until we hit a
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 * Sets the error generated when a busy call channel is detected.
760 * @param[in] error The error to return for a call on a busy channel.
762 * @pre Neither rx_Init nor rx_InitHost have been called yet
765 rx_SetBusyChannelError(afs_int32 error)
767 osi_Assert(rxinit_status != 0);
768 rxi_busyChannelError = error;
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 rxi_CheckConnTimeouts(conn);
1117 int rxi_lowPeerRefCount = 0;
1118 int rxi_lowConnRefCount = 0;
1121 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1122 * NOTE: must not be called with rx_connHashTable_lock held.
1125 rxi_CleanupConnection(struct rx_connection *conn)
1127 /* Notify the service exporter, if requested, that this connection
1128 * is being destroyed */
1129 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1130 (*conn->service->destroyConnProc) (conn);
1132 /* Notify the security module that this connection is being destroyed */
1133 RXS_DestroyConnection(conn->securityObject, conn);
1135 /* If this is the last connection using the rx_peer struct, set its
1136 * idle time to now. rxi_ReapConnections will reap it if it's still
1137 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1139 MUTEX_ENTER(&rx_peerHashTable_lock);
1140 if (conn->peer->refCount < 2) {
1141 conn->peer->idleWhen = clock_Sec();
1142 if (conn->peer->refCount < 1) {
1143 conn->peer->refCount = 1;
1144 if (rx_stats_active) {
1145 MUTEX_ENTER(&rx_stats_mutex);
1146 rxi_lowPeerRefCount++;
1147 MUTEX_EXIT(&rx_stats_mutex);
1151 conn->peer->refCount--;
1152 MUTEX_EXIT(&rx_peerHashTable_lock);
1154 if (rx_stats_active)
1156 if (conn->type == RX_SERVER_CONNECTION)
1157 rx_atomic_dec(&rx_stats.nServerConns);
1159 rx_atomic_dec(&rx_stats.nClientConns);
1162 if (conn->specific) {
1164 for (i = 0; i < conn->nSpecific; i++) {
1165 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1166 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1167 conn->specific[i] = NULL;
1169 free(conn->specific);
1171 conn->specific = NULL;
1172 conn->nSpecific = 0;
1173 #endif /* !KERNEL */
1175 MUTEX_DESTROY(&conn->conn_call_lock);
1176 MUTEX_DESTROY(&conn->conn_data_lock);
1177 CV_DESTROY(&conn->conn_call_cv);
1179 rxi_FreeConnection(conn);
1182 /* Destroy the specified connection */
1184 rxi_DestroyConnection(struct rx_connection *conn)
1186 MUTEX_ENTER(&rx_connHashTable_lock);
1187 rxi_DestroyConnectionNoLock(conn);
1188 /* conn should be at the head of the cleanup list */
1189 if (conn == rx_connCleanup_list) {
1190 rx_connCleanup_list = rx_connCleanup_list->next;
1191 MUTEX_EXIT(&rx_connHashTable_lock);
1192 rxi_CleanupConnection(conn);
1194 #ifdef RX_ENABLE_LOCKS
1196 MUTEX_EXIT(&rx_connHashTable_lock);
1198 #endif /* RX_ENABLE_LOCKS */
1202 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1204 struct rx_connection **conn_ptr;
1206 struct rx_packet *packet;
1213 MUTEX_ENTER(&conn->conn_data_lock);
1214 MUTEX_ENTER(&rx_refcnt_mutex);
1215 if (conn->refCount > 0)
1218 if (rx_stats_active) {
1219 MUTEX_ENTER(&rx_stats_mutex);
1220 rxi_lowConnRefCount++;
1221 MUTEX_EXIT(&rx_stats_mutex);
1225 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1226 /* Busy; wait till the last guy before proceeding */
1227 MUTEX_EXIT(&rx_refcnt_mutex);
1228 MUTEX_EXIT(&conn->conn_data_lock);
1233 /* If the client previously called rx_NewCall, but it is still
1234 * waiting, treat this as a running call, and wait to destroy the
1235 * connection later when the call completes. */
1236 if ((conn->type == RX_CLIENT_CONNECTION)
1237 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1238 conn->flags |= RX_CONN_DESTROY_ME;
1239 MUTEX_EXIT(&conn->conn_data_lock);
1243 MUTEX_EXIT(&rx_refcnt_mutex);
1244 MUTEX_EXIT(&conn->conn_data_lock);
1246 /* Check for extant references to this connection */
1247 MUTEX_ENTER(&conn->conn_call_lock);
1248 for (i = 0; i < RX_MAXCALLS; i++) {
1249 struct rx_call *call = conn->call[i];
1252 if (conn->type == RX_CLIENT_CONNECTION) {
1253 MUTEX_ENTER(&call->lock);
1254 if (call->delayedAckEvent) {
1255 /* Push the final acknowledgment out now--there
1256 * won't be a subsequent call to acknowledge the
1257 * last reply packets */
1258 rxevent_Cancel(&call->delayedAckEvent, call,
1259 RX_CALL_REFCOUNT_DELAY);
1260 if (call->state == RX_STATE_PRECALL
1261 || call->state == RX_STATE_ACTIVE) {
1262 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1264 rxi_AckAll(NULL, call, 0);
1267 MUTEX_EXIT(&call->lock);
1271 MUTEX_EXIT(&conn->conn_call_lock);
1273 #ifdef RX_ENABLE_LOCKS
1275 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1276 MUTEX_EXIT(&conn->conn_data_lock);
1278 /* Someone is accessing a packet right now. */
1282 #endif /* RX_ENABLE_LOCKS */
1285 /* Don't destroy the connection if there are any call
1286 * structures still in use */
1287 MUTEX_ENTER(&conn->conn_data_lock);
1288 conn->flags |= RX_CONN_DESTROY_ME;
1289 MUTEX_EXIT(&conn->conn_data_lock);
1294 if (conn->natKeepAliveEvent) {
1295 rxi_NatKeepAliveOff(conn);
1298 if (conn->delayedAbortEvent) {
1299 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
1300 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1302 MUTEX_ENTER(&conn->conn_data_lock);
1303 rxi_SendConnectionAbort(conn, packet, 0, 1);
1304 MUTEX_EXIT(&conn->conn_data_lock);
1305 rxi_FreePacket(packet);
1309 /* Remove from connection hash table before proceeding */
1311 &rx_connHashTable[CONN_HASH
1312 (peer->host, peer->port, conn->cid, conn->epoch,
1314 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1315 if (*conn_ptr == conn) {
1316 *conn_ptr = conn->next;
1320 /* if the conn that we are destroying was the last connection, then we
1321 * clear rxLastConn as well */
1322 if (rxLastConn == conn)
1325 /* Make sure the connection is completely reset before deleting it. */
1326 /* get rid of pending events that could zap us later */
1327 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
1328 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
1329 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
1331 /* Add the connection to the list of destroyed connections that
1332 * need to be cleaned up. This is necessary to avoid deadlocks
1333 * in the routines we call to inform others that this connection is
1334 * being destroyed. */
1335 conn->next = rx_connCleanup_list;
1336 rx_connCleanup_list = conn;
1339 /* Externally available version */
1341 rx_DestroyConnection(struct rx_connection *conn)
1346 rxi_DestroyConnection(conn);
1351 rx_GetConnection(struct rx_connection *conn)
1356 MUTEX_ENTER(&rx_refcnt_mutex);
1358 MUTEX_EXIT(&rx_refcnt_mutex);
1362 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1363 /* Wait for the transmit queue to no longer be busy.
1364 * requires the call->lock to be held */
1366 rxi_WaitforTQBusy(struct rx_call *call) {
1367 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1368 call->flags |= RX_CALL_TQ_WAIT;
1370 #ifdef RX_ENABLE_LOCKS
1371 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1372 CV_WAIT(&call->cv_tq, &call->lock);
1373 #else /* RX_ENABLE_LOCKS */
1374 osi_rxSleep(&call->tq);
1375 #endif /* RX_ENABLE_LOCKS */
1377 if (call->tqWaiters == 0) {
1378 call->flags &= ~RX_CALL_TQ_WAIT;
1385 rxi_WakeUpTransmitQueue(struct rx_call *call)
1387 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1388 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1389 call, call->tqWaiters, call->flags));
1390 #ifdef RX_ENABLE_LOCKS
1391 osirx_AssertMine(&call->lock, "rxi_Start start");
1392 CV_BROADCAST(&call->cv_tq);
1393 #else /* RX_ENABLE_LOCKS */
1394 osi_rxWakeup(&call->tq);
1395 #endif /* RX_ENABLE_LOCKS */
1399 /* Start a new rx remote procedure call, on the specified connection.
1400 * If wait is set to 1, wait for a free call channel; otherwise return
1401 * 0. Maxtime gives the maximum number of seconds this call may take,
1402 * after rx_NewCall returns. After this time interval, a call to any
1403 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1404 * For fine grain locking, we hold the conn_call_lock in order to
1405 * to ensure that we don't get signalle after we found a call in an active
1406 * state and before we go to sleep.
1409 rx_NewCall(struct rx_connection *conn)
1411 int i, wait, ignoreBusy = 1;
1412 struct rx_call *call;
1413 struct clock queueTime;
1414 afs_uint32 leastBusy = 0;
1418 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1421 clock_GetTime(&queueTime);
1423 * Check if there are others waiting for a new call.
1424 * If so, let them go first to avoid starving them.
1425 * This is a fairly simple scheme, and might not be
1426 * a complete solution for large numbers of waiters.
1428 * makeCallWaiters keeps track of the number of
1429 * threads waiting to make calls and the
1430 * RX_CONN_MAKECALL_WAITING flag bit is used to
1431 * indicate that there are indeed calls waiting.
1432 * The flag is set when the waiter is incremented.
1433 * It is only cleared when makeCallWaiters is 0.
1434 * This prevents us from accidently destroying the
1435 * connection while it is potentially about to be used.
1437 MUTEX_ENTER(&conn->conn_call_lock);
1438 MUTEX_ENTER(&conn->conn_data_lock);
1439 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1440 conn->flags |= RX_CONN_MAKECALL_WAITING;
1441 conn->makeCallWaiters++;
1442 MUTEX_EXIT(&conn->conn_data_lock);
1444 #ifdef RX_ENABLE_LOCKS
1445 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1449 MUTEX_ENTER(&conn->conn_data_lock);
1450 conn->makeCallWaiters--;
1451 if (conn->makeCallWaiters == 0)
1452 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1455 /* We are now the active thread in rx_NewCall */
1456 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1457 MUTEX_EXIT(&conn->conn_data_lock);
1462 for (i = 0; i < RX_MAXCALLS; i++) {
1463 call = conn->call[i];
1465 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1466 /* we're not ignoring busy call slots; only look at the
1467 * call slot that is the "least" busy */
1471 if (call->state == RX_STATE_DALLY) {
1472 MUTEX_ENTER(&call->lock);
1473 if (call->state == RX_STATE_DALLY) {
1474 if (ignoreBusy && conn->lastBusy[i]) {
1475 /* if we're ignoring busy call slots, skip any ones that
1476 * have lastBusy set */
1477 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1478 leastBusy = conn->lastBusy[i];
1480 MUTEX_EXIT(&call->lock);
1485 * We are setting the state to RX_STATE_RESET to
1486 * ensure that no one else will attempt to use this
1487 * call once we drop the conn->conn_call_lock and
1488 * call->lock. We must drop the conn->conn_call_lock
1489 * before calling rxi_ResetCall because the process
1490 * of clearing the transmit queue can block for an
1491 * extended period of time. If we block while holding
1492 * the conn->conn_call_lock, then all rx_EndCall
1493 * processing will block as well. This has a detrimental
1494 * effect on overall system performance.
1496 call->state = RX_STATE_RESET;
1497 MUTEX_EXIT(&conn->conn_call_lock);
1498 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1499 rxi_ResetCall(call, 0);
1500 (*call->callNumber)++;
1501 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1505 * If we failed to be able to safely obtain the
1506 * conn->conn_call_lock we will have to drop the
1507 * call->lock to avoid a deadlock. When the call->lock
1508 * is released the state of the call can change. If it
1509 * is no longer RX_STATE_RESET then some other thread is
1512 MUTEX_EXIT(&call->lock);
1513 MUTEX_ENTER(&conn->conn_call_lock);
1514 MUTEX_ENTER(&call->lock);
1516 if (call->state == RX_STATE_RESET)
1520 * If we get here it means that after dropping
1521 * the conn->conn_call_lock and call->lock that
1522 * the call is no longer ours. If we can't find
1523 * a free call in the remaining slots we should
1524 * not go immediately to RX_CONN_MAKECALL_WAITING
1525 * because by dropping the conn->conn_call_lock
1526 * we have given up synchronization with rx_EndCall.
1527 * Instead, cycle through one more time to see if
1528 * we can find a call that can call our own.
1530 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1533 MUTEX_EXIT(&call->lock);
1536 if (ignoreBusy && conn->lastBusy[i]) {
1537 /* if we're ignoring busy call slots, skip any ones that
1538 * have lastBusy set */
1539 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1540 leastBusy = conn->lastBusy[i];
1545 /* rxi_NewCall returns with mutex locked */
1546 call = rxi_NewCall(conn, i);
1547 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1551 if (i < RX_MAXCALLS) {
1552 conn->lastBusy[i] = 0;
1557 if (leastBusy && ignoreBusy) {
1558 /* we didn't find a useable call slot, but we did see at least one
1559 * 'busy' slot; look again and only use a slot with the 'least
1565 MUTEX_ENTER(&conn->conn_data_lock);
1566 conn->flags |= RX_CONN_MAKECALL_WAITING;
1567 conn->makeCallWaiters++;
1568 MUTEX_EXIT(&conn->conn_data_lock);
1570 #ifdef RX_ENABLE_LOCKS
1571 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1575 MUTEX_ENTER(&conn->conn_data_lock);
1576 conn->makeCallWaiters--;
1577 if (conn->makeCallWaiters == 0)
1578 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1579 MUTEX_EXIT(&conn->conn_data_lock);
1581 /* Client is initially in send mode */
1582 call->state = RX_STATE_ACTIVE;
1583 call->error = conn->error;
1585 call->mode = RX_MODE_ERROR;
1587 call->mode = RX_MODE_SENDING;
1589 /* remember start time for call in case we have hard dead time limit */
1590 call->queueTime = queueTime;
1591 clock_GetTime(&call->startTime);
1592 hzero(call->bytesSent);
1593 hzero(call->bytesRcvd);
1595 /* Turn on busy protocol. */
1596 rxi_KeepAliveOn(call);
1598 /* Attempt MTU discovery */
1599 rxi_GrowMTUOn(call);
1602 * We are no longer the active thread in rx_NewCall
1604 MUTEX_ENTER(&conn->conn_data_lock);
1605 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1606 MUTEX_EXIT(&conn->conn_data_lock);
1609 * Wake up anyone else who might be giving us a chance to
1610 * run (see code above that avoids resource starvation).
1612 #ifdef RX_ENABLE_LOCKS
1613 CV_BROADCAST(&conn->conn_call_cv);
1617 MUTEX_EXIT(&conn->conn_call_lock);
1619 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1620 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1621 osi_Panic("rx_NewCall call about to be used without an empty tq");
1623 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1625 MUTEX_EXIT(&call->lock);
1628 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1633 rxi_HasActiveCalls(struct rx_connection *aconn)
1636 struct rx_call *tcall;
1640 for (i = 0; i < RX_MAXCALLS; i++) {
1641 if ((tcall = aconn->call[i])) {
1642 if ((tcall->state == RX_STATE_ACTIVE)
1643 || (tcall->state == RX_STATE_PRECALL)) {
1654 rxi_GetCallNumberVector(struct rx_connection *aconn,
1655 afs_int32 * aint32s)
1658 struct rx_call *tcall;
1662 for (i = 0; i < RX_MAXCALLS; i++) {
1663 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1664 aint32s[i] = aconn->callNumber[i] + 1;
1666 aint32s[i] = aconn->callNumber[i];
1673 rxi_SetCallNumberVector(struct rx_connection *aconn,
1674 afs_int32 * aint32s)
1677 struct rx_call *tcall;
1681 for (i = 0; i < RX_MAXCALLS; i++) {
1682 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1683 aconn->callNumber[i] = aint32s[i] - 1;
1685 aconn->callNumber[i] = aint32s[i];
1691 /* Advertise a new service. A service is named locally by a UDP port
1692 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1695 char *serviceName; Name for identification purposes (e.g. the
1696 service name might be used for probing for
1699 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1700 char *serviceName, struct rx_securityClass **securityObjects,
1701 int nSecurityObjects,
1702 afs_int32(*serviceProc) (struct rx_call * acall))
1704 osi_socket socket = OSI_NULLSOCKET;
1705 struct rx_service *tservice;
1711 if (serviceId == 0) {
1713 "rx_NewService: service id for service %s is not non-zero.\n",
1720 "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",
1728 tservice = rxi_AllocService();
1731 #ifdef RX_ENABLE_LOCKS
1732 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1735 for (i = 0; i < RX_MAX_SERVICES; i++) {
1736 struct rx_service *service = rx_services[i];
1738 if (port == service->servicePort && host == service->serviceHost) {
1739 if (service->serviceId == serviceId) {
1740 /* The identical service has already been
1741 * installed; if the caller was intending to
1742 * change the security classes used by this
1743 * service, he/she loses. */
1745 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1746 serviceName, serviceId, service->serviceName);
1748 rxi_FreeService(tservice);
1751 /* Different service, same port: re-use the socket
1752 * which is bound to the same port */
1753 socket = service->socket;
1756 if (socket == OSI_NULLSOCKET) {
1757 /* If we don't already have a socket (from another
1758 * service on same port) get a new one */
1759 socket = rxi_GetHostUDPSocket(host, port);
1760 if (socket == OSI_NULLSOCKET) {
1762 rxi_FreeService(tservice);
1767 service->socket = socket;
1768 service->serviceHost = host;
1769 service->servicePort = port;
1770 service->serviceId = serviceId;
1771 service->serviceName = serviceName;
1772 service->nSecurityObjects = nSecurityObjects;
1773 service->securityObjects = securityObjects;
1774 service->minProcs = 0;
1775 service->maxProcs = 1;
1776 service->idleDeadTime = 60;
1777 service->idleDeadErr = 0;
1778 service->connDeadTime = rx_connDeadTime;
1779 service->executeRequestProc = serviceProc;
1780 service->checkReach = 0;
1781 service->nSpecific = 0;
1782 service->specific = NULL;
1783 rx_services[i] = service; /* not visible until now */
1789 rxi_FreeService(tservice);
1790 (osi_Msg "rx_NewService: cannot support > %d services\n",
1795 /* Set configuration options for all of a service's security objects */
1798 rx_SetSecurityConfiguration(struct rx_service *service,
1799 rx_securityConfigVariables type,
1803 for (i = 0; i<service->nSecurityObjects; i++) {
1804 if (service->securityObjects[i]) {
1805 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1813 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1814 struct rx_securityClass **securityObjects, int nSecurityObjects,
1815 afs_int32(*serviceProc) (struct rx_call * acall))
1817 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1820 /* Generic request processing loop. This routine should be called
1821 * by the implementation dependent rx_ServerProc. If socketp is
1822 * non-null, it will be set to the file descriptor that this thread
1823 * is now listening on. If socketp is null, this routine will never
1826 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1828 struct rx_call *call;
1830 struct rx_service *tservice = NULL;
1837 call = rx_GetCall(threadID, tservice, socketp);
1838 if (socketp && *socketp != OSI_NULLSOCKET) {
1839 /* We are now a listener thread */
1845 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1846 #ifdef RX_ENABLE_LOCKS
1848 #endif /* RX_ENABLE_LOCKS */
1849 afs_termState = AFSOP_STOP_AFS;
1850 afs_osi_Wakeup(&afs_termState);
1851 #ifdef RX_ENABLE_LOCKS
1853 #endif /* RX_ENABLE_LOCKS */
1858 /* if server is restarting( typically smooth shutdown) then do not
1859 * allow any new calls.
1862 if (rx_tranquil && (call != NULL)) {
1866 MUTEX_ENTER(&call->lock);
1868 rxi_CallError(call, RX_RESTARTING);
1869 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1871 MUTEX_EXIT(&call->lock);
1876 tservice = call->conn->service;
1878 if (tservice->beforeProc)
1879 (*tservice->beforeProc) (call);
1881 code = tservice->executeRequestProc(call);
1883 if (tservice->afterProc)
1884 (*tservice->afterProc) (call, code);
1886 rx_EndCall(call, code);
1888 if (tservice->postProc)
1889 (*tservice->postProc) (code);
1891 if (rx_stats_active) {
1892 MUTEX_ENTER(&rx_stats_mutex);
1894 MUTEX_EXIT(&rx_stats_mutex);
1901 rx_WakeupServerProcs(void)
1903 struct rx_serverQueueEntry *np, *tqp;
1907 MUTEX_ENTER(&rx_serverPool_lock);
1909 #ifdef RX_ENABLE_LOCKS
1910 if (rx_waitForPacket)
1911 CV_BROADCAST(&rx_waitForPacket->cv);
1912 #else /* RX_ENABLE_LOCKS */
1913 if (rx_waitForPacket)
1914 osi_rxWakeup(rx_waitForPacket);
1915 #endif /* RX_ENABLE_LOCKS */
1916 MUTEX_ENTER(&freeSQEList_lock);
1917 for (np = rx_FreeSQEList; np; np = tqp) {
1918 tqp = *(struct rx_serverQueueEntry **)np;
1919 #ifdef RX_ENABLE_LOCKS
1920 CV_BROADCAST(&np->cv);
1921 #else /* RX_ENABLE_LOCKS */
1923 #endif /* RX_ENABLE_LOCKS */
1925 MUTEX_EXIT(&freeSQEList_lock);
1926 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1927 #ifdef RX_ENABLE_LOCKS
1928 CV_BROADCAST(&np->cv);
1929 #else /* RX_ENABLE_LOCKS */
1931 #endif /* RX_ENABLE_LOCKS */
1933 MUTEX_EXIT(&rx_serverPool_lock);
1938 * One thing that seems to happen is that all the server threads get
1939 * tied up on some empty or slow call, and then a whole bunch of calls
1940 * arrive at once, using up the packet pool, so now there are more
1941 * empty calls. The most critical resources here are server threads
1942 * and the free packet pool. The "doreclaim" code seems to help in
1943 * general. I think that eventually we arrive in this state: there
1944 * are lots of pending calls which do have all their packets present,
1945 * so they won't be reclaimed, are multi-packet calls, so they won't
1946 * be scheduled until later, and thus are tying up most of the free
1947 * packet pool for a very long time.
1949 * 1. schedule multi-packet calls if all the packets are present.
1950 * Probably CPU-bound operation, useful to return packets to pool.
1951 * Do what if there is a full window, but the last packet isn't here?
1952 * 3. preserve one thread which *only* runs "best" calls, otherwise
1953 * it sleeps and waits for that type of call.
1954 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1955 * the current dataquota business is badly broken. The quota isn't adjusted
1956 * to reflect how many packets are presently queued for a running call.
1957 * So, when we schedule a queued call with a full window of packets queued
1958 * up for it, that *should* free up a window full of packets for other 2d-class
1959 * calls to be able to use from the packet pool. But it doesn't.
1961 * NB. Most of the time, this code doesn't run -- since idle server threads
1962 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1963 * as a new call arrives.
1965 /* Sleep until a call arrives. Returns a pointer to the call, ready
1966 * for an rx_Read. */
1967 #ifdef RX_ENABLE_LOCKS
1969 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1971 struct rx_serverQueueEntry *sq;
1972 struct rx_call *call = (struct rx_call *)0;
1973 struct rx_service *service = NULL;
1975 MUTEX_ENTER(&freeSQEList_lock);
1977 if ((sq = rx_FreeSQEList)) {
1978 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1979 MUTEX_EXIT(&freeSQEList_lock);
1980 } else { /* otherwise allocate a new one and return that */
1981 MUTEX_EXIT(&freeSQEList_lock);
1982 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1983 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1984 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1987 MUTEX_ENTER(&rx_serverPool_lock);
1988 if (cur_service != NULL) {
1989 ReturnToServerPool(cur_service);
1992 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1993 struct rx_call *tcall, *ncall, *choice2 = NULL;
1995 /* Scan for eligible incoming calls. A call is not eligible
1996 * if the maximum number of calls for its service type are
1997 * already executing */
1998 /* One thread will process calls FCFS (to prevent starvation),
1999 * while the other threads may run ahead looking for calls which
2000 * have all their input data available immediately. This helps
2001 * keep threads from blocking, waiting for data from the client. */
2002 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2003 service = tcall->conn->service;
2004 if (!QuotaOK(service)) {
2007 MUTEX_ENTER(&rx_pthread_mutex);
2008 if (tno == rxi_fcfs_thread_num
2009 || !tcall->queue_item_header.next) {
2010 MUTEX_EXIT(&rx_pthread_mutex);
2011 /* If we're the fcfs thread , then we'll just use
2012 * this call. If we haven't been able to find an optimal
2013 * choice, and we're at the end of the list, then use a
2014 * 2d choice if one has been identified. Otherwise... */
2015 call = (choice2 ? choice2 : tcall);
2016 service = call->conn->service;
2018 MUTEX_EXIT(&rx_pthread_mutex);
2019 if (!queue_IsEmpty(&tcall->rq)) {
2020 struct rx_packet *rp;
2021 rp = queue_First(&tcall->rq, rx_packet);
2022 if (rp->header.seq == 1) {
2024 || (rp->header.flags & RX_LAST_PACKET)) {
2026 } else if (rxi_2dchoice && !choice2
2027 && !(tcall->flags & RX_CALL_CLEARED)
2028 && (tcall->rprev > rxi_HardAckRate)) {
2038 ReturnToServerPool(service);
2045 MUTEX_EXIT(&rx_serverPool_lock);
2046 MUTEX_ENTER(&call->lock);
2048 if (call->flags & RX_CALL_WAIT_PROC) {
2049 call->flags &= ~RX_CALL_WAIT_PROC;
2050 rx_atomic_dec(&rx_nWaiting);
2053 if (call->state != RX_STATE_PRECALL || call->error) {
2054 MUTEX_EXIT(&call->lock);
2055 MUTEX_ENTER(&rx_serverPool_lock);
2056 ReturnToServerPool(service);
2061 if (queue_IsEmpty(&call->rq)
2062 || queue_First(&call->rq, rx_packet)->header.seq != 1)
2063 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2065 CLEAR_CALL_QUEUE_LOCK(call);
2068 /* If there are no eligible incoming calls, add this process
2069 * to the idle server queue, to wait for one */
2073 *socketp = OSI_NULLSOCKET;
2075 sq->socketp = socketp;
2076 queue_Append(&rx_idleServerQueue, sq);
2077 #ifndef AFS_AIX41_ENV
2078 rx_waitForPacket = sq;
2080 rx_waitingForPacket = sq;
2081 #endif /* AFS_AIX41_ENV */
2083 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2085 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2086 MUTEX_EXIT(&rx_serverPool_lock);
2087 return (struct rx_call *)0;
2090 } while (!(call = sq->newcall)
2091 && !(socketp && *socketp != OSI_NULLSOCKET));
2092 MUTEX_EXIT(&rx_serverPool_lock);
2094 MUTEX_ENTER(&call->lock);
2100 MUTEX_ENTER(&freeSQEList_lock);
2101 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2102 rx_FreeSQEList = sq;
2103 MUTEX_EXIT(&freeSQEList_lock);
2106 clock_GetTime(&call->startTime);
2107 call->state = RX_STATE_ACTIVE;
2108 call->mode = RX_MODE_RECEIVING;
2109 #ifdef RX_KERNEL_TRACE
2110 if (ICL_SETACTIVE(afs_iclSetp)) {
2111 int glockOwner = ISAFS_GLOCK();
2114 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2115 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2122 rxi_calltrace(RX_CALL_START, call);
2123 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2124 call->conn->service->servicePort, call->conn->service->serviceId,
2127 MUTEX_EXIT(&call->lock);
2128 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2130 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2135 #else /* RX_ENABLE_LOCKS */
2137 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2139 struct rx_serverQueueEntry *sq;
2140 struct rx_call *call = (struct rx_call *)0, *choice2;
2141 struct rx_service *service = NULL;
2145 MUTEX_ENTER(&freeSQEList_lock);
2147 if ((sq = rx_FreeSQEList)) {
2148 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2149 MUTEX_EXIT(&freeSQEList_lock);
2150 } else { /* otherwise allocate a new one and return that */
2151 MUTEX_EXIT(&freeSQEList_lock);
2152 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2153 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2154 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2156 MUTEX_ENTER(&sq->lock);
2158 if (cur_service != NULL) {
2159 cur_service->nRequestsRunning--;
2160 MUTEX_ENTER(&rx_quota_mutex);
2161 if (cur_service->nRequestsRunning < cur_service->minProcs)
2164 MUTEX_EXIT(&rx_quota_mutex);
2166 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2167 struct rx_call *tcall, *ncall;
2168 /* Scan for eligible incoming calls. A call is not eligible
2169 * if the maximum number of calls for its service type are
2170 * already executing */
2171 /* One thread will process calls FCFS (to prevent starvation),
2172 * while the other threads may run ahead looking for calls which
2173 * have all their input data available immediately. This helps
2174 * keep threads from blocking, waiting for data from the client. */
2175 choice2 = (struct rx_call *)0;
2176 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2177 service = tcall->conn->service;
2178 if (QuotaOK(service)) {
2179 MUTEX_ENTER(&rx_pthread_mutex);
2180 if (tno == rxi_fcfs_thread_num
2181 || !tcall->queue_item_header.next) {
2182 MUTEX_EXIT(&rx_pthread_mutex);
2183 /* If we're the fcfs thread, then we'll just use
2184 * this call. If we haven't been able to find an optimal
2185 * choice, and we're at the end of the list, then use a
2186 * 2d choice if one has been identified. Otherwise... */
2187 call = (choice2 ? choice2 : tcall);
2188 service = call->conn->service;
2190 MUTEX_EXIT(&rx_pthread_mutex);
2191 if (!queue_IsEmpty(&tcall->rq)) {
2192 struct rx_packet *rp;
2193 rp = queue_First(&tcall->rq, rx_packet);
2194 if (rp->header.seq == 1
2196 || (rp->header.flags & RX_LAST_PACKET))) {
2198 } else if (rxi_2dchoice && !choice2
2199 && !(tcall->flags & RX_CALL_CLEARED)
2200 && (tcall->rprev > rxi_HardAckRate)) {
2214 /* we can't schedule a call if there's no data!!! */
2215 /* send an ack if there's no data, if we're missing the
2216 * first packet, or we're missing something between first
2217 * and last -- there's a "hole" in the incoming data. */
2218 if (queue_IsEmpty(&call->rq)
2219 || queue_First(&call->rq, rx_packet)->header.seq != 1
2220 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2221 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2223 call->flags &= (~RX_CALL_WAIT_PROC);
2224 service->nRequestsRunning++;
2225 /* just started call in minProcs pool, need fewer to maintain
2227 MUTEX_ENTER(&rx_quota_mutex);
2228 if (service->nRequestsRunning <= service->minProcs)
2231 MUTEX_EXIT(&rx_quota_mutex);
2232 rx_atomic_dec(&rx_nWaiting);
2233 /* MUTEX_EXIT(&call->lock); */
2235 /* If there are no eligible incoming calls, add this process
2236 * to the idle server queue, to wait for one */
2239 *socketp = OSI_NULLSOCKET;
2241 sq->socketp = socketp;
2242 queue_Append(&rx_idleServerQueue, sq);
2246 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2248 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2249 return (struct rx_call *)0;
2252 } while (!(call = sq->newcall)
2253 && !(socketp && *socketp != OSI_NULLSOCKET));
2255 MUTEX_EXIT(&sq->lock);
2257 MUTEX_ENTER(&freeSQEList_lock);
2258 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2259 rx_FreeSQEList = sq;
2260 MUTEX_EXIT(&freeSQEList_lock);
2263 clock_GetTime(&call->startTime);
2264 call->state = RX_STATE_ACTIVE;
2265 call->mode = RX_MODE_RECEIVING;
2266 #ifdef RX_KERNEL_TRACE
2267 if (ICL_SETACTIVE(afs_iclSetp)) {
2268 int glockOwner = ISAFS_GLOCK();
2271 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2272 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2279 rxi_calltrace(RX_CALL_START, call);
2280 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2281 call->conn->service->servicePort, call->conn->service->serviceId,
2284 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2291 #endif /* RX_ENABLE_LOCKS */
2295 /* Establish a procedure to be called when a packet arrives for a
2296 * call. This routine will be called at most once after each call,
2297 * and will also be called if there is an error condition on the or
2298 * the call is complete. Used by multi rx to build a selection
2299 * function which determines which of several calls is likely to be a
2300 * good one to read from.
2301 * NOTE: the way this is currently implemented it is probably only a
2302 * good idea to (1) use it immediately after a newcall (clients only)
2303 * and (2) only use it once. Other uses currently void your warranty
2306 rx_SetArrivalProc(struct rx_call *call,
2307 void (*proc) (struct rx_call * call,
2310 void * handle, int arg)
2312 call->arrivalProc = proc;
2313 call->arrivalProcHandle = handle;
2314 call->arrivalProcArg = arg;
2317 /* Call is finished (possibly prematurely). Return rc to the peer, if
2318 * appropriate, and return the final error code from the conversation
2322 rx_EndCall(struct rx_call *call, afs_int32 rc)
2324 struct rx_connection *conn = call->conn;
2328 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2329 call, rc, call->error, call->abortCode));
2332 MUTEX_ENTER(&call->lock);
2334 if (rc == 0 && call->error == 0) {
2335 call->abortCode = 0;
2336 call->abortCount = 0;
2339 call->arrivalProc = (void (*)())0;
2340 if (rc && call->error == 0) {
2341 rxi_CallError(call, rc);
2342 call->mode = RX_MODE_ERROR;
2343 /* Send an abort message to the peer if this error code has
2344 * only just been set. If it was set previously, assume the
2345 * peer has already been sent the error code or will request it
2347 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2349 if (conn->type == RX_SERVER_CONNECTION) {
2350 /* Make sure reply or at least dummy reply is sent */
2351 if (call->mode == RX_MODE_RECEIVING) {
2352 MUTEX_EXIT(&call->lock);
2353 rxi_WriteProc(call, 0, 0);
2354 MUTEX_ENTER(&call->lock);
2356 if (call->mode == RX_MODE_SENDING) {
2357 MUTEX_EXIT(&call->lock);
2358 rxi_FlushWrite(call);
2359 MUTEX_ENTER(&call->lock);
2361 rxi_calltrace(RX_CALL_END, call);
2362 /* Call goes to hold state until reply packets are acknowledged */
2363 if (call->tfirst + call->nSoftAcked < call->tnext) {
2364 call->state = RX_STATE_HOLD;
2366 call->state = RX_STATE_DALLY;
2367 rxi_ClearTransmitQueue(call, 0);
2368 rxi_rto_cancel(call);
2369 rxevent_Cancel(&call->keepAliveEvent, call,
2370 RX_CALL_REFCOUNT_ALIVE);
2372 } else { /* Client connection */
2374 /* Make sure server receives input packets, in the case where
2375 * no reply arguments are expected */
2376 if ((call->mode == RX_MODE_SENDING)
2377 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2378 MUTEX_EXIT(&call->lock);
2379 (void)rxi_ReadProc(call, &dummy, 1);
2380 MUTEX_ENTER(&call->lock);
2383 /* If we had an outstanding delayed ack, be nice to the server
2384 * and force-send it now.
2386 if (call->delayedAckEvent) {
2387 rxevent_Cancel(&call->delayedAckEvent, call,
2388 RX_CALL_REFCOUNT_DELAY);
2389 rxi_SendDelayedAck(NULL, call, NULL, 0);
2392 /* We need to release the call lock since it's lower than the
2393 * conn_call_lock and we don't want to hold the conn_call_lock
2394 * over the rx_ReadProc call. The conn_call_lock needs to be held
2395 * here for the case where rx_NewCall is perusing the calls on
2396 * the connection structure. We don't want to signal until
2397 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2398 * have checked this call, found it active and by the time it
2399 * goes to sleep, will have missed the signal.
2401 MUTEX_EXIT(&call->lock);
2402 MUTEX_ENTER(&conn->conn_call_lock);
2403 MUTEX_ENTER(&call->lock);
2405 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2406 conn->lastBusy[call->channel] = 0;
2409 MUTEX_ENTER(&conn->conn_data_lock);
2410 conn->flags |= RX_CONN_BUSY;
2411 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2412 MUTEX_EXIT(&conn->conn_data_lock);
2413 #ifdef RX_ENABLE_LOCKS
2414 CV_BROADCAST(&conn->conn_call_cv);
2419 #ifdef RX_ENABLE_LOCKS
2421 MUTEX_EXIT(&conn->conn_data_lock);
2423 #endif /* RX_ENABLE_LOCKS */
2424 call->state = RX_STATE_DALLY;
2426 error = call->error;
2428 /* currentPacket, nLeft, and NFree must be zeroed here, because
2429 * ResetCall cannot: ResetCall may be called at splnet(), in the
2430 * kernel version, and may interrupt the macros rx_Read or
2431 * rx_Write, which run at normal priority for efficiency. */
2432 if (call->currentPacket) {
2433 #ifdef RX_TRACK_PACKETS
2434 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2436 rxi_FreePacket(call->currentPacket);
2437 call->currentPacket = (struct rx_packet *)0;
2440 call->nLeft = call->nFree = call->curlen = 0;
2442 /* Free any packets from the last call to ReadvProc/WritevProc */
2443 #ifdef RXDEBUG_PACKET
2445 #endif /* RXDEBUG_PACKET */
2446 rxi_FreePackets(0, &call->iovq);
2447 MUTEX_EXIT(&call->lock);
2449 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2450 if (conn->type == RX_CLIENT_CONNECTION) {
2451 MUTEX_ENTER(&conn->conn_data_lock);
2452 conn->flags &= ~RX_CONN_BUSY;
2453 MUTEX_EXIT(&conn->conn_data_lock);
2454 MUTEX_EXIT(&conn->conn_call_lock);
2458 * Map errors to the local host's errno.h format.
2460 error = ntoh_syserr_conv(error);
2464 #if !defined(KERNEL)
2466 /* Call this routine when shutting down a server or client (especially
2467 * clients). This will allow Rx to gracefully garbage collect server
2468 * connections, and reduce the number of retries that a server might
2469 * make to a dead client.
2470 * This is not quite right, since some calls may still be ongoing and
2471 * we can't lock them to destroy them. */
2475 struct rx_connection **conn_ptr, **conn_end;
2479 if (rxinit_status == 1) {
2481 return; /* Already shutdown. */
2483 rxi_DeleteCachedConnections();
2484 if (rx_connHashTable) {
2485 MUTEX_ENTER(&rx_connHashTable_lock);
2486 for (conn_ptr = &rx_connHashTable[0], conn_end =
2487 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2489 struct rx_connection *conn, *next;
2490 for (conn = *conn_ptr; conn; conn = next) {
2492 if (conn->type == RX_CLIENT_CONNECTION) {
2493 MUTEX_ENTER(&rx_refcnt_mutex);
2495 MUTEX_EXIT(&rx_refcnt_mutex);
2496 #ifdef RX_ENABLE_LOCKS
2497 rxi_DestroyConnectionNoLock(conn);
2498 #else /* RX_ENABLE_LOCKS */
2499 rxi_DestroyConnection(conn);
2500 #endif /* RX_ENABLE_LOCKS */
2504 #ifdef RX_ENABLE_LOCKS
2505 while (rx_connCleanup_list) {
2506 struct rx_connection *conn;
2507 conn = rx_connCleanup_list;
2508 rx_connCleanup_list = rx_connCleanup_list->next;
2509 MUTEX_EXIT(&rx_connHashTable_lock);
2510 rxi_CleanupConnection(conn);
2511 MUTEX_ENTER(&rx_connHashTable_lock);
2513 MUTEX_EXIT(&rx_connHashTable_lock);
2514 #endif /* RX_ENABLE_LOCKS */
2519 afs_winsockCleanup();
2527 /* if we wakeup packet waiter too often, can get in loop with two
2528 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2530 rxi_PacketsUnWait(void)
2532 if (!rx_waitingForPackets) {
2536 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2537 return; /* still over quota */
2540 rx_waitingForPackets = 0;
2541 #ifdef RX_ENABLE_LOCKS
2542 CV_BROADCAST(&rx_waitingForPackets_cv);
2544 osi_rxWakeup(&rx_waitingForPackets);
2550 /* ------------------Internal interfaces------------------------- */
2552 /* Return this process's service structure for the
2553 * specified socket and service */
2554 static struct rx_service *
2555 rxi_FindService(osi_socket socket, u_short serviceId)
2557 struct rx_service **sp;
2558 for (sp = &rx_services[0]; *sp; sp++) {
2559 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2565 #ifdef RXDEBUG_PACKET
2566 #ifdef KDUMP_RX_LOCK
2567 static struct rx_call_rx_lock *rx_allCallsp = 0;
2569 static struct rx_call *rx_allCallsp = 0;
2571 #endif /* RXDEBUG_PACKET */
2573 /* Allocate a call structure, for the indicated channel of the
2574 * supplied connection. The mode and state of the call must be set by
2575 * the caller. Returns the call with mutex locked. */
2576 static struct rx_call *
2577 rxi_NewCall(struct rx_connection *conn, int channel)
2579 struct rx_call *call;
2580 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2581 struct rx_call *cp; /* Call pointer temp */
2582 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2583 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2585 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2587 /* Grab an existing call structure, or allocate a new one.
2588 * Existing call structures are assumed to have been left reset by
2590 MUTEX_ENTER(&rx_freeCallQueue_lock);
2592 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2594 * EXCEPT that the TQ might not yet be cleared out.
2595 * Skip over those with in-use TQs.
2598 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2599 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2605 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2606 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2607 call = queue_First(&rx_freeCallQueue, rx_call);
2608 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2610 if (rx_stats_active)
2611 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2612 MUTEX_EXIT(&rx_freeCallQueue_lock);
2613 MUTEX_ENTER(&call->lock);
2614 CLEAR_CALL_QUEUE_LOCK(call);
2615 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2616 /* Now, if TQ wasn't cleared earlier, do it now. */
2617 rxi_WaitforTQBusy(call);
2618 if (call->flags & RX_CALL_TQ_CLEARME) {
2619 rxi_ClearTransmitQueue(call, 1);
2620 /*queue_Init(&call->tq);*/
2622 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2623 /* Bind the call to its connection structure */
2625 rxi_ResetCall(call, 1);
2628 call = rxi_Alloc(sizeof(struct rx_call));
2629 #ifdef RXDEBUG_PACKET
2630 call->allNextp = rx_allCallsp;
2631 rx_allCallsp = call;
2633 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2634 #else /* RXDEBUG_PACKET */
2635 rx_atomic_inc(&rx_stats.nCallStructs);
2636 #endif /* RXDEBUG_PACKET */
2638 MUTEX_EXIT(&rx_freeCallQueue_lock);
2639 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2640 MUTEX_ENTER(&call->lock);
2641 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2642 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2643 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2645 /* Initialize once-only items */
2646 queue_Init(&call->tq);
2647 queue_Init(&call->rq);
2648 queue_Init(&call->iovq);
2649 #ifdef RXDEBUG_PACKET
2650 call->rqc = call->tqc = call->iovqc = 0;
2651 #endif /* RXDEBUG_PACKET */
2652 /* Bind the call to its connection structure (prereq for reset) */
2654 rxi_ResetCall(call, 1);
2656 call->channel = channel;
2657 call->callNumber = &conn->callNumber[channel];
2658 call->rwind = conn->rwind[channel];
2659 call->twind = conn->twind[channel];
2660 /* Note that the next expected call number is retained (in
2661 * conn->callNumber[i]), even if we reallocate the call structure
2663 conn->call[channel] = call;
2664 /* if the channel's never been used (== 0), we should start at 1, otherwise
2665 * the call number is valid from the last time this channel was used */
2666 if (*call->callNumber == 0)
2667 *call->callNumber = 1;
2672 /* A call has been inactive long enough that so we can throw away
2673 * state, including the call structure, which is placed on the call
2676 * call->lock amd rx_refcnt_mutex are held upon entry.
2677 * haveCTLock is set when called from rxi_ReapConnections.
2680 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2682 int channel = call->channel;
2683 struct rx_connection *conn = call->conn;
2686 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2687 (*call->callNumber)++;
2689 * We are setting the state to RX_STATE_RESET to
2690 * ensure that no one else will attempt to use this
2691 * call once we drop the refcnt lock. We must drop
2692 * the refcnt lock before calling rxi_ResetCall
2693 * because it cannot be held across acquiring the
2694 * freepktQ lock. NewCall does the same.
2696 call->state = RX_STATE_RESET;
2697 MUTEX_EXIT(&rx_refcnt_mutex);
2698 rxi_ResetCall(call, 0);
2700 MUTEX_ENTER(&conn->conn_call_lock);
2701 if (call->conn->call[channel] == call)
2702 call->conn->call[channel] = 0;
2703 MUTEX_EXIT(&conn->conn_call_lock);
2705 MUTEX_ENTER(&rx_freeCallQueue_lock);
2706 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2707 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2708 /* A call may be free even though its transmit queue is still in use.
2709 * Since we search the call list from head to tail, put busy calls at
2710 * the head of the list, and idle calls at the tail.
2712 if (call->flags & RX_CALL_TQ_BUSY)
2713 queue_Prepend(&rx_freeCallQueue, call);
2715 queue_Append(&rx_freeCallQueue, call);
2716 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2717 queue_Append(&rx_freeCallQueue, call);
2718 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2719 if (rx_stats_active)
2720 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2721 MUTEX_EXIT(&rx_freeCallQueue_lock);
2723 /* Destroy the connection if it was previously slated for
2724 * destruction, i.e. the Rx client code previously called
2725 * rx_DestroyConnection (client connections), or
2726 * rxi_ReapConnections called the same routine (server
2727 * connections). Only do this, however, if there are no
2728 * outstanding calls. Note that for fine grain locking, there appears
2729 * to be a deadlock in that rxi_FreeCall has a call locked and
2730 * DestroyConnectionNoLock locks each call in the conn. But note a
2731 * few lines up where we have removed this call from the conn.
2732 * If someone else destroys a connection, they either have no
2733 * call lock held or are going through this section of code.
2735 MUTEX_ENTER(&conn->conn_data_lock);
2736 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2737 MUTEX_ENTER(&rx_refcnt_mutex);
2739 MUTEX_EXIT(&rx_refcnt_mutex);
2740 MUTEX_EXIT(&conn->conn_data_lock);
2741 #ifdef RX_ENABLE_LOCKS
2743 rxi_DestroyConnectionNoLock(conn);
2745 rxi_DestroyConnection(conn);
2746 #else /* RX_ENABLE_LOCKS */
2747 rxi_DestroyConnection(conn);
2748 #endif /* RX_ENABLE_LOCKS */
2750 MUTEX_EXIT(&conn->conn_data_lock);
2752 MUTEX_ENTER(&rx_refcnt_mutex);
2755 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2756 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2759 rxi_Alloc(size_t size)
2763 if (rx_stats_active) {
2764 rx_atomic_add(&rxi_Allocsize, (int) size);
2765 rx_atomic_inc(&rxi_Alloccnt);
2769 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2770 afs_osi_Alloc_NoSleep(size);
2775 osi_Panic("rxi_Alloc error");
2781 rxi_Free(void *addr, size_t size)
2783 if (rx_stats_active) {
2784 rx_atomic_sub(&rxi_Allocsize, (int) size);
2785 rx_atomic_dec(&rxi_Alloccnt);
2787 osi_Free(addr, size);
2791 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2793 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2794 struct rx_peer *next = NULL;
2798 MUTEX_ENTER(&rx_peerHashTable_lock);
2800 peer_ptr = &rx_peerHashTable[0];
2801 peer_end = &rx_peerHashTable[rx_hashTableSize];
2804 for ( ; peer_ptr < peer_end; peer_ptr++) {
2807 for ( ; peer; peer = next) {
2809 if (host == peer->host)
2814 hashIndex = PEER_HASH(host, port);
2815 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2816 if ((peer->host == host) && (peer->port == port))
2821 MUTEX_ENTER(&rx_peerHashTable_lock);
2826 MUTEX_EXIT(&rx_peerHashTable_lock);
2828 MUTEX_ENTER(&peer->peer_lock);
2829 /* We don't handle dropping below min, so don't */
2830 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2831 peer->ifMTU=MIN(mtu, peer->ifMTU);
2832 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2833 /* if we tweaked this down, need to tune our peer MTU too */
2834 peer->MTU = MIN(peer->MTU, peer->natMTU);
2835 /* if we discovered a sub-1500 mtu, degrade */
2836 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2837 peer->maxDgramPackets = 1;
2838 /* We no longer have valid peer packet information */
2839 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2840 peer->maxPacketSize = 0;
2841 MUTEX_EXIT(&peer->peer_lock);
2843 MUTEX_ENTER(&rx_peerHashTable_lock);
2845 if (host && !port) {
2847 /* pick up where we left off */
2851 MUTEX_EXIT(&rx_peerHashTable_lock);
2854 /* Find the peer process represented by the supplied (host,port)
2855 * combination. If there is no appropriate active peer structure, a
2856 * new one will be allocated and initialized
2857 * The origPeer, if set, is a pointer to a peer structure on which the
2858 * refcount will be be decremented. This is used to replace the peer
2859 * structure hanging off a connection structure */
2861 rxi_FindPeer(afs_uint32 host, u_short port,
2862 struct rx_peer *origPeer, int create)
2866 hashIndex = PEER_HASH(host, port);
2867 MUTEX_ENTER(&rx_peerHashTable_lock);
2868 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2869 if ((pp->host == host) && (pp->port == port))
2874 pp = rxi_AllocPeer(); /* This bzero's *pp */
2875 pp->host = host; /* set here or in InitPeerParams is zero */
2877 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2878 queue_Init(&pp->congestionQueue);
2879 queue_Init(&pp->rpcStats);
2880 pp->next = rx_peerHashTable[hashIndex];
2881 rx_peerHashTable[hashIndex] = pp;
2882 rxi_InitPeerParams(pp);
2883 if (rx_stats_active)
2884 rx_atomic_inc(&rx_stats.nPeerStructs);
2891 origPeer->refCount--;
2892 MUTEX_EXIT(&rx_peerHashTable_lock);
2897 /* Find the connection at (host, port) started at epoch, and with the
2898 * given connection id. Creates the server connection if necessary.
2899 * The type specifies whether a client connection or a server
2900 * connection is desired. In both cases, (host, port) specify the
2901 * peer's (host, pair) pair. Client connections are not made
2902 * automatically by this routine. The parameter socket gives the
2903 * socket descriptor on which the packet was received. This is used,
2904 * in the case of server connections, to check that *new* connections
2905 * come via a valid (port, serviceId). Finally, the securityIndex
2906 * parameter must match the existing index for the connection. If a
2907 * server connection is created, it will be created using the supplied
2908 * index, if the index is valid for this service */
2909 struct rx_connection *
2910 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2911 u_short port, u_short serviceId, afs_uint32 cid,
2912 afs_uint32 epoch, int type, u_int securityIndex)
2914 int hashindex, flag, i;
2915 struct rx_connection *conn;
2916 hashindex = CONN_HASH(host, port, cid, epoch, type);
2917 MUTEX_ENTER(&rx_connHashTable_lock);
2918 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2919 rx_connHashTable[hashindex],
2922 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2923 && (epoch == conn->epoch)) {
2924 struct rx_peer *pp = conn->peer;
2925 if (securityIndex != conn->securityIndex) {
2926 /* this isn't supposed to happen, but someone could forge a packet
2927 * like this, and there seems to be some CM bug that makes this
2928 * happen from time to time -- in which case, the fileserver
2930 MUTEX_EXIT(&rx_connHashTable_lock);
2931 return (struct rx_connection *)0;
2933 if (pp->host == host && pp->port == port)
2935 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2937 /* So what happens when it's a callback connection? */
2938 if ( /*type == RX_CLIENT_CONNECTION && */
2939 (conn->epoch & 0x80000000))
2943 /* the connection rxLastConn that was used the last time is not the
2944 ** one we are looking for now. Hence, start searching in the hash */
2946 conn = rx_connHashTable[hashindex];
2951 struct rx_service *service;
2952 if (type == RX_CLIENT_CONNECTION) {
2953 MUTEX_EXIT(&rx_connHashTable_lock);
2954 return (struct rx_connection *)0;
2956 service = rxi_FindService(socket, serviceId);
2957 if (!service || (securityIndex >= service->nSecurityObjects)
2958 || (service->securityObjects[securityIndex] == 0)) {
2959 MUTEX_EXIT(&rx_connHashTable_lock);
2960 return (struct rx_connection *)0;
2962 conn = rxi_AllocConnection(); /* This bzero's the connection */
2963 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2964 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2965 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2966 conn->next = rx_connHashTable[hashindex];
2967 rx_connHashTable[hashindex] = conn;
2968 conn->peer = rxi_FindPeer(host, port, 0, 1);
2969 conn->type = RX_SERVER_CONNECTION;
2970 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2971 conn->epoch = epoch;
2972 conn->cid = cid & RX_CIDMASK;
2973 /* conn->serial = conn->lastSerial = 0; */
2974 /* conn->timeout = 0; */
2975 conn->ackRate = RX_FAST_ACK_RATE;
2976 conn->service = service;
2977 conn->serviceId = serviceId;
2978 conn->securityIndex = securityIndex;
2979 conn->securityObject = service->securityObjects[securityIndex];
2980 conn->nSpecific = 0;
2981 conn->specific = NULL;
2982 rx_SetConnDeadTime(conn, service->connDeadTime);
2983 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2984 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2985 for (i = 0; i < RX_MAXCALLS; i++) {
2986 conn->twind[i] = rx_initSendWindow;
2987 conn->rwind[i] = rx_initReceiveWindow;
2989 /* Notify security object of the new connection */
2990 RXS_NewConnection(conn->securityObject, conn);
2991 /* XXXX Connection timeout? */
2992 if (service->newConnProc)
2993 (*service->newConnProc) (conn);
2994 if (rx_stats_active)
2995 rx_atomic_inc(&rx_stats.nServerConns);
2998 MUTEX_ENTER(&rx_refcnt_mutex);
3000 MUTEX_EXIT(&rx_refcnt_mutex);
3002 rxLastConn = conn; /* store this connection as the last conn used */
3003 MUTEX_EXIT(&rx_connHashTable_lock);
3008 * Timeout a call on a busy call channel if appropriate.
3010 * @param[in] call The busy call.
3012 * @pre 'call' is marked as busy (namely,
3013 * call->conn->lastBusy[call->channel] != 0)
3015 * @pre call->lock is held
3016 * @pre rxi_busyChannelError is nonzero
3018 * @note call->lock is dropped and reacquired
3021 rxi_CheckBusy(struct rx_call *call)
3023 struct rx_connection *conn = call->conn;
3024 int channel = call->channel;
3025 int freechannel = 0;
3027 afs_uint32 callNumber = *call->callNumber;
3029 MUTEX_EXIT(&call->lock);
3031 MUTEX_ENTER(&conn->conn_call_lock);
3033 /* Are there any other call slots on this conn that we should try? Look for
3034 * slots that are empty and are either non-busy, or were marked as busy
3035 * longer than conn->secondsUntilDead seconds before this call started. */
3037 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
3039 /* only look at channels that aren't us */
3043 if (conn->lastBusy[i]) {
3044 /* if this channel looked busy too recently, don't look at it */
3045 if (conn->lastBusy[i] >= call->startTime.sec) {
3048 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
3053 if (conn->call[i]) {
3054 struct rx_call *tcall = conn->call[i];
3055 MUTEX_ENTER(&tcall->lock);
3056 if (tcall->state == RX_STATE_DALLY) {
3059 MUTEX_EXIT(&tcall->lock);
3065 MUTEX_EXIT(&conn->conn_call_lock);
3067 MUTEX_ENTER(&call->lock);
3069 /* Since the call->lock and conn->conn_call_lock have been released it is
3070 * possible that (1) the call may no longer be busy and/or (2) the call may
3071 * have been reused by another waiting thread. Therefore, we must confirm
3072 * that the call state has not changed when deciding whether or not to
3073 * force this application thread to retry by forcing a Timeout error. */
3075 if (freechannel && *call->callNumber == callNumber &&
3076 (call->flags & RX_CALL_PEER_BUSY)) {
3077 /* Since 'freechannel' is set, there exists another channel in this
3078 * rx_conn that the application thread might be able to use. We know
3079 * that we have the correct call since callNumber is unchanged, and we
3080 * know that the call is still busy. So, set the call error state to
3081 * rxi_busyChannelError so the application can retry the request,
3082 * presumably on a less-busy call channel. */
3084 rxi_CallError(call, rxi_busyChannelError);
3088 /* There are two packet tracing routines available for testing and monitoring
3089 * Rx. One is called just after every packet is received and the other is
3090 * called just before every packet is sent. Received packets, have had their
3091 * headers decoded, and packets to be sent have not yet had their headers
3092 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3093 * containing the network address. Both can be modified. The return value, if
3094 * non-zero, indicates that the packet should be dropped. */
3096 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3097 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3099 /* A packet has been received off the interface. Np is the packet, socket is
3100 * the socket number it was received from (useful in determining which service
3101 * this packet corresponds to), and (host, port) reflect the host,port of the
3102 * sender. This call returns the packet to the caller if it is finished with
3103 * it, rather than de-allocating it, just as a small performance hack */
3106 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3107 afs_uint32 host, u_short port, int *tnop,
3108 struct rx_call **newcallp)
3110 struct rx_call *call;
3111 struct rx_connection *conn;
3113 afs_uint32 currentCallNumber;
3119 struct rx_packet *tnp;
3122 /* We don't print out the packet until now because (1) the time may not be
3123 * accurate enough until now in the lwp implementation (rx_Listener only gets
3124 * the time after the packet is read) and (2) from a protocol point of view,
3125 * this is the first time the packet has been seen */
3126 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3127 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3128 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3129 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3130 np->header.epoch, np->header.cid, np->header.callNumber,
3131 np->header.seq, np->header.flags, np));
3134 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3135 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3138 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3139 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3142 /* If an input tracer function is defined, call it with the packet and
3143 * network address. Note this function may modify its arguments. */
3144 if (rx_justReceived) {
3145 struct sockaddr_in addr;
3147 addr.sin_family = AF_INET;
3148 addr.sin_port = port;
3149 addr.sin_addr.s_addr = host;
3150 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3151 addr.sin_len = sizeof(addr);
3152 #endif /* AFS_OSF_ENV */
3153 drop = (*rx_justReceived) (np, &addr);
3154 /* drop packet if return value is non-zero */
3157 port = addr.sin_port; /* in case fcn changed addr */
3158 host = addr.sin_addr.s_addr;
3162 /* If packet was not sent by the client, then *we* must be the client */
3163 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3164 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3166 /* Find the connection (or fabricate one, if we're the server & if
3167 * necessary) associated with this packet */
3169 rxi_FindConnection(socket, host, port, np->header.serviceId,
3170 np->header.cid, np->header.epoch, type,
3171 np->header.securityIndex);
3174 /* If no connection found or fabricated, just ignore the packet.
3175 * (An argument could be made for sending an abort packet for
3180 /* If the connection is in an error state, send an abort packet and ignore
3181 * the incoming packet */
3183 /* Don't respond to an abort packet--we don't want loops! */
3184 MUTEX_ENTER(&conn->conn_data_lock);
3185 if (np->header.type != RX_PACKET_TYPE_ABORT)
3186 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3187 putConnection(conn);
3188 MUTEX_EXIT(&conn->conn_data_lock);
3192 /* Check for connection-only requests (i.e. not call specific). */
3193 if (np->header.callNumber == 0) {
3194 switch (np->header.type) {
3195 case RX_PACKET_TYPE_ABORT: {
3196 /* What if the supplied error is zero? */
3197 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3198 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3199 rxi_ConnectionError(conn, errcode);
3200 putConnection(conn);
3203 case RX_PACKET_TYPE_CHALLENGE:
3204 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3205 putConnection(conn);
3207 case RX_PACKET_TYPE_RESPONSE:
3208 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3209 putConnection(conn);
3211 case RX_PACKET_TYPE_PARAMS:
3212 case RX_PACKET_TYPE_PARAMS + 1:
3213 case RX_PACKET_TYPE_PARAMS + 2:
3214 /* ignore these packet types for now */
3215 putConnection(conn);
3219 /* Should not reach here, unless the peer is broken: send an
3221 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3222 MUTEX_ENTER(&conn->conn_data_lock);
3223 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3224 putConnection(conn);
3225 MUTEX_EXIT(&conn->conn_data_lock);
3230 channel = np->header.cid & RX_CHANNELMASK;
3231 call = conn->call[channel];
3234 MUTEX_ENTER(&call->lock);
3235 currentCallNumber = conn->callNumber[channel];
3236 } else if (type == RX_SERVER_CONNECTION) { /* No call allocated */
3237 MUTEX_ENTER(&conn->conn_call_lock);
3238 call = conn->call[channel];
3240 MUTEX_ENTER(&call->lock);
3241 MUTEX_EXIT(&conn->conn_call_lock);
3242 currentCallNumber = conn->callNumber[channel];
3244 call = rxi_NewCall(conn, channel); /* returns locked call */
3245 MUTEX_EXIT(&conn->conn_call_lock);
3246 *call->callNumber = currentCallNumber = np->header.callNumber;
3248 if (np->header.callNumber == 0)
3249 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3250 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3251 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3252 np->header.flags, np, np->length));
3254 call->state = RX_STATE_PRECALL;
3255 clock_GetTime(&call->queueTime);
3256 hzero(call->bytesSent);
3257 hzero(call->bytesRcvd);
3259 * If the number of queued calls exceeds the overload
3260 * threshold then abort this call.
3262 if ((rx_BusyThreshold > 0) &&
3263 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3264 struct rx_packet *tp;
3266 rxi_CallError(call, rx_BusyError);
3267 tp = rxi_SendCallAbort(call, np, 1, 0);
3268 MUTEX_EXIT(&call->lock);
3269 putConnection(conn);
3270 if (rx_stats_active)
3271 rx_atomic_inc(&rx_stats.nBusies);
3274 rxi_KeepAliveOn(call);
3276 } else { /* RX_CLIENT_CONNECTION and No call allocated */
3277 /* This packet can't be for this call. If the new call address is
3278 * 0 then no call is running on this channel. If there is a call
3279 * then, since this is a client connection we're getting data for
3280 * it must be for the previous call.
3282 if (rx_stats_active)
3283 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3284 putConnection(conn);
3288 /* There is a non-NULL locked call at this point */
3289 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3290 if (np->header.callNumber < currentCallNumber) {
3291 MUTEX_EXIT(&call->lock);
3292 if (rx_stats_active)
3293 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3294 putConnection(conn);
3296 } else if (np->header.callNumber != currentCallNumber) {
3297 /* Wait until the transmit queue is idle before deciding
3298 * whether to reset the current call. Chances are that the
3299 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3302 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3303 if (call->state == RX_STATE_ACTIVE) {
3304 rxi_WaitforTQBusy(call);
3306 * If we entered error state while waiting,
3307 * must call rxi_CallError to permit rxi_ResetCall
3308 * to processed when the tqWaiter count hits zero.
3311 rxi_CallError(call, call->error);
3312 MUTEX_EXIT(&call->lock);
3313 putConnection(conn);
3317 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3318 /* If the new call cannot be taken right now send a busy and set
3319 * the error condition in this call, so that it terminates as
3320 * quickly as possible */
3321 if (call->state == RX_STATE_ACTIVE) {
3322 struct rx_packet *tp;
3324 rxi_CallError(call, RX_CALL_DEAD);
3325 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3327 MUTEX_EXIT(&call->lock);
3328 putConnection(conn);
3331 rxi_ResetCall(call, 0);
3332 *call->callNumber = np->header.callNumber;
3334 if (np->header.callNumber == 0)
3335 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3336 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3337 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3338 np->header.flags, np, np->length));
3340 call->state = RX_STATE_PRECALL;
3341 clock_GetTime(&call->queueTime);
3342 hzero(call->bytesSent);
3343 hzero(call->bytesRcvd);
3345 * If the number of queued calls exceeds the overload
3346 * threshold then abort this call.
3348 if ((rx_BusyThreshold > 0) &&
3349 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3350 struct rx_packet *tp;
3352 rxi_CallError(call, rx_BusyError);
3353 tp = rxi_SendCallAbort(call, np, 1, 0);
3354 MUTEX_EXIT(&call->lock);
3355 putConnection(conn);
3356 if (rx_stats_active)
3357 rx_atomic_inc(&rx_stats.nBusies);
3360 rxi_KeepAliveOn(call);
3362 /* Continuing call; do nothing here. */
3364 } else { /* we're the client */
3365 /* Ignore all incoming acknowledgements for calls in DALLY state */
3366 if ((call->state == RX_STATE_DALLY)
3367 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3368 if (rx_stats_active)
3369 rx_atomic_inc(&rx_stats.ignorePacketDally);
3370 MUTEX_EXIT(&call->lock);
3371 putConnection(conn);
3375 /* Ignore anything that's not relevant to the current call. If there
3376 * isn't a current call, then no packet is relevant. */
3377 if (np->header.callNumber != currentCallNumber) {
3378 if (rx_stats_active)
3379 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3380 MUTEX_EXIT(&call->lock);
3381 putConnection(conn);
3384 /* If the service security object index stamped in the packet does not
3385 * match the connection's security index, ignore the packet */
3386 if (np->header.securityIndex != conn->securityIndex) {
3387 MUTEX_EXIT(&call->lock);
3388 putConnection(conn);
3392 /* If we're receiving the response, then all transmit packets are
3393 * implicitly acknowledged. Get rid of them. */
3394 if (np->header.type == RX_PACKET_TYPE_DATA) {
3395 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3396 /* XXX Hack. Because we must release the global rx lock when
3397 * sending packets (osi_NetSend) we drop all acks while we're
3398 * traversing the tq in rxi_Start sending packets out because
3399 * packets may move to the freePacketQueue as result of being here!
3400 * So we drop these packets until we're safely out of the
3401 * traversing. Really ugly!
3402 * For fine grain RX locking, we set the acked field in the
3403 * packets and let rxi_Start remove them from the transmit queue.
3405 if (call->flags & RX_CALL_TQ_BUSY) {
3406 #ifdef RX_ENABLE_LOCKS
3407 rxi_SetAcksInTransmitQueue(call);
3409 putConnection(conn);
3410 return np; /* xmitting; drop packet */
3413 rxi_ClearTransmitQueue(call, 0);
3415 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3416 rxi_ClearTransmitQueue(call, 0);
3417 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3419 if (np->header.type == RX_PACKET_TYPE_ACK) {
3420 /* now check to see if this is an ack packet acknowledging that the
3421 * server actually *lost* some hard-acked data. If this happens we
3422 * ignore this packet, as it may indicate that the server restarted in
3423 * the middle of a call. It is also possible that this is an old ack
3424 * packet. We don't abort the connection in this case, because this
3425 * *might* just be an old ack packet. The right way to detect a server
3426 * restart in the midst of a call is to notice that the server epoch
3428 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3429 * XXX unacknowledged. I think that this is off-by-one, but
3430 * XXX I don't dare change it just yet, since it will
3431 * XXX interact badly with the server-restart detection
3432 * XXX code in receiveackpacket. */
3433 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3434 if (rx_stats_active)
3435 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3436 MUTEX_EXIT(&call->lock);
3437 putConnection(conn);
3441 } /* else not a data packet */
3444 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3445 /* Set remote user defined status from packet */
3446 call->remoteStatus = np->header.userStatus;
3448 /* Note the gap between the expected next packet and the actual
3449 * packet that arrived, when the new packet has a smaller serial number
3450 * than expected. Rioses frequently reorder packets all by themselves,
3451 * so this will be quite important with very large window sizes.
3452 * Skew is checked against 0 here to avoid any dependence on the type of
3453 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3455 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3456 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3457 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3459 MUTEX_ENTER(&conn->conn_data_lock);
3460 skew = conn->lastSerial - np->header.serial;
3461 conn->lastSerial = np->header.serial;
3462 MUTEX_EXIT(&conn->conn_data_lock);
3464 struct rx_peer *peer;
3466 if (skew > peer->inPacketSkew) {
3467 dpf(("*** In skew changed from %d to %d\n",
3468 peer->inPacketSkew, skew));
3469 peer->inPacketSkew = skew;
3473 /* Now do packet type-specific processing */
3474 switch (np->header.type) {
3475 case RX_PACKET_TYPE_DATA:
3476 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3479 case RX_PACKET_TYPE_ACK:
3480 /* Respond immediately to ack packets requesting acknowledgement
3482 if (np->header.flags & RX_REQUEST_ACK) {
3484 (void)rxi_SendCallAbort(call, 0, 1, 0);
3486 (void)rxi_SendAck(call, 0, np->header.serial,
3487 RX_ACK_PING_RESPONSE, 1);
3489 np = rxi_ReceiveAckPacket(call, np, 1);
3491 case RX_PACKET_TYPE_ABORT: {
3492 /* An abort packet: reset the call, passing the error up to the user. */
3493 /* What if error is zero? */
3494 /* What if the error is -1? the application will treat it as a timeout. */
3495 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3496 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3497 rxi_CallError(call, errdata);
3498 MUTEX_EXIT(&call->lock);
3499 putConnection(conn);
3500 return np; /* xmitting; drop packet */
3502 case RX_PACKET_TYPE_BUSY: {
3503 struct clock busyTime;
3505 clock_GetTime(&busyTime);
3507 MUTEX_EXIT(&call->lock);
3509 MUTEX_ENTER(&conn->conn_call_lock);
3510 MUTEX_ENTER(&call->lock);
3511 conn->lastBusy[call->channel] = busyTime.sec;
3512 call->flags |= RX_CALL_PEER_BUSY;
3513 MUTEX_EXIT(&call->lock);
3514 MUTEX_EXIT(&conn->conn_call_lock);
3516 putConnection(conn);
3520 case RX_PACKET_TYPE_ACKALL:
3521 /* All packets acknowledged, so we can drop all packets previously
3522 * readied for sending */
3523 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3524 /* XXX Hack. We because we can't release the global rx lock when
3525 * sending packets (osi_NetSend) we drop all ack pkts while we're
3526 * traversing the tq in rxi_Start sending packets out because
3527 * packets may move to the freePacketQueue as result of being
3528 * here! So we drop these packets until we're safely out of the
3529 * traversing. Really ugly!
3530 * For fine grain RX locking, we set the acked field in the packets
3531 * and let rxi_Start remove the packets from the transmit queue.
3533 if (call->flags & RX_CALL_TQ_BUSY) {
3534 #ifdef RX_ENABLE_LOCKS
3535 rxi_SetAcksInTransmitQueue(call);
3537 #else /* RX_ENABLE_LOCKS */
3538 MUTEX_EXIT(&call->lock);
3539 putConnection(conn);
3540 return np; /* xmitting; drop packet */
3541 #endif /* RX_ENABLE_LOCKS */
3543 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3544 rxi_ClearTransmitQueue(call, 0);
3547 /* Should not reach here, unless the peer is broken: send an abort
3549 rxi_CallError(call, RX_PROTOCOL_ERROR);
3550 np = rxi_SendCallAbort(call, np, 1, 0);
3553 /* Note when this last legitimate packet was received, for keep-alive
3554 * processing. Note, we delay getting the time until now in the hope that
3555 * the packet will be delivered to the user before any get time is required
3556 * (if not, then the time won't actually be re-evaluated here). */
3557 call->lastReceiveTime = clock_Sec();
3558 /* we've received a legit packet, so the channel is not busy */
3559 call->flags &= ~RX_CALL_PEER_BUSY;
3560 MUTEX_EXIT(&call->lock);
3561 putConnection(conn);
3565 /* return true if this is an "interesting" connection from the point of view
3566 of someone trying to debug the system */
3568 rxi_IsConnInteresting(struct rx_connection *aconn)
3571 struct rx_call *tcall;
3573 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3576 for (i = 0; i < RX_MAXCALLS; i++) {
3577 tcall = aconn->call[i];
3579 if ((tcall->state == RX_STATE_PRECALL)
3580 || (tcall->state == RX_STATE_ACTIVE))
3582 if ((tcall->mode == RX_MODE_SENDING)
3583 || (tcall->mode == RX_MODE_RECEIVING))
3591 /* if this is one of the last few packets AND it wouldn't be used by the
3592 receiving call to immediately satisfy a read request, then drop it on
3593 the floor, since accepting it might prevent a lock-holding thread from
3594 making progress in its reading. If a call has been cleared while in
3595 the precall state then ignore all subsequent packets until the call
3596 is assigned to a thread. */
3599 TooLow(struct rx_packet *ap, struct rx_call *acall)
3603 MUTEX_ENTER(&rx_quota_mutex);
3604 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3605 && (acall->state == RX_STATE_PRECALL))
3606 || ((rx_nFreePackets < rxi_dataQuota + 2)
3607 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3608 && (acall->flags & RX_CALL_READER_WAIT)))) {
3611 MUTEX_EXIT(&rx_quota_mutex);
3617 * Clear the attach wait flag on a connection and proceed.
3619 * Any processing waiting for a connection to be attached should be
3620 * unblocked. We clear the flag and do any other needed tasks.
3623 * the conn to unmark waiting for attach
3625 * @pre conn's conn_data_lock must be locked before calling this function
3629 rxi_ConnClearAttachWait(struct rx_connection *conn)
3631 /* Indicate that rxi_CheckReachEvent is no longer running by
3632 * clearing the flag. Must be atomic under conn_data_lock to
3633 * avoid a new call slipping by: rxi_CheckConnReach holds
3634 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3636 conn->flags &= ~RX_CONN_ATTACHWAIT;
3637 if (conn->flags & RX_CONN_NAT_PING) {
3638 conn->flags &= ~RX_CONN_NAT_PING;
3639 rxi_ScheduleNatKeepAliveEvent(conn);
3644 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3646 struct rx_connection *conn = arg1;
3647 struct rx_call *acall = arg2;
3648 struct rx_call *call = acall;
3649 struct clock when, now;
3652 MUTEX_ENTER(&conn->conn_data_lock);
3655 rxevent_Put(conn->checkReachEvent);
3656 conn->checkReachEvent = NULL;
3659 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3661 putConnection(conn);
3663 MUTEX_EXIT(&conn->conn_data_lock);
3667 MUTEX_ENTER(&conn->conn_call_lock);
3668 MUTEX_ENTER(&conn->conn_data_lock);
3669 for (i = 0; i < RX_MAXCALLS; i++) {
3670 struct rx_call *tc = conn->call[i];
3671 if (tc && tc->state == RX_STATE_PRECALL) {
3677 rxi_ConnClearAttachWait(conn);
3678 MUTEX_EXIT(&conn->conn_data_lock);
3679 MUTEX_EXIT(&conn->conn_call_lock);
3684 MUTEX_ENTER(&call->lock);
3685 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3687 MUTEX_EXIT(&call->lock);
3689 clock_GetTime(&now);
3691 when.sec += RX_CHECKREACH_TIMEOUT;
3692 MUTEX_ENTER(&conn->conn_data_lock);
3693 if (!conn->checkReachEvent) {
3694 MUTEX_ENTER(&rx_refcnt_mutex);
3696 MUTEX_EXIT(&rx_refcnt_mutex);
3697 conn->checkReachEvent = rxevent_Post(&when, &now,
3698 rxi_CheckReachEvent, conn,
3701 MUTEX_EXIT(&conn->conn_data_lock);
3707 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3709 struct rx_service *service = conn->service;
3710 struct rx_peer *peer = conn->peer;
3711 afs_uint32 now, lastReach;
3713 if (service->checkReach == 0)
3717 MUTEX_ENTER(&peer->peer_lock);
3718 lastReach = peer->lastReachTime;
3719 MUTEX_EXIT(&peer->peer_lock);
3720 if (now - lastReach < RX_CHECKREACH_TTL)
3723 MUTEX_ENTER(&conn->conn_data_lock);
3724 if (conn->flags & RX_CONN_ATTACHWAIT) {
3725 MUTEX_EXIT(&conn->conn_data_lock);
3728 conn->flags |= RX_CONN_ATTACHWAIT;
3729 MUTEX_EXIT(&conn->conn_data_lock);
3730 if (!conn->checkReachEvent)
3731 rxi_CheckReachEvent(NULL, conn, call, 0);
3736 /* try to attach call, if authentication is complete */
3738 TryAttach(struct rx_call *acall, osi_socket socket,
3739 int *tnop, struct rx_call **newcallp,
3742 struct rx_connection *conn = acall->conn;
3744 if (conn->type == RX_SERVER_CONNECTION
3745 && acall->state == RX_STATE_PRECALL) {
3746 /* Don't attach until we have any req'd. authentication. */
3747 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3748 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3749 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3750 /* Note: this does not necessarily succeed; there
3751 * may not any proc available
3754 rxi_ChallengeOn(acall->conn);
3759 /* A data packet has been received off the interface. This packet is
3760 * appropriate to the call (the call is in the right state, etc.). This
3761 * routine can return a packet to the caller, for re-use */
3764 rxi_ReceiveDataPacket(struct rx_call *call,
3765 struct rx_packet *np, int istack,
3766 osi_socket socket, afs_uint32 host, u_short port,
3767 int *tnop, struct rx_call **newcallp)
3769 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3774 afs_uint32 serial=0, flags=0;
3776 struct rx_packet *tnp;
3777 if (rx_stats_active)
3778 rx_atomic_inc(&rx_stats.dataPacketsRead);
3781 /* If there are no packet buffers, drop this new packet, unless we can find
3782 * packet buffers from inactive calls */
3784 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3785 MUTEX_ENTER(&rx_freePktQ_lock);
3786 rxi_NeedMorePackets = TRUE;
3787 MUTEX_EXIT(&rx_freePktQ_lock);
3788 if (rx_stats_active)
3789 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3790 call->rprev = np->header.serial;
3791 rxi_calltrace(RX_TRACE_DROP, call);
3792 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3793 /* We used to clear the receive queue here, in an attempt to free
3794 * packets. However this is unsafe if the queue has received a
3795 * soft ACK for the final packet */
3796 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3798 /* we've damaged this call already, might as well do it in. */
3804 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3805 * packet is one of several packets transmitted as a single
3806 * datagram. Do not send any soft or hard acks until all packets
3807 * in a jumbogram have been processed. Send negative acks right away.
3809 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3810 /* tnp is non-null when there are more packets in the
3811 * current jumbo gram */
3818 seq = np->header.seq;
3819 serial = np->header.serial;
3820 flags = np->header.flags;
3822 /* If the call is in an error state, send an abort message */
3824 return rxi_SendCallAbort(call, np, istack, 0);
3826 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3827 * AFS 3.5 jumbogram. */
3828 if (flags & RX_JUMBO_PACKET) {
3829 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3834 if (np->header.spare != 0) {
3835 MUTEX_ENTER(&call->conn->conn_data_lock);
3836 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3837 MUTEX_EXIT(&call->conn->conn_data_lock);
3840 /* The usual case is that this is the expected next packet */
3841 if (seq == call->rnext) {
3843 /* Check to make sure it is not a duplicate of one already queued */
3844 if (queue_IsNotEmpty(&call->rq)
3845 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3846 if (rx_stats_active)
3847 rx_atomic_inc(&rx_stats.dupPacketsRead);
3848 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3849 rxevent_Cancel(&call->delayedAckEvent, call,
3850 RX_CALL_REFCOUNT_DELAY);
3851 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3857 /* It's the next packet. Stick it on the receive queue
3858 * for this call. Set newPackets to make sure we wake
3859 * the reader once all packets have been processed */
3860 #ifdef RX_TRACK_PACKETS
3861 np->flags |= RX_PKTFLAG_RQ;
3863 queue_Prepend(&call->rq, np);
3864 #ifdef RXDEBUG_PACKET
3866 #endif /* RXDEBUG_PACKET */
3868 np = NULL; /* We can't use this anymore */
3871 /* If an ack is requested then set a flag to make sure we
3872 * send an acknowledgement for this packet */
3873 if (flags & RX_REQUEST_ACK) {
3874 ackNeeded = RX_ACK_REQUESTED;
3877 /* Keep track of whether we have received the last packet */
3878 if (flags & RX_LAST_PACKET) {
3879 call->flags |= RX_CALL_HAVE_LAST;
3883 /* Check whether we have all of the packets for this call */
3884 if (call->flags & RX_CALL_HAVE_LAST) {
3885 afs_uint32 tseq; /* temporary sequence number */
3886 struct rx_packet *tp; /* Temporary packet pointer */
3887 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3889 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3890 if (tseq != tp->header.seq)
3892 if (tp->header.flags & RX_LAST_PACKET) {
3893 call->flags |= RX_CALL_RECEIVE_DONE;
3900 /* Provide asynchronous notification for those who want it
3901 * (e.g. multi rx) */
3902 if (call->arrivalProc) {
3903 (*call->arrivalProc) (call, call->arrivalProcHandle,
3904 call->arrivalProcArg);
3905 call->arrivalProc = (void (*)())0;
3908 /* Update last packet received */
3911 /* If there is no server process serving this call, grab
3912 * one, if available. We only need to do this once. If a
3913 * server thread is available, this thread becomes a server
3914 * thread and the server thread becomes a listener thread. */
3916 TryAttach(call, socket, tnop, newcallp, 0);
3919 /* This is not the expected next packet. */
3921 /* Determine whether this is a new or old packet, and if it's
3922 * a new one, whether it fits into the current receive window.
3923 * Also figure out whether the packet was delivered in sequence.
3924 * We use the prev variable to determine whether the new packet
3925 * is the successor of its immediate predecessor in the
3926 * receive queue, and the missing flag to determine whether
3927 * any of this packets predecessors are missing. */
3929 afs_uint32 prev; /* "Previous packet" sequence number */
3930 struct rx_packet *tp; /* Temporary packet pointer */
3931 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3932 int missing; /* Are any predecessors missing? */
3934 /* If the new packet's sequence number has been sent to the
3935 * application already, then this is a duplicate */
3936 if (seq < call->rnext) {
3937 if (rx_stats_active)
3938 rx_atomic_inc(&rx_stats.dupPacketsRead);
3939 rxevent_Cancel(&call->delayedAckEvent, call,
3940 RX_CALL_REFCOUNT_DELAY);
3941 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3947 /* If the sequence number is greater than what can be
3948 * accomodated by the current window, then send a negative
3949 * acknowledge and drop the packet */
3950 if ((call->rnext + call->rwind) <= seq) {
3951 rxevent_Cancel(&call->delayedAckEvent, call,
3952 RX_CALL_REFCOUNT_DELAY);
3953 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3960 /* Look for the packet in the queue of old received packets */
3961 for (prev = call->rnext - 1, missing =
3962 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3963 /*Check for duplicate packet */
3964 if (seq == tp->header.seq) {
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,
3975 /* If we find a higher sequence packet, break out and
3976 * insert the new packet here. */
3977 if (seq < tp->header.seq)
3979 /* Check for missing packet */
3980 if (tp->header.seq != prev + 1) {
3984 prev = tp->header.seq;
3987 /* Keep track of whether we have received the last packet. */
3988 if (flags & RX_LAST_PACKET) {
3989 call->flags |= RX_CALL_HAVE_LAST;
3992 /* It's within the window: add it to the the receive queue.
3993 * tp is left by the previous loop either pointing at the
3994 * packet before which to insert the new packet, or at the
3995 * queue head if the queue is empty or the packet should be
3997 #ifdef RX_TRACK_PACKETS
3998 np->flags |= RX_PKTFLAG_RQ;
4000 #ifdef RXDEBUG_PACKET
4002 #endif /* RXDEBUG_PACKET */
4003 queue_InsertBefore(tp, np);
4007 /* Check whether we have all of the packets for this call */
4008 if ((call->flags & RX_CALL_HAVE_LAST)
4009 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4010 afs_uint32 tseq; /* temporary sequence number */
4013 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4014 if (tseq != tp->header.seq)
4016 if (tp->header.flags & RX_LAST_PACKET) {
4017 call->flags |= RX_CALL_RECEIVE_DONE;
4024 /* We need to send an ack of the packet is out of sequence,
4025 * or if an ack was requested by the peer. */
4026 if (seq != prev + 1 || missing) {
4027 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4028 } else if (flags & RX_REQUEST_ACK) {
4029 ackNeeded = RX_ACK_REQUESTED;
4032 /* Acknowledge the last packet for each call */
4033 if (flags & RX_LAST_PACKET) {
4044 * If the receiver is waiting for an iovec, fill the iovec
4045 * using the data from the receive queue */
4046 if (call->flags & RX_CALL_IOVEC_WAIT) {
4047 didHardAck = rxi_FillReadVec(call, serial);
4048 /* the call may have been aborted */
4057 /* Wakeup the reader if any */
4058 if ((call->flags & RX_CALL_READER_WAIT)
4059 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4060 || (call->iovNext >= call->iovMax)
4061 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4062 call->flags &= ~RX_CALL_READER_WAIT;
4063 #ifdef RX_ENABLE_LOCKS
4064 CV_BROADCAST(&call->cv_rq);
4066 osi_rxWakeup(&call->rq);
4072 * Send an ack when requested by the peer, or once every
4073 * rxi_SoftAckRate packets until the last packet has been
4074 * received. Always send a soft ack for the last packet in
4075 * the server's reply. */
4077 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4078 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4079 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4080 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4081 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4082 } else if (call->nSoftAcks) {
4083 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4084 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4086 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4087 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4088 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4095 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4097 struct rx_peer *peer = conn->peer;
4099 MUTEX_ENTER(&peer->peer_lock);
4100 peer->lastReachTime = clock_Sec();
4101 MUTEX_EXIT(&peer->peer_lock);
4103 MUTEX_ENTER(&conn->conn_data_lock);
4104 if (conn->flags & RX_CONN_ATTACHWAIT) {
4107 rxi_ConnClearAttachWait(conn);
4108 MUTEX_EXIT(&conn->conn_data_lock);
4110 for (i = 0; i < RX_MAXCALLS; i++) {
4111 struct rx_call *call = conn->call[i];
4114 MUTEX_ENTER(&call->lock);
4115 /* tnop can be null if newcallp is null */
4116 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4118 MUTEX_EXIT(&call->lock);
4122 MUTEX_EXIT(&conn->conn_data_lock);
4125 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4127 rx_ack_reason(int reason)
4130 case RX_ACK_REQUESTED:
4132 case RX_ACK_DUPLICATE:
4134 case RX_ACK_OUT_OF_SEQUENCE:
4136 case RX_ACK_EXCEEDS_WINDOW:
4138 case RX_ACK_NOSPACE:
4142 case RX_ACK_PING_RESPONSE:
4155 /* The real smarts of the whole thing. */
4157 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4160 struct rx_ackPacket *ap;
4162 struct rx_packet *tp;
4163 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4164 struct rx_connection *conn = call->conn;
4165 struct rx_peer *peer = conn->peer;
4166 struct clock now; /* Current time, for RTT calculations */
4170 /* because there are CM's that are bogus, sending weird values for this. */
4171 afs_uint32 skew = 0;
4176 int newAckCount = 0;
4177 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4178 int pktsize = 0; /* Set if we need to update the peer mtu */
4179 int conn_data_locked = 0;
4181 if (rx_stats_active)
4182 rx_atomic_inc(&rx_stats.ackPacketsRead);
4183 ap = (struct rx_ackPacket *)rx_DataOf(np);
4184 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4186 return np; /* truncated ack packet */
4188 /* depends on ack packet struct */
4189 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4190 first = ntohl(ap->firstPacket);
4191 prev = ntohl(ap->previousPacket);
4192 serial = ntohl(ap->serial);
4193 /* temporarily disabled -- needs to degrade over time
4194 * skew = ntohs(ap->maxSkew); */
4196 /* Ignore ack packets received out of order */
4197 if (first < call->tfirst ||
4198 (first == call->tfirst && prev < call->tprev)) {
4204 if (np->header.flags & RX_SLOW_START_OK) {
4205 call->flags |= RX_CALL_SLOW_START_OK;
4208 if (ap->reason == RX_ACK_PING_RESPONSE)
4209 rxi_UpdatePeerReach(conn, call);
4211 if (conn->lastPacketSizeSeq) {
4212 MUTEX_ENTER(&conn->conn_data_lock);
4213 conn_data_locked = 1;
4214 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4215 pktsize = conn->lastPacketSize;
4216 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4219 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4220 if (!conn_data_locked) {
4221 MUTEX_ENTER(&conn->conn_data_lock);
4222 conn_data_locked = 1;
4224 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4225 /* process mtu ping ack */
4226 pktsize = conn->lastPingSize;
4227 conn->lastPingSizeSer = conn->lastPingSize = 0;
4231 if (conn_data_locked) {
4232 MUTEX_EXIT(&conn->conn_data_lock);
4233 conn_data_locked = 0;
4237 if (rxdebug_active) {
4241 len = _snprintf(msg, sizeof(msg),
4242 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4243 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4244 ntohl(ap->serial), ntohl(ap->previousPacket),
4245 (unsigned int)np->header.seq, (unsigned int)skew,
4246 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4250 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4251 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4255 OutputDebugString(msg);
4257 #else /* AFS_NT40_ENV */
4260 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4261 ap->reason, ntohl(ap->previousPacket),
4262 (unsigned int)np->header.seq, (unsigned int)serial,
4263 (unsigned int)skew, ntohl(ap->firstPacket));
4266 for (offset = 0; offset < nAcks; offset++)
4267 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4272 #endif /* AFS_NT40_ENV */
4275 MUTEX_ENTER(&peer->peer_lock);
4278 * Start somewhere. Can't assume we can send what we can receive,
4279 * but we are clearly receiving.
4281 if (!peer->maxPacketSize)
4282 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4284 if (pktsize > peer->maxPacketSize) {
4285 peer->maxPacketSize = pktsize;
4286 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4287 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4288 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4289 rxi_ScheduleGrowMTUEvent(call, 1);
4294 /* Update the outgoing packet skew value to the latest value of
4295 * the peer's incoming packet skew value. The ack packet, of
4296 * course, could arrive out of order, but that won't affect things
4298 peer->outPacketSkew = skew;
4301 clock_GetTime(&now);
4303 /* The transmit queue splits into 4 sections.
4305 * The first section is packets which have now been acknowledged
4306 * by a window size change in the ack. These have reached the
4307 * application layer, and may be discarded. These are packets
4308 * with sequence numbers < ap->firstPacket.
4310 * The second section is packets which have sequence numbers in
4311 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4312 * contents of the packet's ack array determines whether these
4313 * packets are acknowledged or not.
4315 * The third section is packets which fall above the range
4316 * addressed in the ack packet. These have not yet been received
4319 * The four section is packets which have not yet been transmitted.
4320 * These packets will have a header.serial of 0.
4323 /* First section - implicitly acknowledged packets that can be
4327 tp = queue_First(&call->tq, rx_packet);
4328 while(!queue_IsEnd(&call->tq, tp) && tp->header.seq < first) {
4329 struct rx_packet *next;
4331 next = queue_Next(tp, rx_packet);
4332 call->tfirst = tp->header.seq + 1;
4334 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4336 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4339 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4340 /* XXX Hack. Because we have to release the global rx lock when sending
4341 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4342 * in rxi_Start sending packets out because packets may move to the
4343 * freePacketQueue as result of being here! So we drop these packets until
4344 * we're safely out of the traversing. Really ugly!
4345 * To make it even uglier, if we're using fine grain locking, we can
4346 * set the ack bits in the packets and have rxi_Start remove the packets
4347 * when it's done transmitting.
4349 if (call->flags & RX_CALL_TQ_BUSY) {
4350 #ifdef RX_ENABLE_LOCKS
4351 tp->flags |= RX_PKTFLAG_ACKED;
4352 call->flags |= RX_CALL_TQ_SOME_ACKED;
4353 #else /* RX_ENABLE_LOCKS */
4355 #endif /* RX_ENABLE_LOCKS */
4357 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4360 #ifdef RX_TRACK_PACKETS
4361 tp->flags &= ~RX_PKTFLAG_TQ;
4363 #ifdef RXDEBUG_PACKET
4365 #endif /* RXDEBUG_PACKET */
4366 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4371 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4373 /* Second section of the queue - packets for which we are receiving
4376 * Go through the explicit acks/nacks and record the results in
4377 * the waiting packets. These are packets that can't be released
4378 * yet, even with a positive acknowledge. This positive
4379 * acknowledge only means the packet has been received by the
4380 * peer, not that it will be retained long enough to be sent to
4381 * the peer's upper level. In addition, reset the transmit timers
4382 * of any missing packets (those packets that must be missing
4383 * because this packet was out of sequence) */
4385 call->nSoftAcked = 0;
4387 while (!queue_IsEnd(&call->tq, tp) && tp->header.seq < first + nAcks) {
4388 /* Set the acknowledge flag per packet based on the
4389 * information in the ack packet. An acknowlegded packet can
4390 * be downgraded when the server has discarded a packet it
4391 * soacked previously, or when an ack packet is received
4392 * out of sequence. */
4393 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4394 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4396 tp->flags |= RX_PKTFLAG_ACKED;
4397 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4404 } else /* RX_ACK_TYPE_NACK */ {
4405 tp->flags &= ~RX_PKTFLAG_ACKED;
4409 tp = queue_Next(tp, rx_packet);
4412 /* We don't need to take any action with the 3rd or 4th section in the
4413 * queue - they're not addressed by the contents of this ACK packet.
4416 /* If the window has been extended by this acknowledge packet,
4417 * then wakeup a sender waiting in alloc for window space, or try
4418 * sending packets now, if he's been sitting on packets due to
4419 * lack of window space */
4420 if (call->tnext < (call->tfirst + call->twind)) {
4421 #ifdef RX_ENABLE_LOCKS
4422 CV_SIGNAL(&call->cv_twind);
4424 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4425 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4426 osi_rxWakeup(&call->twind);
4429 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4430 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4434 /* if the ack packet has a receivelen field hanging off it,
4435 * update our state */
4436 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4439 /* If the ack packet has a "recommended" size that is less than
4440 * what I am using now, reduce my size to match */
4441 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4442 (int)sizeof(afs_int32), &tSize);
4443 tSize = (afs_uint32) ntohl(tSize);
4444 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4446 /* Get the maximum packet size to send to this peer */
4447 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4449 tSize = (afs_uint32) ntohl(tSize);
4450 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4451 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4453 /* sanity check - peer might have restarted with different params.
4454 * If peer says "send less", dammit, send less... Peer should never
4455 * be unable to accept packets of the size that prior AFS versions would
4456 * send without asking. */
4457 if (peer->maxMTU != tSize) {
4458 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4460 peer->maxMTU = tSize;
4461 peer->MTU = MIN(tSize, peer->MTU);
4462 call->MTU = MIN(call->MTU, tSize);
4465 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4468 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4469 (int)sizeof(afs_int32), &tSize);
4470 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4471 if (tSize < call->twind) { /* smaller than our send */
4472 call->twind = tSize; /* window, we must send less... */
4473 call->ssthresh = MIN(call->twind, call->ssthresh);
4474 call->conn->twind[call->channel] = call->twind;
4477 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4478 * network MTU confused with the loopback MTU. Calculate the
4479 * maximum MTU here for use in the slow start code below.
4481 /* Did peer restart with older RX version? */
4482 if (peer->maxDgramPackets > 1) {
4483 peer->maxDgramPackets = 1;
4485 } else if (np->length >=
4486 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4489 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4490 sizeof(afs_int32), &tSize);
4491 tSize = (afs_uint32) ntohl(tSize);
4493 * As of AFS 3.5 we set the send window to match the receive window.
4495 if (tSize < call->twind) {
4496 call->twind = tSize;
4497 call->conn->twind[call->channel] = call->twind;
4498 call->ssthresh = MIN(call->twind, call->ssthresh);
4499 } else if (tSize > call->twind) {
4500 call->twind = tSize;
4501 call->conn->twind[call->channel] = call->twind;
4505 * As of AFS 3.5, a jumbogram is more than one fixed size
4506 * packet transmitted in a single UDP datagram. If the remote
4507 * MTU is smaller than our local MTU then never send a datagram
4508 * larger than the natural MTU.
4511 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4512 (int)sizeof(afs_int32), &tSize);
4513 maxDgramPackets = (afs_uint32) ntohl(tSize);
4514 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4516 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4517 if (maxDgramPackets > 1) {
4518 peer->maxDgramPackets = maxDgramPackets;
4519 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4521 peer->maxDgramPackets = 1;
4522 call->MTU = peer->natMTU;
4524 } else if (peer->maxDgramPackets > 1) {
4525 /* Restarted with lower version of RX */
4526 peer->maxDgramPackets = 1;
4528 } else if (peer->maxDgramPackets > 1
4529 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4530 /* Restarted with lower version of RX */
4531 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4532 peer->natMTU = OLD_MAX_PACKET_SIZE;
4533 peer->MTU = OLD_MAX_PACKET_SIZE;
4534 peer->maxDgramPackets = 1;
4535 peer->nDgramPackets = 1;
4537 call->MTU = OLD_MAX_PACKET_SIZE;
4542 * Calculate how many datagrams were successfully received after
4543 * the first missing packet and adjust the negative ack counter
4548 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4549 if (call->nNacks < nNacked) {
4550 call->nNacks = nNacked;
4553 call->nAcks += newAckCount;
4557 /* If the packet contained new acknowledgements, rather than just
4558 * being a duplicate of one we have previously seen, then we can restart
4561 if (newAckCount > 0)
4562 rxi_rto_packet_acked(call, istack);
4564 if (call->flags & RX_CALL_FAST_RECOVER) {
4565 if (newAckCount == 0) {
4566 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4568 call->flags &= ~RX_CALL_FAST_RECOVER;
4569 call->cwind = call->nextCwind;
4570 call->nextCwind = 0;
4573 call->nCwindAcks = 0;
4574 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4575 /* Three negative acks in a row trigger congestion recovery */
4576 call->flags |= RX_CALL_FAST_RECOVER;
4577 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4579 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4580 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4581 call->nextCwind = call->ssthresh;
4584 peer->MTU = call->MTU;
4585 peer->cwind = call->nextCwind;
4586 peer->nDgramPackets = call->nDgramPackets;
4588 call->congestSeq = peer->congestSeq;
4590 /* Reset the resend times on the packets that were nacked
4591 * so we will retransmit as soon as the window permits
4594 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4596 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4597 tp->flags &= ~RX_PKTFLAG_SENT;
4599 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4604 /* If cwind is smaller than ssthresh, then increase
4605 * the window one packet for each ack we receive (exponential
4607 * If cwind is greater than or equal to ssthresh then increase
4608 * the congestion window by one packet for each cwind acks we
4609 * receive (linear growth). */
4610 if (call->cwind < call->ssthresh) {
4612 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4613 call->nCwindAcks = 0;
4615 call->nCwindAcks += newAckCount;
4616 if (call->nCwindAcks >= call->cwind) {
4617 call->nCwindAcks = 0;
4618 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4622 * If we have received several acknowledgements in a row then
4623 * it is time to increase the size of our datagrams
4625 if ((int)call->nAcks > rx_nDgramThreshold) {
4626 if (peer->maxDgramPackets > 1) {
4627 if (call->nDgramPackets < peer->maxDgramPackets) {
4628 call->nDgramPackets++;
4630 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4631 } else if (call->MTU < peer->maxMTU) {
4632 /* don't upgrade if we can't handle it */
4633 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4634 call->MTU = peer->ifMTU;
4636 call->MTU += peer->natMTU;
4637 call->MTU = MIN(call->MTU, peer->maxMTU);
4644 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4646 /* Servers need to hold the call until all response packets have
4647 * been acknowledged. Soft acks are good enough since clients
4648 * are not allowed to clear their receive queues. */
4649 if (call->state == RX_STATE_HOLD
4650 && call->tfirst + call->nSoftAcked >= call->tnext) {
4651 call->state = RX_STATE_DALLY;
4652 rxi_ClearTransmitQueue(call, 0);
4653 rxevent_Cancel(&call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4654 } else if (!queue_IsEmpty(&call->tq)) {
4655 rxi_Start(call, istack);
4660 /* Received a response to a challenge packet */
4662 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4663 struct rx_packet *np, int istack)
4667 /* Ignore the packet if we're the client */
4668 if (conn->type == RX_CLIENT_CONNECTION)
4671 /* If already authenticated, ignore the packet (it's probably a retry) */
4672 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4675 /* Otherwise, have the security object evaluate the response packet */
4676 error = RXS_CheckResponse(conn->securityObject, conn, np);
4678 /* If the response is invalid, reset the connection, sending
4679 * an abort to the peer */
4683 rxi_ConnectionError(conn, error);
4684 MUTEX_ENTER(&conn->conn_data_lock);
4685 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4686 MUTEX_EXIT(&conn->conn_data_lock);
4689 /* If the response is valid, any calls waiting to attach
4690 * servers can now do so */
4693 for (i = 0; i < RX_MAXCALLS; i++) {
4694 struct rx_call *call = conn->call[i];
4696 MUTEX_ENTER(&call->lock);
4697 if (call->state == RX_STATE_PRECALL)
4698 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4699 /* tnop can be null if newcallp is null */
4700 MUTEX_EXIT(&call->lock);
4704 /* Update the peer reachability information, just in case
4705 * some calls went into attach-wait while we were waiting
4706 * for authentication..
4708 rxi_UpdatePeerReach(conn, NULL);
4713 /* A client has received an authentication challenge: the security
4714 * object is asked to cough up a respectable response packet to send
4715 * back to the server. The server is responsible for retrying the
4716 * challenge if it fails to get a response. */
4719 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4720 struct rx_packet *np, int istack)
4724 /* Ignore the challenge if we're the server */
4725 if (conn->type == RX_SERVER_CONNECTION)
4728 /* Ignore the challenge if the connection is otherwise idle; someone's
4729 * trying to use us as an oracle. */
4730 if (!rxi_HasActiveCalls(conn))
4733 /* Send the security object the challenge packet. It is expected to fill
4734 * in the response. */
4735 error = RXS_GetResponse(conn->securityObject, conn, np);
4737 /* If the security object is unable to return a valid response, reset the
4738 * connection and send an abort to the peer. Otherwise send the response
4739 * packet to the peer connection. */
4741 rxi_ConnectionError(conn, error);
4742 MUTEX_ENTER(&conn->conn_data_lock);
4743 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4744 MUTEX_EXIT(&conn->conn_data_lock);
4746 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4747 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4753 /* Find an available server process to service the current request in
4754 * the given call structure. If one isn't available, queue up this
4755 * call so it eventually gets one */
4757 rxi_AttachServerProc(struct rx_call *call,
4758 osi_socket socket, int *tnop,
4759 struct rx_call **newcallp)
4761 struct rx_serverQueueEntry *sq;
4762 struct rx_service *service = call->conn->service;
4765 /* May already be attached */
4766 if (call->state == RX_STATE_ACTIVE)
4769 MUTEX_ENTER(&rx_serverPool_lock);
4771 haveQuota = QuotaOK(service);
4772 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4773 /* If there are no processes available to service this call,
4774 * put the call on the incoming call queue (unless it's
4775 * already on the queue).
4777 #ifdef RX_ENABLE_LOCKS
4779 ReturnToServerPool(service);
4780 #endif /* RX_ENABLE_LOCKS */
4782 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4783 call->flags |= RX_CALL_WAIT_PROC;
4784 rx_atomic_inc(&rx_nWaiting);
4785 rx_atomic_inc(&rx_nWaited);
4786 rxi_calltrace(RX_CALL_ARRIVAL, call);
4787 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4788 queue_Append(&rx_incomingCallQueue, call);
4791 sq = queue_Last(&rx_idleServerQueue, rx_serverQueueEntry);
4793 /* If hot threads are enabled, and both newcallp and sq->socketp
4794 * are non-null, then this thread will process the call, and the
4795 * idle server thread will start listening on this threads socket.
4798 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4801 *sq->socketp = socket;
4802 clock_GetTime(&call->startTime);
4803 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4807 if (call->flags & RX_CALL_WAIT_PROC) {
4808 /* Conservative: I don't think this should happen */
4809 call->flags &= ~RX_CALL_WAIT_PROC;
4810 if (queue_IsOnQueue(call)) {
4813 rx_atomic_dec(&rx_nWaiting);
4816 call->state = RX_STATE_ACTIVE;
4817 call->mode = RX_MODE_RECEIVING;
4818 #ifdef RX_KERNEL_TRACE
4820 int glockOwner = ISAFS_GLOCK();
4823 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4824 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4830 if (call->flags & RX_CALL_CLEARED) {
4831 /* send an ack now to start the packet flow up again */
4832 call->flags &= ~RX_CALL_CLEARED;
4833 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4835 #ifdef RX_ENABLE_LOCKS
4838 service->nRequestsRunning++;
4839 MUTEX_ENTER(&rx_quota_mutex);
4840 if (service->nRequestsRunning <= service->minProcs)
4843 MUTEX_EXIT(&rx_quota_mutex);
4847 MUTEX_EXIT(&rx_serverPool_lock);
4850 /* Delay the sending of an acknowledge event for a short while, while
4851 * a new call is being prepared (in the case of a client) or a reply
4852 * is being prepared (in the case of a server). Rather than sending
4853 * an ack packet, an ACKALL packet is sent. */
4855 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4857 #ifdef RX_ENABLE_LOCKS
4859 MUTEX_ENTER(&call->lock);
4860 rxevent_Put(call->delayedAckEvent);
4861 call->delayedAckEvent = NULL;
4862 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4864 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4865 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4866 call->flags |= RX_CALL_ACKALL_SENT;
4868 MUTEX_EXIT(&call->lock);
4869 #else /* RX_ENABLE_LOCKS */
4871 rxevent_Put(call->delayedAckEvent);
4872 call->delayedAckEvent = NULL;
4874 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4875 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4876 call->flags |= RX_CALL_ACKALL_SENT;
4877 #endif /* RX_ENABLE_LOCKS */
4881 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4884 struct rx_call *call = arg1;
4885 #ifdef RX_ENABLE_LOCKS
4887 MUTEX_ENTER(&call->lock);
4888 if (event == call->delayedAckEvent) {
4889 rxevent_Put(call->delayedAckEvent);
4890 call->delayedAckEvent = NULL;
4892 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4894 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4896 MUTEX_EXIT(&call->lock);
4897 #else /* RX_ENABLE_LOCKS */
4899 rxevent_Put(call->delayedAckEvent);
4900 call->delayedAckEvent = NULL;
4902 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4903 #endif /* RX_ENABLE_LOCKS */
4907 #ifdef RX_ENABLE_LOCKS
4908 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4909 * clearing them out.
4912 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4914 struct rx_packet *p, *tp;
4917 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4918 p->flags |= RX_PKTFLAG_ACKED;
4922 call->flags |= RX_CALL_TQ_CLEARME;
4923 call->flags |= RX_CALL_TQ_SOME_ACKED;
4926 rxi_rto_cancel(call);
4928 call->tfirst = call->tnext;
4929 call->nSoftAcked = 0;
4931 if (call->flags & RX_CALL_FAST_RECOVER) {
4932 call->flags &= ~RX_CALL_FAST_RECOVER;
4933 call->cwind = call->nextCwind;
4934 call->nextCwind = 0;
4937 CV_SIGNAL(&call->cv_twind);
4939 #endif /* RX_ENABLE_LOCKS */
4941 /* Clear out the transmit queue for the current call (all packets have
4942 * been received by peer) */
4944 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4946 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4947 struct rx_packet *p, *tp;
4949 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4951 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4952 p->flags |= RX_PKTFLAG_ACKED;
4956 call->flags |= RX_CALL_TQ_CLEARME;
4957 call->flags |= RX_CALL_TQ_SOME_ACKED;
4960 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4961 #ifdef RXDEBUG_PACKET
4963 #endif /* RXDEBUG_PACKET */
4964 rxi_FreePackets(0, &call->tq);
4965 rxi_WakeUpTransmitQueue(call);
4966 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4967 call->flags &= ~RX_CALL_TQ_CLEARME;
4969 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4971 rxi_rto_cancel(call);
4972 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4973 call->nSoftAcked = 0;
4975 if (call->flags & RX_CALL_FAST_RECOVER) {
4976 call->flags &= ~RX_CALL_FAST_RECOVER;
4977 call->cwind = call->nextCwind;
4979 #ifdef RX_ENABLE_LOCKS
4980 CV_SIGNAL(&call->cv_twind);
4982 osi_rxWakeup(&call->twind);
4987 rxi_ClearReceiveQueue(struct rx_call *call)
4989 if (queue_IsNotEmpty(&call->rq)) {
4992 count = rxi_FreePackets(0, &call->rq);
4993 rx_packetReclaims += count;
4994 #ifdef RXDEBUG_PACKET
4996 if ( call->rqc != 0 )
4997 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
4999 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5001 if (call->state == RX_STATE_PRECALL) {
5002 call->flags |= RX_CALL_CLEARED;
5006 /* Send an abort packet for the specified call */
5008 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5009 int istack, int force)
5012 struct clock when, now;
5017 /* Clients should never delay abort messages */
5018 if (rx_IsClientConn(call->conn))
5021 if (call->abortCode != call->error) {
5022 call->abortCode = call->error;
5023 call->abortCount = 0;
5026 if (force || rxi_callAbortThreshhold == 0
5027 || call->abortCount < rxi_callAbortThreshhold) {
5028 if (call->delayedAbortEvent) {
5029 rxevent_Cancel(&call->delayedAbortEvent, call,
5030 RX_CALL_REFCOUNT_ABORT);
5032 error = htonl(call->error);
5035 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5036 (char *)&error, sizeof(error), istack);
5037 } else if (!call->delayedAbortEvent) {
5038 clock_GetTime(&now);
5040 clock_Addmsec(&when, rxi_callAbortDelay);
5041 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5042 call->delayedAbortEvent =
5043 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5048 /* Send an abort packet for the specified connection. Packet is an
5049 * optional pointer to a packet that can be used to send the abort.
5050 * Once the number of abort messages reaches the threshhold, an
5051 * event is scheduled to send the abort. Setting the force flag
5052 * overrides sending delayed abort messages.
5054 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5055 * to send the abort packet.
5058 rxi_SendConnectionAbort(struct rx_connection *conn,
5059 struct rx_packet *packet, int istack, int force)
5062 struct clock when, now;
5067 /* Clients should never delay abort messages */
5068 if (rx_IsClientConn(conn))
5071 if (force || rxi_connAbortThreshhold == 0
5072 || conn->abortCount < rxi_connAbortThreshhold) {
5074 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
5075 error = htonl(conn->error);
5077 MUTEX_EXIT(&conn->conn_data_lock);
5079 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5080 RX_PACKET_TYPE_ABORT, (char *)&error,
5081 sizeof(error), istack);
5082 MUTEX_ENTER(&conn->conn_data_lock);
5083 } else if (!conn->delayedAbortEvent) {
5084 clock_GetTime(&now);
5086 clock_Addmsec(&when, rxi_connAbortDelay);
5087 conn->delayedAbortEvent =
5088 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
5093 /* Associate an error all of the calls owned by a connection. Called
5094 * with error non-zero. This is only for really fatal things, like
5095 * bad authentication responses. The connection itself is set in
5096 * error at this point, so that future packets received will be
5099 rxi_ConnectionError(struct rx_connection *conn,
5105 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5107 MUTEX_ENTER(&conn->conn_data_lock);
5108 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
5109 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
5110 if (conn->checkReachEvent) {
5111 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
5112 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5113 putConnection(conn);
5115 MUTEX_EXIT(&conn->conn_data_lock);
5116 for (i = 0; i < RX_MAXCALLS; i++) {
5117 struct rx_call *call = conn->call[i];
5119 MUTEX_ENTER(&call->lock);
5120 rxi_CallError(call, error);
5121 MUTEX_EXIT(&call->lock);
5124 conn->error = error;
5125 if (rx_stats_active)
5126 rx_atomic_inc(&rx_stats.fatalErrors);
5131 * Interrupt an in-progress call with the specified error and wakeup waiters.
5133 * @param[in] call The call to interrupt
5134 * @param[in] error The error code to send to the peer
5137 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5139 MUTEX_ENTER(&call->lock);
5140 rxi_CallError(call, error);
5141 rxi_SendCallAbort(call, NULL, 0, 1);
5142 MUTEX_EXIT(&call->lock);
5146 rxi_CallError(struct rx_call *call, afs_int32 error)
5149 osirx_AssertMine(&call->lock, "rxi_CallError");
5151 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5153 error = call->error;
5155 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5156 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5157 rxi_ResetCall(call, 0);
5160 rxi_ResetCall(call, 0);
5162 call->error = error;
5165 /* Reset various fields in a call structure, and wakeup waiting
5166 * processes. Some fields aren't changed: state & mode are not
5167 * touched (these must be set by the caller), and bufptr, nLeft, and
5168 * nFree are not reset, since these fields are manipulated by
5169 * unprotected macros, and may only be reset by non-interrupting code.
5173 rxi_ResetCall(struct rx_call *call, int newcall)
5176 struct rx_peer *peer;
5177 struct rx_packet *packet;
5179 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5181 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5183 /* Notify anyone who is waiting for asynchronous packet arrival */
5184 if (call->arrivalProc) {
5185 (*call->arrivalProc) (call, call->arrivalProcHandle,
5186 call->arrivalProcArg);
5187 call->arrivalProc = (void (*)())0;
5191 rxevent_Cancel(&call->growMTUEvent, call, RX_CALL_REFCOUNT_ALIVE);
5193 if (call->delayedAbortEvent) {
5194 rxevent_Cancel(&call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5195 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5197 rxi_SendCallAbort(call, packet, 0, 1);
5198 rxi_FreePacket(packet);
5203 * Update the peer with the congestion information in this call
5204 * so other calls on this connection can pick up where this call
5205 * left off. If the congestion sequence numbers don't match then
5206 * another call experienced a retransmission.
5208 peer = call->conn->peer;
5209 MUTEX_ENTER(&peer->peer_lock);
5211 if (call->congestSeq == peer->congestSeq) {
5212 peer->cwind = MAX(peer->cwind, call->cwind);
5213 peer->MTU = MAX(peer->MTU, call->MTU);
5214 peer->nDgramPackets =
5215 MAX(peer->nDgramPackets, call->nDgramPackets);
5218 call->abortCode = 0;
5219 call->abortCount = 0;
5221 if (peer->maxDgramPackets > 1) {
5222 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5224 call->MTU = peer->MTU;
5226 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5227 call->ssthresh = rx_maxSendWindow;
5228 call->nDgramPackets = peer->nDgramPackets;
5229 call->congestSeq = peer->congestSeq;
5230 call->rtt = peer->rtt;
5231 call->rtt_dev = peer->rtt_dev;
5232 clock_Zero(&call->rto);
5233 clock_Addmsec(&call->rto,
5234 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5235 MUTEX_EXIT(&peer->peer_lock);
5237 flags = call->flags;
5238 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5239 rxi_WaitforTQBusy(call);
5240 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5242 rxi_ClearTransmitQueue(call, 1);
5243 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5244 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5248 if ((flags & RX_CALL_PEER_BUSY)) {
5249 /* The call channel is still busy; resetting the call doesn't change
5251 call->flags |= RX_CALL_PEER_BUSY;
5254 rxi_ClearReceiveQueue(call);
5255 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5259 call->twind = call->conn->twind[call->channel];
5260 call->rwind = call->conn->rwind[call->channel];
5261 call->nSoftAcked = 0;
5262 call->nextCwind = 0;
5265 call->nCwindAcks = 0;
5266 call->nSoftAcks = 0;
5267 call->nHardAcks = 0;
5269 call->tfirst = call->rnext = call->tnext = 1;
5272 call->lastAcked = 0;
5273 call->localStatus = call->remoteStatus = 0;
5275 if (flags & RX_CALL_READER_WAIT) {
5276 #ifdef RX_ENABLE_LOCKS
5277 CV_BROADCAST(&call->cv_rq);
5279 osi_rxWakeup(&call->rq);
5282 if (flags & RX_CALL_WAIT_PACKETS) {
5283 MUTEX_ENTER(&rx_freePktQ_lock);
5284 rxi_PacketsUnWait(); /* XXX */
5285 MUTEX_EXIT(&rx_freePktQ_lock);
5287 #ifdef RX_ENABLE_LOCKS
5288 CV_SIGNAL(&call->cv_twind);
5290 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5291 osi_rxWakeup(&call->twind);
5294 #ifdef RX_ENABLE_LOCKS
5295 /* The following ensures that we don't mess with any queue while some
5296 * other thread might also be doing so. The call_queue_lock field is
5297 * is only modified under the call lock. If the call is in the process
5298 * of being removed from a queue, the call is not locked until the
5299 * the queue lock is dropped and only then is the call_queue_lock field
5300 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5301 * Note that any other routine which removes a call from a queue has to
5302 * obtain the queue lock before examing the queue and removing the call.
5304 if (call->call_queue_lock) {
5305 MUTEX_ENTER(call->call_queue_lock);
5306 if (queue_IsOnQueue(call)) {
5308 if (flags & RX_CALL_WAIT_PROC) {
5309 rx_atomic_dec(&rx_nWaiting);
5312 MUTEX_EXIT(call->call_queue_lock);
5313 CLEAR_CALL_QUEUE_LOCK(call);
5315 #else /* RX_ENABLE_LOCKS */
5316 if (queue_IsOnQueue(call)) {
5318 if (flags & RX_CALL_WAIT_PROC)
5319 rx_atomic_dec(&rx_nWaiting);
5321 #endif /* RX_ENABLE_LOCKS */
5323 rxi_KeepAliveOff(call);
5324 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5327 /* Send an acknowledge for the indicated packet (seq,serial) of the
5328 * indicated call, for the indicated reason (reason). This
5329 * acknowledge will specifically acknowledge receiving the packet, and
5330 * will also specify which other packets for this call have been
5331 * received. This routine returns the packet that was used to the
5332 * caller. The caller is responsible for freeing it or re-using it.
5333 * This acknowledgement also returns the highest sequence number
5334 * actually read out by the higher level to the sender; the sender
5335 * promises to keep around packets that have not been read by the
5336 * higher level yet (unless, of course, the sender decides to abort
5337 * the call altogether). Any of p, seq, serial, pflags, or reason may
5338 * be set to zero without ill effect. That is, if they are zero, they
5339 * will not convey any information.
5340 * NOW there is a trailer field, after the ack where it will safely be
5341 * ignored by mundanes, which indicates the maximum size packet this
5342 * host can swallow. */
5344 struct rx_packet *optionalPacket; use to send ack (or null)
5345 int seq; Sequence number of the packet we are acking
5346 int serial; Serial number of the packet
5347 int pflags; Flags field from packet header
5348 int reason; Reason an acknowledge was prompted
5352 rxi_SendAck(struct rx_call *call,
5353 struct rx_packet *optionalPacket, int serial, int reason,
5356 struct rx_ackPacket *ap;
5357 struct rx_packet *rqp;
5358 struct rx_packet *nxp; /* For queue_Scan */
5359 struct rx_packet *p;
5362 afs_uint32 padbytes = 0;
5363 #ifdef RX_ENABLE_TSFPQ
5364 struct rx_ts_info_t * rx_ts_info;
5368 * Open the receive window once a thread starts reading packets
5370 if (call->rnext > 1) {
5371 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5374 /* Don't attempt to grow MTU if this is a critical ping */
5375 if (reason == RX_ACK_MTU) {
5376 /* keep track of per-call attempts, if we're over max, do in small
5377 * otherwise in larger? set a size to increment by, decrease
5380 if (call->conn->peer->maxPacketSize &&
5381 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5383 padbytes = call->conn->peer->maxPacketSize+16;
5385 padbytes = call->conn->peer->maxMTU + 128;
5387 /* do always try a minimum size ping */
5388 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5390 /* subtract the ack payload */
5391 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5392 reason = RX_ACK_PING;
5395 call->nHardAcks = 0;
5396 call->nSoftAcks = 0;
5397 if (call->rnext > call->lastAcked)
5398 call->lastAcked = call->rnext;
5402 rx_computelen(p, p->length); /* reset length, you never know */
5403 } /* where that's been... */
5404 #ifdef RX_ENABLE_TSFPQ
5406 RX_TS_INFO_GET(rx_ts_info);
5407 if ((p = rx_ts_info->local_special_packet)) {
5408 rx_computelen(p, p->length);
5409 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5410 rx_ts_info->local_special_packet = p;
5411 } else { /* We won't send the ack, but don't panic. */
5412 return optionalPacket;
5416 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5417 /* We won't send the ack, but don't panic. */
5418 return optionalPacket;
5423 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5426 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5427 #ifndef RX_ENABLE_TSFPQ
5428 if (!optionalPacket)
5431 return optionalPacket;
5433 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5434 if (rx_Contiguous(p) < templ) {
5435 #ifndef RX_ENABLE_TSFPQ
5436 if (!optionalPacket)
5439 return optionalPacket;
5444 /* MTUXXX failing to send an ack is very serious. We should */
5445 /* try as hard as possible to send even a partial ack; it's */
5446 /* better than nothing. */
5447 ap = (struct rx_ackPacket *)rx_DataOf(p);
5448 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5449 ap->reason = reason;
5451 /* The skew computation used to be bogus, I think it's better now. */
5452 /* We should start paying attention to skew. XXX */
5453 ap->serial = htonl(serial);
5454 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5457 * First packet not yet forwarded to reader. When ACKALL has been
5458 * sent the peer has been told that all received packets will be
5459 * delivered to the reader. The value 'rnext' is used internally
5460 * to refer to the next packet in the receive queue that must be
5461 * delivered to the reader. From the perspective of the peer it
5462 * already has so report the last sequence number plus one if there
5463 * are packets in the receive queue awaiting processing.
5465 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5466 !queue_IsEmpty(&call->rq)) {
5467 ap->firstPacket = htonl(queue_Last(&call->rq, rx_packet)->header.seq + 1);
5469 ap->firstPacket = htonl(call->rnext);
5471 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5473 /* No fear of running out of ack packet here because there can only be at most
5474 * one window full of unacknowledged packets. The window size must be constrained
5475 * to be less than the maximum ack size, of course. Also, an ack should always
5476 * fit into a single packet -- it should not ever be fragmented. */
5477 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5478 if (!rqp || !call->rq.next
5479 || (rqp->header.seq > (call->rnext + call->rwind))) {
5480 #ifndef RX_ENABLE_TSFPQ
5481 if (!optionalPacket)
5484 rxi_CallError(call, RX_CALL_DEAD);
5485 return optionalPacket;
5488 while (rqp->header.seq > call->rnext + offset)
5489 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5490 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5492 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5493 #ifndef RX_ENABLE_TSFPQ
5494 if (!optionalPacket)
5497 rxi_CallError(call, RX_CALL_DEAD);
5498 return optionalPacket;
5504 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5506 /* these are new for AFS 3.3 */
5507 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5508 templ = htonl(templ);
5509 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5510 templ = htonl(call->conn->peer->ifMTU);
5511 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5512 sizeof(afs_int32), &templ);
5514 /* new for AFS 3.4 */
5515 templ = htonl(call->rwind);
5516 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5517 sizeof(afs_int32), &templ);
5519 /* new for AFS 3.5 */
5520 templ = htonl(call->conn->peer->ifDgramPackets);
5521 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5522 sizeof(afs_int32), &templ);
5524 p->header.serviceId = call->conn->serviceId;
5525 p->header.cid = (call->conn->cid | call->channel);
5526 p->header.callNumber = *call->callNumber;
5528 p->header.securityIndex = call->conn->securityIndex;
5529 p->header.epoch = call->conn->epoch;
5530 p->header.type = RX_PACKET_TYPE_ACK;
5531 p->header.flags = RX_SLOW_START_OK;
5532 if (reason == RX_ACK_PING) {
5533 p->header.flags |= RX_REQUEST_ACK;
5535 p->length = padbytes +
5536 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5539 /* not fast but we can potentially use this if truncated
5540 * fragments are delivered to figure out the mtu.
5542 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5543 sizeof(afs_int32), sizeof(afs_int32),
5547 if (call->conn->type == RX_CLIENT_CONNECTION)
5548 p->header.flags |= RX_CLIENT_INITIATED;
5552 if (rxdebug_active) {
5556 len = _snprintf(msg, sizeof(msg),
5557 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5558 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5559 ntohl(ap->serial), ntohl(ap->previousPacket),
5560 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5561 ap->nAcks, ntohs(ap->bufferSpace) );
5565 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5566 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5570 OutputDebugString(msg);
5572 #else /* AFS_NT40_ENV */
5574 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5575 ap->reason, ntohl(ap->previousPacket),
5576 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5578 for (offset = 0; offset < ap->nAcks; offset++)
5579 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5584 #endif /* AFS_NT40_ENV */
5587 int i, nbytes = p->length;
5589 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5590 if (nbytes <= p->wirevec[i].iov_len) {
5593 savelen = p->wirevec[i].iov_len;
5595 p->wirevec[i].iov_len = nbytes;
5597 rxi_Send(call, p, istack);
5598 p->wirevec[i].iov_len = savelen;
5602 nbytes -= p->wirevec[i].iov_len;
5605 if (rx_stats_active)
5606 rx_atomic_inc(&rx_stats.ackPacketsSent);
5607 #ifndef RX_ENABLE_TSFPQ
5608 if (!optionalPacket)
5611 return optionalPacket; /* Return packet for re-use by caller */
5615 struct rx_packet **list;
5620 /* Send all of the packets in the list in single datagram */
5622 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5623 int istack, int moreFlag)
5629 struct rx_connection *conn = call->conn;
5630 struct rx_peer *peer = conn->peer;
5632 MUTEX_ENTER(&peer->peer_lock);
5633 peer->nSent += xmit->len;
5634 if (xmit->resending)
5635 peer->reSends += xmit->len;
5636 MUTEX_EXIT(&peer->peer_lock);
5638 if (rx_stats_active) {
5639 if (xmit->resending)
5640 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5642 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5645 clock_GetTime(&now);
5647 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5651 /* Set the packet flags and schedule the resend events */
5652 /* Only request an ack for the last packet in the list */
5653 for (i = 0; i < xmit->len; i++) {
5654 struct rx_packet *packet = xmit->list[i];
5656 /* Record the time sent */
5657 packet->timeSent = now;
5658 packet->flags |= RX_PKTFLAG_SENT;
5660 /* Ask for an ack on retransmitted packets, on every other packet
5661 * if the peer doesn't support slow start. Ask for an ack on every
5662 * packet until the congestion window reaches the ack rate. */
5663 if (packet->header.serial) {
5666 packet->firstSent = now;
5667 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5668 || (!(call->flags & RX_CALL_SLOW_START_OK)
5669 && (packet->header.seq & 1)))) {
5674 /* Tag this packet as not being the last in this group,
5675 * for the receiver's benefit */
5676 if (i < xmit->len - 1 || moreFlag) {
5677 packet->header.flags |= RX_MORE_PACKETS;
5682 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5685 /* Since we're about to send a data packet to the peer, it's
5686 * safe to nuke any scheduled end-of-packets ack */
5687 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5689 MUTEX_EXIT(&call->lock);
5690 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5691 if (xmit->len > 1) {
5692 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5694 rxi_SendPacket(call, conn, xmit->list[0], istack);
5696 MUTEX_ENTER(&call->lock);
5697 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5699 /* Tell the RTO calculation engine that we have sent a packet, and
5700 * if it was the last one */
5701 rxi_rto_packet_sent(call, lastPacket, istack);
5703 /* Update last send time for this call (for keep-alive
5704 * processing), and for the connection (so that we can discover
5705 * idle connections) */
5706 conn->lastSendTime = call->lastSendTime = clock_Sec();
5707 /* Let a set of retransmits trigger an idle timeout */
5708 if (!xmit->resending)
5709 call->lastSendData = call->lastSendTime;
5712 /* When sending packets we need to follow these rules:
5713 * 1. Never send more than maxDgramPackets in a jumbogram.
5714 * 2. Never send a packet with more than two iovecs in a jumbogram.
5715 * 3. Never send a retransmitted packet in a jumbogram.
5716 * 4. Never send more than cwind/4 packets in a jumbogram
5717 * We always keep the last list we should have sent so we
5718 * can set the RX_MORE_PACKETS flags correctly.
5722 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5727 struct xmitlist working;
5728 struct xmitlist last;
5730 struct rx_peer *peer = call->conn->peer;
5731 int morePackets = 0;
5733 memset(&last, 0, sizeof(struct xmitlist));
5734 working.list = &list[0];
5736 working.resending = 0;
5738 recovery = call->flags & RX_CALL_FAST_RECOVER;
5740 for (i = 0; i < len; i++) {
5741 /* Does the current packet force us to flush the current list? */
5743 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5744 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5746 /* This sends the 'last' list and then rolls the current working
5747 * set into the 'last' one, and resets the working set */
5750 rxi_SendList(call, &last, istack, 1);
5751 /* If the call enters an error state stop sending, or if
5752 * we entered congestion recovery mode, stop sending */
5754 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5759 working.resending = 0;
5760 working.list = &list[i];
5762 /* Add the current packet to the list if it hasn't been acked.
5763 * Otherwise adjust the list pointer to skip the current packet. */
5764 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5767 if (list[i]->header.serial)
5768 working.resending = 1;
5770 /* Do we need to flush the list? */
5771 if (working.len >= (int)peer->maxDgramPackets
5772 || working.len >= (int)call->nDgramPackets
5773 || working.len >= (int)call->cwind
5774 || list[i]->header.serial
5775 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5777 rxi_SendList(call, &last, istack, 1);
5778 /* If the call enters an error state stop sending, or if
5779 * we entered congestion recovery mode, stop sending */
5781 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5786 working.resending = 0;
5787 working.list = &list[i + 1];
5790 if (working.len != 0) {
5791 osi_Panic("rxi_SendList error");
5793 working.list = &list[i + 1];
5797 /* Send the whole list when the call is in receive mode, when
5798 * the call is in eof mode, when we are in fast recovery mode,
5799 * and when we have the last packet */
5800 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5801 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5802 || (call->flags & RX_CALL_FAST_RECOVER)) {
5803 /* Check for the case where the current list contains
5804 * an acked packet. Since we always send retransmissions
5805 * in a separate packet, we only need to check the first
5806 * packet in the list */
5807 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5811 rxi_SendList(call, &last, istack, morePackets);
5812 /* If the call enters an error state stop sending, or if
5813 * we entered congestion recovery mode, stop sending */
5815 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5819 rxi_SendList(call, &working, istack, 0);
5821 } else if (last.len > 0) {
5822 rxi_SendList(call, &last, istack, 0);
5823 /* Packets which are in 'working' are not sent by this call */
5828 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5830 struct rx_call *call = arg0;
5831 struct rx_peer *peer;
5832 struct rx_packet *p, *nxp;
5833 struct clock maxTimeout = { 60, 0 };
5835 MUTEX_ENTER(&call->lock);
5837 peer = call->conn->peer;
5839 /* Make sure that the event pointer is removed from the call
5840 * structure, since there is no longer a per-call retransmission
5842 if (event == call->resendEvent) {
5843 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5844 rxevent_Put(call->resendEvent);
5845 call->resendEvent = NULL;
5848 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5849 rxi_CheckBusy(call);
5852 if (queue_IsEmpty(&call->tq)) {
5853 /* Nothing to do. This means that we've been raced, and that an
5854 * ACK has come in between when we were triggered, and when we
5855 * actually got to run. */
5859 /* We're in loss recovery */
5860 call->flags |= RX_CALL_FAST_RECOVER;
5862 /* Mark all of the pending packets in the queue as being lost */
5863 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5864 if (!(p->flags & RX_PKTFLAG_ACKED))
5865 p->flags &= ~RX_PKTFLAG_SENT;
5868 /* We're resending, so we double the timeout of the call. This will be
5869 * dropped back down by the first successful ACK that we receive.
5871 * We apply a maximum value here of 60 seconds
5873 clock_Add(&call->rto, &call->rto);
5874 if (clock_Gt(&call->rto, &maxTimeout))
5875 call->rto = maxTimeout;
5877 /* Packet loss is most likely due to congestion, so drop our window size
5878 * and start again from the beginning */
5879 if (peer->maxDgramPackets >1) {
5880 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5881 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5883 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5884 call->nDgramPackets = 1;
5886 call->nextCwind = 1;
5889 MUTEX_ENTER(&peer->peer_lock);
5890 peer->MTU = call->MTU;
5891 peer->cwind = call->cwind;
5892 peer->nDgramPackets = 1;
5894 call->congestSeq = peer->congestSeq;
5895 MUTEX_EXIT(&peer->peer_lock);
5897 rxi_Start(call, istack);
5900 MUTEX_EXIT(&call->lock);
5903 /* This routine is called when new packets are readied for
5904 * transmission and when retransmission may be necessary, or when the
5905 * transmission window or burst count are favourable. This should be
5906 * better optimized for new packets, the usual case, now that we've
5907 * got rid of queues of send packets. XXXXXXXXXXX */
5909 rxi_Start(struct rx_call *call, int istack)
5912 struct rx_packet *p;
5913 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5918 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5919 if (rx_stats_active)
5920 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5925 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5927 /* Send (or resend) any packets that need it, subject to
5928 * window restrictions and congestion burst control
5929 * restrictions. Ask for an ack on the last packet sent in
5930 * this burst. For now, we're relying upon the window being
5931 * considerably bigger than the largest number of packets that
5932 * are typically sent at once by one initial call to
5933 * rxi_Start. This is probably bogus (perhaps we should ask
5934 * for an ack when we're half way through the current
5935 * window?). Also, for non file transfer applications, this
5936 * may end up asking for an ack for every packet. Bogus. XXXX
5939 * But check whether we're here recursively, and let the other guy
5942 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5943 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5944 call->flags |= RX_CALL_TQ_BUSY;
5946 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5948 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5949 call->flags &= ~RX_CALL_NEED_START;
5950 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5952 maxXmitPackets = MIN(call->twind, call->cwind);
5953 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5954 #ifdef RX_TRACK_PACKETS
5955 if ((p->flags & RX_PKTFLAG_FREE)
5956 || (!queue_IsEnd(&call->tq, nxp)
5957 && (nxp->flags & RX_PKTFLAG_FREE))
5958 || (p == (struct rx_packet *)&rx_freePacketQueue)
5959 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5960 osi_Panic("rxi_Start: xmit queue clobbered");
5963 if (p->flags & RX_PKTFLAG_ACKED) {
5964 /* Since we may block, don't trust this */
5965 if (rx_stats_active)
5966 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5967 continue; /* Ignore this packet if it has been acknowledged */
5970 /* Turn off all flags except these ones, which are the same
5971 * on each transmission */
5972 p->header.flags &= RX_PRESET_FLAGS;
5974 if (p->header.seq >=
5975 call->tfirst + MIN((int)call->twind,
5976 (int)(call->nSoftAcked +
5978 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5979 /* Note: if we're waiting for more window space, we can
5980 * still send retransmits; hence we don't return here, but
5981 * break out to schedule a retransmit event */
5982 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5983 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5988 /* Transmit the packet if it needs to be sent. */
5989 if (!(p->flags & RX_PKTFLAG_SENT)) {
5990 if (nXmitPackets == maxXmitPackets) {
5991 rxi_SendXmitList(call, call->xmitList,
5992 nXmitPackets, istack);
5995 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
5996 *(call->callNumber), p));
5997 call->xmitList[nXmitPackets++] = p;
6001 /* xmitList now hold pointers to all of the packets that are
6002 * ready to send. Now we loop to send the packets */
6003 if (nXmitPackets > 0) {
6004 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6008 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6010 /* We went into the error state while sending packets. Now is
6011 * the time to reset the call. This will also inform the using
6012 * process that the call is in an error state.
6014 if (rx_stats_active)
6015 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6016 call->flags &= ~RX_CALL_TQ_BUSY;
6017 rxi_WakeUpTransmitQueue(call);
6018 rxi_CallError(call, call->error);
6021 #ifdef RX_ENABLE_LOCKS
6022 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6024 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6025 /* Some packets have received acks. If they all have, we can clear
6026 * the transmit queue.
6029 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
6030 if (p->header.seq < call->tfirst
6031 && (p->flags & RX_PKTFLAG_ACKED)) {
6033 #ifdef RX_TRACK_PACKETS
6034 p->flags &= ~RX_PKTFLAG_TQ;
6036 #ifdef RXDEBUG_PACKET
6044 call->flags |= RX_CALL_TQ_CLEARME;
6046 #endif /* RX_ENABLE_LOCKS */
6047 if (call->flags & RX_CALL_TQ_CLEARME)
6048 rxi_ClearTransmitQueue(call, 1);
6049 } while (call->flags & RX_CALL_NEED_START);
6051 * TQ references no longer protected by this flag; they must remain
6052 * protected by the global lock.
6054 call->flags &= ~RX_CALL_TQ_BUSY;
6055 rxi_WakeUpTransmitQueue(call);
6057 call->flags |= RX_CALL_NEED_START;
6059 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6061 rxi_rto_cancel(call);
6065 /* Also adjusts the keep alive parameters for the call, to reflect
6066 * that we have just sent a packet (so keep alives aren't sent
6069 rxi_Send(struct rx_call *call, struct rx_packet *p,
6072 struct rx_connection *conn = call->conn;
6074 /* Stamp each packet with the user supplied status */
6075 p->header.userStatus = call->localStatus;
6077 /* Allow the security object controlling this call's security to
6078 * make any last-minute changes to the packet */
6079 RXS_SendPacket(conn->securityObject, call, p);
6081 /* Since we're about to send SOME sort of packet to the peer, it's
6082 * safe to nuke any scheduled end-of-packets ack */
6083 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6085 /* Actually send the packet, filling in more connection-specific fields */
6086 MUTEX_EXIT(&call->lock);
6087 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6088 rxi_SendPacket(call, conn, p, istack);
6089 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6090 MUTEX_ENTER(&call->lock);
6092 /* Update last send time for this call (for keep-alive
6093 * processing), and for the connection (so that we can discover
6094 * idle connections) */
6095 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6096 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6097 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6099 conn->lastSendTime = call->lastSendTime = clock_Sec();
6100 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6101 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6102 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6103 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6104 RX_ACK_PING_RESPONSE)))
6105 call->lastSendData = call->lastSendTime;
6109 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6110 * that things are fine. Also called periodically to guarantee that nothing
6111 * falls through the cracks (e.g. (error + dally) connections have keepalive
6112 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6114 * haveCTLock Set if calling from rxi_ReapConnections
6116 #ifdef RX_ENABLE_LOCKS
6118 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6119 #else /* RX_ENABLE_LOCKS */
6121 rxi_CheckCall(struct rx_call *call)
6122 #endif /* RX_ENABLE_LOCKS */
6124 struct rx_connection *conn = call->conn;
6126 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6127 afs_uint32 fudgeFactor;
6131 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6132 if (call->flags & RX_CALL_TQ_BUSY) {
6133 /* Call is active and will be reset by rxi_Start if it's
6134 * in an error state.
6139 /* RTT + 8*MDEV, rounded up to the next second. */
6140 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6141 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6143 deadTime = conn->secondsUntilDead + fudgeFactor;
6145 /* These are computed to the second (+- 1 second). But that's
6146 * good enough for these values, which should be a significant
6147 * number of seconds. */
6148 if (now > (call->lastReceiveTime + deadTime)) {
6149 if (call->state == RX_STATE_ACTIVE) {
6151 #if defined(KERNEL) && defined(AFS_SUN5_ENV)
6153 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6154 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6155 ip_stack_t *ipst = ns->netstack_ip;
6157 ire = ire_cache_lookup(conn->peer->host
6158 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6160 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6162 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6169 if (ire && ire->ire_max_frag > 0)
6170 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6172 #if defined(GLOBAL_NETSTACKID)
6176 #endif /* ADAPT_PMTU */
6177 cerror = RX_CALL_DEAD;
6180 #ifdef RX_ENABLE_LOCKS
6181 /* Cancel pending events */
6182 rxevent_Cancel(&call->delayedAckEvent, call,
6183 RX_CALL_REFCOUNT_DELAY);
6184 rxi_rto_cancel(call);
6185 rxevent_Cancel(&call->keepAliveEvent, call,
6186 RX_CALL_REFCOUNT_ALIVE);
6187 rxevent_Cancel(&call->growMTUEvent, call,
6188 RX_CALL_REFCOUNT_ALIVE);
6189 MUTEX_ENTER(&rx_refcnt_mutex);
6190 if (call->refCount == 0) {
6191 rxi_FreeCall(call, haveCTLock);
6192 MUTEX_EXIT(&rx_refcnt_mutex);
6195 MUTEX_EXIT(&rx_refcnt_mutex);
6197 #else /* RX_ENABLE_LOCKS */
6198 rxi_FreeCall(call, 0);
6200 #endif /* RX_ENABLE_LOCKS */
6202 /* Non-active calls are destroyed if they are not responding
6203 * to pings; active calls are simply flagged in error, so the
6204 * attached process can die reasonably gracefully. */
6207 if (conn->idleDeadTime) {
6208 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6211 /* see if we have a non-activity timeout */
6212 if (call->startWait && idleDeadTime
6213 && ((call->startWait + idleDeadTime) < now) &&
6214 (call->flags & RX_CALL_READER_WAIT)) {
6215 if (call->state == RX_STATE_ACTIVE) {
6216 cerror = RX_CALL_TIMEOUT;
6220 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6221 && ((call->lastSendData + idleDeadTime) < now)) {
6222 if (call->state == RX_STATE_ACTIVE) {
6223 cerror = conn->idleDeadErr;
6228 if (conn->hardDeadTime) {
6229 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6232 /* see if we have a hard timeout */
6234 && (now > (hardDeadTime + call->startTime.sec))) {
6235 if (call->state == RX_STATE_ACTIVE)
6236 rxi_CallError(call, RX_CALL_TIMEOUT);
6241 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6242 && call->lastReceiveTime) {
6243 int oldMTU = conn->peer->ifMTU;
6245 /* if we thought we could send more, perhaps things got worse */
6246 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6247 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6248 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6249 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6251 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6253 /* minimum capped in SetPeerMtu */
6254 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6257 conn->lastPacketSize = 0;
6259 /* needed so ResetCall doesn't clobber us. */
6260 call->MTU = conn->peer->ifMTU;
6262 /* if we never succeeded, let the error pass out as-is */
6263 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6264 cerror = conn->msgsizeRetryErr;
6267 rxi_CallError(call, cerror);
6272 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6273 void *dummy, int dummy2)
6275 struct rx_connection *conn = arg1;
6276 struct rx_header theader;
6277 char tbuffer[1 + sizeof(struct rx_header)];
6278 struct sockaddr_in taddr;
6281 struct iovec tmpiov[2];
6284 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6287 tp = &tbuffer[sizeof(struct rx_header)];
6288 taddr.sin_family = AF_INET;
6289 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6290 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6291 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6292 taddr.sin_len = sizeof(struct sockaddr_in);
6294 memset(&theader, 0, sizeof(theader));
6295 theader.epoch = htonl(999);
6297 theader.callNumber = 0;
6300 theader.type = RX_PACKET_TYPE_VERSION;
6301 theader.flags = RX_LAST_PACKET;
6302 theader.serviceId = 0;
6304 memcpy(tbuffer, &theader, sizeof(theader));
6305 memcpy(tp, &a, sizeof(a));
6306 tmpiov[0].iov_base = tbuffer;
6307 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6309 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6311 MUTEX_ENTER(&conn->conn_data_lock);
6312 MUTEX_ENTER(&rx_refcnt_mutex);
6313 /* Only reschedule ourselves if the connection would not be destroyed */
6314 if (conn->refCount <= 1) {
6315 rxevent_Put(conn->natKeepAliveEvent);
6316 conn->natKeepAliveEvent = NULL;
6317 MUTEX_EXIT(&rx_refcnt_mutex);
6318 MUTEX_EXIT(&conn->conn_data_lock);
6319 rx_DestroyConnection(conn); /* drop the reference for this */
6321 conn->refCount--; /* drop the reference for this */
6322 MUTEX_EXIT(&rx_refcnt_mutex);
6323 rxevent_Put(conn->natKeepAliveEvent);
6324 conn->natKeepAliveEvent = NULL;
6325 rxi_ScheduleNatKeepAliveEvent(conn);
6326 MUTEX_EXIT(&conn->conn_data_lock);
6331 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6333 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6334 struct clock when, now;
6335 clock_GetTime(&now);
6337 when.sec += conn->secondsUntilNatPing;
6338 MUTEX_ENTER(&rx_refcnt_mutex);
6339 conn->refCount++; /* hold a reference for this */
6340 MUTEX_EXIT(&rx_refcnt_mutex);
6341 conn->natKeepAliveEvent =
6342 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6347 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6349 MUTEX_ENTER(&conn->conn_data_lock);
6350 conn->secondsUntilNatPing = seconds;
6352 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6353 rxi_ScheduleNatKeepAliveEvent(conn);
6355 conn->flags |= RX_CONN_NAT_PING;
6357 MUTEX_EXIT(&conn->conn_data_lock);
6361 rxi_NatKeepAliveOn(struct rx_connection *conn)
6363 MUTEX_ENTER(&conn->conn_data_lock);
6364 /* if it's already attached */
6365 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6366 rxi_ScheduleNatKeepAliveEvent(conn);
6368 conn->flags |= RX_CONN_NAT_PING;
6369 MUTEX_EXIT(&conn->conn_data_lock);
6372 /* When a call is in progress, this routine is called occasionally to
6373 * make sure that some traffic has arrived (or been sent to) the peer.
6374 * If nothing has arrived in a reasonable amount of time, the call is
6375 * declared dead; if nothing has been sent for a while, we send a
6376 * keep-alive packet (if we're actually trying to keep the call alive)
6379 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6382 struct rx_call *call = arg1;
6383 struct rx_connection *conn;
6386 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6387 MUTEX_ENTER(&call->lock);
6389 if (event == call->keepAliveEvent) {
6390 rxevent_Put(call->keepAliveEvent);
6391 call->keepAliveEvent = NULL;
6396 #ifdef RX_ENABLE_LOCKS
6397 if (rxi_CheckCall(call, 0)) {
6398 MUTEX_EXIT(&call->lock);
6401 #else /* RX_ENABLE_LOCKS */
6402 if (rxi_CheckCall(call))
6404 #endif /* RX_ENABLE_LOCKS */
6406 /* Don't try to keep alive dallying calls */
6407 if (call->state == RX_STATE_DALLY) {
6408 MUTEX_EXIT(&call->lock);
6413 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6414 /* Don't try to send keepalives if there is unacknowledged data */
6415 /* the rexmit code should be good enough, this little hack
6416 * doesn't quite work XXX */
6417 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6419 rxi_ScheduleKeepAliveEvent(call);
6420 MUTEX_EXIT(&call->lock);
6423 /* Does what's on the nameplate. */
6425 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6427 struct rx_call *call = arg1;
6428 struct rx_connection *conn;
6430 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6431 MUTEX_ENTER(&call->lock);
6433 if (event == call->growMTUEvent) {
6434 rxevent_Put(call->growMTUEvent);
6435 call->growMTUEvent = NULL;
6438 #ifdef RX_ENABLE_LOCKS
6439 if (rxi_CheckCall(call, 0)) {
6440 MUTEX_EXIT(&call->lock);
6443 #else /* RX_ENABLE_LOCKS */
6444 if (rxi_CheckCall(call))
6446 #endif /* RX_ENABLE_LOCKS */
6448 /* Don't bother with dallying calls */
6449 if (call->state == RX_STATE_DALLY) {
6450 MUTEX_EXIT(&call->lock);
6457 * keep being scheduled, just don't do anything if we're at peak,
6458 * or we're not set up to be properly handled (idle timeout required)
6460 if ((conn->peer->maxPacketSize != 0) &&
6461 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6462 (conn->idleDeadErr))
6463 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6464 rxi_ScheduleGrowMTUEvent(call, 0);
6465 MUTEX_EXIT(&call->lock);
6469 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6471 if (!call->keepAliveEvent) {
6472 struct clock when, now;
6473 clock_GetTime(&now);
6475 when.sec += call->conn->secondsUntilPing;
6476 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6477 call->keepAliveEvent =
6478 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6483 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6485 if (!call->growMTUEvent) {
6486 struct clock when, now;
6488 clock_GetTime(&now);
6491 if (call->conn->secondsUntilPing)
6492 secs = (6*call->conn->secondsUntilPing)-1;
6494 if (call->conn->secondsUntilDead)
6495 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6499 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6500 call->growMTUEvent =
6501 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6505 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6507 rxi_KeepAliveOn(struct rx_call *call)
6509 /* Pretend last packet received was received now--i.e. if another
6510 * packet isn't received within the keep alive time, then the call
6511 * will die; Initialize last send time to the current time--even
6512 * if a packet hasn't been sent yet. This will guarantee that a
6513 * keep-alive is sent within the ping time */
6514 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6515 rxi_ScheduleKeepAliveEvent(call);
6519 * Solely in order that callers not need to include rx_call.h
6522 rx_KeepAliveOff(struct rx_call *call)
6524 rxi_KeepAliveOff(call);
6527 rx_KeepAliveOn(struct rx_call *call)
6529 rxi_KeepAliveOn(call);
6533 rxi_GrowMTUOn(struct rx_call *call)
6535 struct rx_connection *conn = call->conn;
6536 MUTEX_ENTER(&conn->conn_data_lock);
6537 conn->lastPingSizeSer = conn->lastPingSize = 0;
6538 MUTEX_EXIT(&conn->conn_data_lock);
6539 rxi_ScheduleGrowMTUEvent(call, 1);
6542 /* This routine is called to send connection abort messages
6543 * that have been delayed to throttle looping clients. */
6545 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6548 struct rx_connection *conn = arg1;
6551 struct rx_packet *packet;
6553 MUTEX_ENTER(&conn->conn_data_lock);
6554 rxevent_Put(conn->delayedAbortEvent);
6555 conn->delayedAbortEvent = NULL;
6556 error = htonl(conn->error);
6558 MUTEX_EXIT(&conn->conn_data_lock);
6559 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6562 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6563 RX_PACKET_TYPE_ABORT, (char *)&error,
6565 rxi_FreePacket(packet);
6569 /* This routine is called to send call abort messages
6570 * that have been delayed to throttle looping clients. */
6572 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6575 struct rx_call *call = arg1;
6578 struct rx_packet *packet;
6580 MUTEX_ENTER(&call->lock);
6581 rxevent_Put(call->delayedAbortEvent);
6582 call->delayedAbortEvent = NULL;
6583 error = htonl(call->error);
6585 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6588 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6589 (char *)&error, sizeof(error), 0);
6590 rxi_FreePacket(packet);
6592 MUTEX_EXIT(&call->lock);
6593 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6596 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6597 * seconds) to ask the client to authenticate itself. The routine
6598 * issues a challenge to the client, which is obtained from the
6599 * security object associated with the connection */
6601 rxi_ChallengeEvent(struct rxevent *event,
6602 void *arg0, void *arg1, int tries)
6604 struct rx_connection *conn = arg0;
6607 rxevent_Put(conn->challengeEvent);
6608 conn->challengeEvent = NULL;
6611 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6612 struct rx_packet *packet;
6613 struct clock when, now;
6616 /* We've failed to authenticate for too long.
6617 * Reset any calls waiting for authentication;
6618 * they are all in RX_STATE_PRECALL.
6622 MUTEX_ENTER(&conn->conn_call_lock);
6623 for (i = 0; i < RX_MAXCALLS; i++) {
6624 struct rx_call *call = conn->call[i];
6626 MUTEX_ENTER(&call->lock);
6627 if (call->state == RX_STATE_PRECALL) {
6628 rxi_CallError(call, RX_CALL_DEAD);
6629 rxi_SendCallAbort(call, NULL, 0, 0);
6631 MUTEX_EXIT(&call->lock);
6634 MUTEX_EXIT(&conn->conn_call_lock);
6638 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6640 /* If there's no packet available, do this later. */
6641 RXS_GetChallenge(conn->securityObject, conn, packet);
6642 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6643 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6644 rxi_FreePacket(packet);
6646 clock_GetTime(&now);
6648 when.sec += RX_CHALLENGE_TIMEOUT;
6649 conn->challengeEvent =
6650 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6655 /* Call this routine to start requesting the client to authenticate
6656 * itself. This will continue until authentication is established,
6657 * the call times out, or an invalid response is returned. The
6658 * security object associated with the connection is asked to create
6659 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6660 * defined earlier. */
6662 rxi_ChallengeOn(struct rx_connection *conn)
6664 if (!conn->challengeEvent) {
6665 RXS_CreateChallenge(conn->securityObject, conn);
6666 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6671 /* rxi_ComputeRoundTripTime is called with peer locked. */
6672 /* peer may be null */
6674 rxi_ComputeRoundTripTime(struct rx_packet *p,
6675 struct rx_ackPacket *ack,
6676 struct rx_call *call,
6677 struct rx_peer *peer,
6680 struct clock thisRtt, *sentp;
6684 /* If the ACK is delayed, then do nothing */
6685 if (ack->reason == RX_ACK_DELAY)
6688 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6689 * their RTT multiple times, so only include the RTT of the last packet
6691 if (p->flags & RX_JUMBO_PACKET)
6694 /* Use the serial number to determine which transmission the ACK is for,
6695 * and set the sent time to match this. If we have no serial number, then
6696 * only use the ACK for RTT calculations if the packet has not been
6700 serial = ntohl(ack->serial);
6702 if (serial == p->header.serial) {
6703 sentp = &p->timeSent;
6704 } else if (serial == p->firstSerial) {
6705 sentp = &p->firstSent;
6706 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6707 sentp = &p->firstSent;
6711 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6712 sentp = &p->firstSent;
6719 if (clock_Lt(&thisRtt, sentp))
6720 return; /* somebody set the clock back, don't count this time. */
6722 clock_Sub(&thisRtt, sentp);
6723 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6724 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6726 if (clock_IsZero(&thisRtt)) {
6728 * The actual round trip time is shorter than the
6729 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6730 * Since we can't tell which at the moment we will assume 1ms.
6732 thisRtt.usec = 1000;
6735 if (rx_stats_active) {
6736 MUTEX_ENTER(&rx_stats_mutex);
6737 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6738 rx_stats.minRtt = thisRtt;
6739 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6740 if (thisRtt.sec > 60) {
6741 MUTEX_EXIT(&rx_stats_mutex);
6742 return; /* somebody set the clock ahead */
6744 rx_stats.maxRtt = thisRtt;
6746 clock_Add(&rx_stats.totalRtt, &thisRtt);
6747 rx_atomic_inc(&rx_stats.nRttSamples);
6748 MUTEX_EXIT(&rx_stats_mutex);
6751 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6753 /* Apply VanJacobson round-trip estimations */
6758 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6759 * srtt is stored as fixed point with 3 bits after the binary
6760 * point (i.e., scaled by 8). The following magic is
6761 * equivalent to the smoothing algorithm in rfc793 with an
6762 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6763 * srtt'*8 = rtt + srtt*7
6764 * srtt'*8 = srtt*8 + rtt - srtt
6765 * srtt' = srtt + rtt/8 - srtt/8
6766 * srtt' = srtt + (rtt - srtt)/8
6769 delta = _8THMSEC(&thisRtt) - call->rtt;
6770 call->rtt += (delta >> 3);
6773 * We accumulate a smoothed rtt variance (actually, a smoothed
6774 * mean difference), then set the retransmit timer to smoothed
6775 * rtt + 4 times the smoothed variance (was 2x in van's original
6776 * paper, but 4x works better for me, and apparently for him as
6778 * rttvar is stored as
6779 * fixed point with 2 bits after the binary point (scaled by
6780 * 4). The following is equivalent to rfc793 smoothing with
6781 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6782 * rttvar'*4 = rttvar*3 + |delta|
6783 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6784 * rttvar' = rttvar + |delta|/4 - rttvar/4
6785 * rttvar' = rttvar + (|delta| - rttvar)/4
6786 * This replaces rfc793's wired-in beta.
6787 * dev*4 = dev*4 + (|actual - expected| - dev)
6793 delta -= (call->rtt_dev << 1);
6794 call->rtt_dev += (delta >> 3);
6796 /* I don't have a stored RTT so I start with this value. Since I'm
6797 * probably just starting a call, and will be pushing more data down
6798 * this, I expect congestion to increase rapidly. So I fudge a
6799 * little, and I set deviance to half the rtt. In practice,
6800 * deviance tends to approach something a little less than
6801 * half the smoothed rtt. */
6802 call->rtt = _8THMSEC(&thisRtt) + 8;
6803 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6805 /* the smoothed RTT time is RTT + 4*MDEV
6807 * We allow a user specified minimum to be set for this, to allow clamping
6808 * at a minimum value in the same way as TCP. In addition, we have to allow
6809 * for the possibility that this packet is answered by a delayed ACK, so we
6810 * add on a fixed 200ms to account for that timer expiring.
6813 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6814 rx_minPeerTimeout) + 200;
6815 clock_Zero(&call->rto);
6816 clock_Addmsec(&call->rto, rtt_timeout);
6818 /* Update the peer, so any new calls start with our values */
6819 peer->rtt_dev = call->rtt_dev;
6820 peer->rtt = call->rtt;
6822 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6823 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6827 /* Find all server connections that have not been active for a long time, and
6830 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6833 struct clock now, when;
6834 clock_GetTime(&now);
6836 /* Find server connection structures that haven't been used for
6837 * greater than rx_idleConnectionTime */
6839 struct rx_connection **conn_ptr, **conn_end;
6840 int i, havecalls = 0;
6841 MUTEX_ENTER(&rx_connHashTable_lock);
6842 for (conn_ptr = &rx_connHashTable[0], conn_end =
6843 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6845 struct rx_connection *conn, *next;
6846 struct rx_call *call;
6850 for (conn = *conn_ptr; conn; conn = next) {
6851 /* XXX -- Shouldn't the connection be locked? */
6854 for (i = 0; i < RX_MAXCALLS; i++) {
6855 call = conn->call[i];
6859 code = MUTEX_TRYENTER(&call->lock);
6862 #ifdef RX_ENABLE_LOCKS
6863 result = rxi_CheckCall(call, 1);
6864 #else /* RX_ENABLE_LOCKS */
6865 result = rxi_CheckCall(call);
6866 #endif /* RX_ENABLE_LOCKS */
6867 MUTEX_EXIT(&call->lock);
6869 /* If CheckCall freed the call, it might
6870 * have destroyed the connection as well,
6871 * which screws up the linked lists.
6877 if (conn->type == RX_SERVER_CONNECTION) {
6878 /* This only actually destroys the connection if
6879 * there are no outstanding calls */
6880 MUTEX_ENTER(&conn->conn_data_lock);
6881 MUTEX_ENTER(&rx_refcnt_mutex);
6882 if (!havecalls && !conn->refCount
6883 && ((conn->lastSendTime + rx_idleConnectionTime) <
6885 conn->refCount++; /* it will be decr in rx_DestroyConn */
6886 MUTEX_EXIT(&rx_refcnt_mutex);
6887 MUTEX_EXIT(&conn->conn_data_lock);
6888 #ifdef RX_ENABLE_LOCKS
6889 rxi_DestroyConnectionNoLock(conn);
6890 #else /* RX_ENABLE_LOCKS */
6891 rxi_DestroyConnection(conn);
6892 #endif /* RX_ENABLE_LOCKS */
6894 #ifdef RX_ENABLE_LOCKS
6896 MUTEX_EXIT(&rx_refcnt_mutex);
6897 MUTEX_EXIT(&conn->conn_data_lock);
6899 #endif /* RX_ENABLE_LOCKS */
6903 #ifdef RX_ENABLE_LOCKS
6904 while (rx_connCleanup_list) {
6905 struct rx_connection *conn;
6906 conn = rx_connCleanup_list;
6907 rx_connCleanup_list = rx_connCleanup_list->next;
6908 MUTEX_EXIT(&rx_connHashTable_lock);
6909 rxi_CleanupConnection(conn);
6910 MUTEX_ENTER(&rx_connHashTable_lock);
6912 MUTEX_EXIT(&rx_connHashTable_lock);
6913 #endif /* RX_ENABLE_LOCKS */
6916 /* Find any peer structures that haven't been used (haven't had an
6917 * associated connection) for greater than rx_idlePeerTime */
6919 struct rx_peer **peer_ptr, **peer_end;
6923 * Why do we need to hold the rx_peerHashTable_lock across
6924 * the incrementing of peer_ptr since the rx_peerHashTable
6925 * array is not changing? We don't.
6927 * By dropping the lock periodically we can permit other
6928 * activities to be performed while a rxi_ReapConnections
6929 * call is in progress. The goal of reap connections
6930 * is to clean up quickly without causing large amounts
6931 * of contention. Therefore, it is important that global
6932 * mutexes not be held for extended periods of time.
6934 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6935 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6937 struct rx_peer *peer, *next, *prev;
6939 MUTEX_ENTER(&rx_peerHashTable_lock);
6940 for (prev = peer = *peer_ptr; peer; peer = next) {
6942 code = MUTEX_TRYENTER(&peer->peer_lock);
6943 if ((code) && (peer->refCount == 0)
6944 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6945 rx_interface_stat_p rpc_stat, nrpc_stat;
6949 * now know that this peer object is one to be
6950 * removed from the hash table. Once it is removed
6951 * it can't be referenced by other threads.
6952 * Lets remove it first and decrement the struct
6953 * nPeerStructs count.
6955 if (peer == *peer_ptr) {
6961 if (rx_stats_active)
6962 rx_atomic_dec(&rx_stats.nPeerStructs);
6965 * Now if we hold references on 'prev' and 'next'
6966 * we can safely drop the rx_peerHashTable_lock
6967 * while we destroy this 'peer' object.
6973 MUTEX_EXIT(&rx_peerHashTable_lock);
6975 MUTEX_EXIT(&peer->peer_lock);
6976 MUTEX_DESTROY(&peer->peer_lock);
6978 (&peer->rpcStats, rpc_stat, nrpc_stat,
6979 rx_interface_stat)) {
6980 unsigned int num_funcs;
6983 queue_Remove(&rpc_stat->queue_header);
6984 queue_Remove(&rpc_stat->all_peers);
6985 num_funcs = rpc_stat->stats[0].func_total;
6987 sizeof(rx_interface_stat_t) +
6988 rpc_stat->stats[0].func_total *
6989 sizeof(rx_function_entry_v1_t);
6991 rxi_Free(rpc_stat, space);
6993 MUTEX_ENTER(&rx_rpc_stats);
6994 rxi_rpc_peer_stat_cnt -= num_funcs;
6995 MUTEX_EXIT(&rx_rpc_stats);
7000 * Regain the rx_peerHashTable_lock and
7001 * decrement the reference count on 'prev'
7004 MUTEX_ENTER(&rx_peerHashTable_lock);
7011 MUTEX_EXIT(&peer->peer_lock);
7016 MUTEX_EXIT(&rx_peerHashTable_lock);
7020 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7021 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7022 * GC, just below. Really, we shouldn't have to keep moving packets from
7023 * one place to another, but instead ought to always know if we can
7024 * afford to hold onto a packet in its particular use. */
7025 MUTEX_ENTER(&rx_freePktQ_lock);
7026 if (rx_waitingForPackets) {
7027 rx_waitingForPackets = 0;
7028 #ifdef RX_ENABLE_LOCKS
7029 CV_BROADCAST(&rx_waitingForPackets_cv);
7031 osi_rxWakeup(&rx_waitingForPackets);
7034 MUTEX_EXIT(&rx_freePktQ_lock);
7037 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7038 rxevent_Put(rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0));
7042 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7043 * rx.h is sort of strange this is better. This is called with a security
7044 * object before it is discarded. Each connection using a security object has
7045 * its own refcount to the object so it won't actually be freed until the last
7046 * connection is destroyed.
7048 * This is the only rxs module call. A hold could also be written but no one
7052 rxs_Release(struct rx_securityClass *aobj)
7054 return RXS_Close(aobj);
7062 #define TRACE_OPTION_RX_DEBUG 16
7070 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7071 0, KEY_QUERY_VALUE, &parmKey);
7072 if (code != ERROR_SUCCESS)
7075 dummyLen = sizeof(TraceOption);
7076 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7077 (BYTE *) &TraceOption, &dummyLen);
7078 if (code == ERROR_SUCCESS) {
7079 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7081 RegCloseKey (parmKey);
7082 #endif /* AFS_NT40_ENV */
7087 rx_DebugOnOff(int on)
7091 rxdebug_active = on;
7097 rx_StatsOnOff(int on)
7099 rx_stats_active = on;
7103 /* Don't call this debugging routine directly; use dpf */
7105 rxi_DebugPrint(char *format, ...)
7114 va_start(ap, format);
7116 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7119 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7121 OutputDebugString(msg);
7127 va_start(ap, format);
7129 clock_GetTime(&now);
7130 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7131 (unsigned int)now.usec);
7132 vfprintf(rx_Log, format, ap);
7140 * This function is used to process the rx_stats structure that is local
7141 * to a process as well as an rx_stats structure received from a remote
7142 * process (via rxdebug). Therefore, it needs to do minimal version
7146 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7147 afs_int32 freePackets, char version)
7151 if (size != sizeof(struct rx_statistics)) {
7153 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7154 size, sizeof(struct rx_statistics));
7157 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7160 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7161 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7162 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7163 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7164 s->specialPktAllocFailures);
7166 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7167 s->receivePktAllocFailures, s->sendPktAllocFailures,
7168 s->specialPktAllocFailures);
7172 " greedy %u, " "bogusReads %u (last from host %x), "
7173 "noPackets %u, " "noBuffers %u, " "selects %u, "
7174 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7175 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7176 s->selects, s->sendSelects);
7178 fprintf(file, " packets read: ");
7179 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7180 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7182 fprintf(file, "\n");
7185 " other read counters: data %u, " "ack %u, " "dup %u "
7186 "spurious %u " "dally %u\n", s->dataPacketsRead,
7187 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7188 s->ignorePacketDally);
7190 fprintf(file, " packets sent: ");
7191 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7192 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7194 fprintf(file, "\n");
7197 " other send counters: ack %u, " "data %u (not resends), "
7198 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7199 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7200 s->dataPacketsPushed, s->ignoreAckedPacket);
7203 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7204 s->netSendFailures, (int)s->fatalErrors);
7206 if (s->nRttSamples) {
7207 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7208 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7210 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7211 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7215 " %d server connections, " "%d client connections, "
7216 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7217 s->nServerConns, s->nClientConns, s->nPeerStructs,
7218 s->nCallStructs, s->nFreeCallStructs);
7220 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7221 fprintf(file, " %d clock updates\n", clock_nUpdates);
7225 /* for backward compatibility */
7227 rx_PrintStats(FILE * file)
7229 MUTEX_ENTER(&rx_stats_mutex);
7230 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7231 sizeof(rx_stats), rx_nFreePackets,
7233 MUTEX_EXIT(&rx_stats_mutex);
7237 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7239 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7240 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7241 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7244 " Rtt %d, " "total sent %d, " "resent %d\n",
7245 peer->rtt, peer->nSent, peer->reSends);
7248 " Packet size %d, " "max in packet skew %d, "
7249 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7250 (int)peer->outPacketSkew);
7254 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7256 * This mutex protects the following static variables:
7260 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7261 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7263 #define LOCK_RX_DEBUG
7264 #define UNLOCK_RX_DEBUG
7265 #endif /* AFS_PTHREAD_ENV */
7267 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7269 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7270 u_char type, void *inputData, size_t inputLength,
7271 void *outputData, size_t outputLength)
7273 static afs_int32 counter = 100;
7274 time_t waitTime, waitCount;
7275 struct rx_header theader;
7278 struct timeval tv_now, tv_wake, tv_delta;
7279 struct sockaddr_in taddr, faddr;
7293 tp = &tbuffer[sizeof(struct rx_header)];
7294 taddr.sin_family = AF_INET;
7295 taddr.sin_port = remotePort;
7296 taddr.sin_addr.s_addr = remoteAddr;
7297 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7298 taddr.sin_len = sizeof(struct sockaddr_in);
7301 memset(&theader, 0, sizeof(theader));
7302 theader.epoch = htonl(999);
7304 theader.callNumber = htonl(counter);
7307 theader.type = type;
7308 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7309 theader.serviceId = 0;
7311 memcpy(tbuffer, &theader, sizeof(theader));
7312 memcpy(tp, inputData, inputLength);
7314 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7315 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7317 /* see if there's a packet available */
7318 gettimeofday(&tv_wake, NULL);
7319 tv_wake.tv_sec += waitTime;
7322 FD_SET(socket, &imask);
7323 tv_delta.tv_sec = tv_wake.tv_sec;
7324 tv_delta.tv_usec = tv_wake.tv_usec;
7325 gettimeofday(&tv_now, NULL);
7327 if (tv_delta.tv_usec < tv_now.tv_usec) {
7329 tv_delta.tv_usec += 1000000;
7332 tv_delta.tv_usec -= tv_now.tv_usec;
7334 if (tv_delta.tv_sec < tv_now.tv_sec) {
7338 tv_delta.tv_sec -= tv_now.tv_sec;
7341 code = select(0, &imask, 0, 0, &tv_delta);
7342 #else /* AFS_NT40_ENV */
7343 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7344 #endif /* AFS_NT40_ENV */
7345 if (code == 1 && FD_ISSET(socket, &imask)) {
7346 /* now receive a packet */
7347 faddrLen = sizeof(struct sockaddr_in);
7349 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7350 (struct sockaddr *)&faddr, &faddrLen);
7353 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7354 if (counter == ntohl(theader.callNumber))
7362 /* see if we've timed out */
7370 code -= sizeof(struct rx_header);
7371 if (code > outputLength)
7372 code = outputLength;
7373 memcpy(outputData, tp, code);
7376 #endif /* RXDEBUG */
7379 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7380 afs_uint16 remotePort, struct rx_debugStats * stat,
7381 afs_uint32 * supportedValues)
7383 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7385 struct rx_debugIn in;
7387 *supportedValues = 0;
7388 in.type = htonl(RX_DEBUGI_GETSTATS);
7391 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7392 &in, sizeof(in), stat, sizeof(*stat));
7395 * If the call was successful, fixup the version and indicate
7396 * what contents of the stat structure are valid.
7397 * Also do net to host conversion of fields here.
7401 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7402 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7404 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7405 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7407 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7408 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7410 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7411 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7413 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7414 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7416 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7417 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7419 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7420 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7422 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7423 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7425 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7426 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7428 stat->nFreePackets = ntohl(stat->nFreePackets);
7429 stat->packetReclaims = ntohl(stat->packetReclaims);
7430 stat->callsExecuted = ntohl(stat->callsExecuted);
7431 stat->nWaiting = ntohl(stat->nWaiting);
7432 stat->idleThreads = ntohl(stat->idleThreads);
7433 stat->nWaited = ntohl(stat->nWaited);
7434 stat->nPackets = ntohl(stat->nPackets);
7443 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7444 afs_uint16 remotePort, struct rx_statistics * stat,
7445 afs_uint32 * supportedValues)
7447 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7449 struct rx_debugIn in;
7450 afs_int32 *lp = (afs_int32 *) stat;
7454 * supportedValues is currently unused, but added to allow future
7455 * versioning of this function.
7458 *supportedValues = 0;
7459 in.type = htonl(RX_DEBUGI_RXSTATS);
7461 memset(stat, 0, sizeof(*stat));
7463 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7464 &in, sizeof(in), stat, sizeof(*stat));
7469 * Do net to host conversion here
7472 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7483 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7484 afs_uint16 remotePort, size_t version_length,
7487 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7489 return MakeDebugCall(socket, remoteAddr, remotePort,
7490 RX_PACKET_TYPE_VERSION, a, 1, version,
7498 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7499 afs_uint16 remotePort, afs_int32 * nextConnection,
7500 int allConnections, afs_uint32 debugSupportedValues,
7501 struct rx_debugConn * conn,
7502 afs_uint32 * supportedValues)
7504 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7506 struct rx_debugIn in;
7510 * supportedValues is currently unused, but added to allow future
7511 * versioning of this function.
7514 *supportedValues = 0;
7515 if (allConnections) {
7516 in.type = htonl(RX_DEBUGI_GETALLCONN);
7518 in.type = htonl(RX_DEBUGI_GETCONN);
7520 in.index = htonl(*nextConnection);
7521 memset(conn, 0, sizeof(*conn));
7523 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7524 &in, sizeof(in), conn, sizeof(*conn));
7527 *nextConnection += 1;
7530 * Convert old connection format to new structure.
7533 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7534 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7535 #define MOVEvL(a) (conn->a = vL->a)
7537 /* any old or unrecognized version... */
7538 for (i = 0; i < RX_MAXCALLS; i++) {
7539 MOVEvL(callState[i]);
7540 MOVEvL(callMode[i]);
7541 MOVEvL(callFlags[i]);
7542 MOVEvL(callOther[i]);
7544 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7545 MOVEvL(secStats.type);
7546 MOVEvL(secStats.level);
7547 MOVEvL(secStats.flags);
7548 MOVEvL(secStats.expires);
7549 MOVEvL(secStats.packetsReceived);
7550 MOVEvL(secStats.packetsSent);
7551 MOVEvL(secStats.bytesReceived);
7552 MOVEvL(secStats.bytesSent);
7557 * Do net to host conversion here
7559 * I don't convert host or port since we are most likely
7560 * going to want these in NBO.
7562 conn->cid = ntohl(conn->cid);
7563 conn->serial = ntohl(conn->serial);
7564 for (i = 0; i < RX_MAXCALLS; i++) {
7565 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7567 conn->error = ntohl(conn->error);
7568 conn->secStats.flags = ntohl(conn->secStats.flags);
7569 conn->secStats.expires = ntohl(conn->secStats.expires);
7570 conn->secStats.packetsReceived =
7571 ntohl(conn->secStats.packetsReceived);
7572 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7573 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7574 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7575 conn->epoch = ntohl(conn->epoch);
7576 conn->natMTU = ntohl(conn->natMTU);
7585 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7586 afs_uint16 remotePort, afs_int32 * nextPeer,
7587 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7588 afs_uint32 * supportedValues)
7590 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7592 struct rx_debugIn in;
7595 * supportedValues is currently unused, but added to allow future
7596 * versioning of this function.
7599 *supportedValues = 0;
7600 in.type = htonl(RX_DEBUGI_GETPEER);
7601 in.index = htonl(*nextPeer);
7602 memset(peer, 0, sizeof(*peer));
7604 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7605 &in, sizeof(in), peer, sizeof(*peer));
7611 * Do net to host conversion here
7613 * I don't convert host or port since we are most likely
7614 * going to want these in NBO.
7616 peer->ifMTU = ntohs(peer->ifMTU);
7617 peer->idleWhen = ntohl(peer->idleWhen);
7618 peer->refCount = ntohs(peer->refCount);
7619 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7620 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7621 peer->rtt = ntohl(peer->rtt);
7622 peer->rtt_dev = ntohl(peer->rtt_dev);
7623 peer->timeout.sec = 0;
7624 peer->timeout.usec = 0;
7625 peer->nSent = ntohl(peer->nSent);
7626 peer->reSends = ntohl(peer->reSends);
7627 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7628 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7629 peer->natMTU = ntohs(peer->natMTU);
7630 peer->maxMTU = ntohs(peer->maxMTU);
7631 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7632 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7633 peer->MTU = ntohs(peer->MTU);
7634 peer->cwind = ntohs(peer->cwind);
7635 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7636 peer->congestSeq = ntohs(peer->congestSeq);
7637 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7638 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7639 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7640 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7649 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7650 struct rx_debugPeer * peerStats)
7653 afs_int32 error = 1; /* default to "did not succeed" */
7654 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7656 MUTEX_ENTER(&rx_peerHashTable_lock);
7657 for(tp = rx_peerHashTable[hashValue];
7658 tp != NULL; tp = tp->next) {
7659 if (tp->host == peerHost)
7665 MUTEX_EXIT(&rx_peerHashTable_lock);
7669 MUTEX_ENTER(&tp->peer_lock);
7670 peerStats->host = tp->host;
7671 peerStats->port = tp->port;
7672 peerStats->ifMTU = tp->ifMTU;
7673 peerStats->idleWhen = tp->idleWhen;
7674 peerStats->refCount = tp->refCount;
7675 peerStats->burstSize = tp->burstSize;
7676 peerStats->burst = tp->burst;
7677 peerStats->burstWait.sec = tp->burstWait.sec;
7678 peerStats->burstWait.usec = tp->burstWait.usec;
7679 peerStats->rtt = tp->rtt;
7680 peerStats->rtt_dev = tp->rtt_dev;
7681 peerStats->timeout.sec = 0;
7682 peerStats->timeout.usec = 0;
7683 peerStats->nSent = tp->nSent;
7684 peerStats->reSends = tp->reSends;
7685 peerStats->inPacketSkew = tp->inPacketSkew;
7686 peerStats->outPacketSkew = tp->outPacketSkew;
7687 peerStats->natMTU = tp->natMTU;
7688 peerStats->maxMTU = tp->maxMTU;
7689 peerStats->maxDgramPackets = tp->maxDgramPackets;
7690 peerStats->ifDgramPackets = tp->ifDgramPackets;
7691 peerStats->MTU = tp->MTU;
7692 peerStats->cwind = tp->cwind;
7693 peerStats->nDgramPackets = tp->nDgramPackets;
7694 peerStats->congestSeq = tp->congestSeq;
7695 peerStats->bytesSent.high = tp->bytesSent.high;
7696 peerStats->bytesSent.low = tp->bytesSent.low;
7697 peerStats->bytesReceived.high = tp->bytesReceived.high;
7698 peerStats->bytesReceived.low = tp->bytesReceived.low;
7699 MUTEX_EXIT(&tp->peer_lock);
7701 MUTEX_ENTER(&rx_peerHashTable_lock);
7704 MUTEX_EXIT(&rx_peerHashTable_lock);
7712 struct rx_serverQueueEntry *np;
7715 struct rx_call *call;
7716 struct rx_serverQueueEntry *sq;
7720 if (rxinit_status == 1) {
7722 return; /* Already shutdown. */
7726 #ifndef AFS_PTHREAD_ENV
7727 FD_ZERO(&rx_selectMask);
7728 #endif /* AFS_PTHREAD_ENV */
7729 rxi_dataQuota = RX_MAX_QUOTA;
7730 #ifndef AFS_PTHREAD_ENV
7732 #endif /* AFS_PTHREAD_ENV */
7735 #ifndef AFS_PTHREAD_ENV
7736 #ifndef AFS_USE_GETTIMEOFDAY
7738 #endif /* AFS_USE_GETTIMEOFDAY */
7739 #endif /* AFS_PTHREAD_ENV */
7741 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7742 call = queue_First(&rx_freeCallQueue, rx_call);
7744 rxi_Free(call, sizeof(struct rx_call));
7747 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7748 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7754 struct rx_peer **peer_ptr, **peer_end;
7755 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7756 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7758 struct rx_peer *peer, *next;
7760 MUTEX_ENTER(&rx_peerHashTable_lock);
7761 for (peer = *peer_ptr; peer; peer = next) {
7762 rx_interface_stat_p rpc_stat, nrpc_stat;
7765 MUTEX_ENTER(&rx_rpc_stats);
7766 MUTEX_ENTER(&peer->peer_lock);
7768 (&peer->rpcStats, rpc_stat, nrpc_stat,
7769 rx_interface_stat)) {
7770 unsigned int num_funcs;
7773 queue_Remove(&rpc_stat->queue_header);
7774 queue_Remove(&rpc_stat->all_peers);
7775 num_funcs = rpc_stat->stats[0].func_total;
7777 sizeof(rx_interface_stat_t) +
7778 rpc_stat->stats[0].func_total *
7779 sizeof(rx_function_entry_v1_t);
7781 rxi_Free(rpc_stat, space);
7783 /* rx_rpc_stats must be held */
7784 rxi_rpc_peer_stat_cnt -= num_funcs;
7786 MUTEX_EXIT(&peer->peer_lock);
7787 MUTEX_EXIT(&rx_rpc_stats);
7791 if (rx_stats_active)
7792 rx_atomic_dec(&rx_stats.nPeerStructs);
7794 MUTEX_EXIT(&rx_peerHashTable_lock);
7797 for (i = 0; i < RX_MAX_SERVICES; i++) {
7799 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7801 for (i = 0; i < rx_hashTableSize; i++) {
7802 struct rx_connection *tc, *ntc;
7803 MUTEX_ENTER(&rx_connHashTable_lock);
7804 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7806 for (j = 0; j < RX_MAXCALLS; j++) {
7808 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7811 rxi_Free(tc, sizeof(*tc));
7813 MUTEX_EXIT(&rx_connHashTable_lock);
7816 MUTEX_ENTER(&freeSQEList_lock);
7818 while ((np = rx_FreeSQEList)) {
7819 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7820 MUTEX_DESTROY(&np->lock);
7821 rxi_Free(np, sizeof(*np));
7824 MUTEX_EXIT(&freeSQEList_lock);
7825 MUTEX_DESTROY(&freeSQEList_lock);
7826 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7827 MUTEX_DESTROY(&rx_connHashTable_lock);
7828 MUTEX_DESTROY(&rx_peerHashTable_lock);
7829 MUTEX_DESTROY(&rx_serverPool_lock);
7831 osi_Free(rx_connHashTable,
7832 rx_hashTableSize * sizeof(struct rx_connection *));
7833 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7835 UNPIN(rx_connHashTable,
7836 rx_hashTableSize * sizeof(struct rx_connection *));
7837 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7839 rxi_FreeAllPackets();
7841 MUTEX_ENTER(&rx_quota_mutex);
7842 rxi_dataQuota = RX_MAX_QUOTA;
7843 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7844 MUTEX_EXIT(&rx_quota_mutex);
7849 #ifdef RX_ENABLE_LOCKS
7851 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7853 if (!MUTEX_ISMINE(lockaddr))
7854 osi_Panic("Lock not held: %s", msg);
7856 #endif /* RX_ENABLE_LOCKS */
7861 * Routines to implement connection specific data.
7865 rx_KeyCreate(rx_destructor_t rtn)
7868 MUTEX_ENTER(&rxi_keyCreate_lock);
7869 key = rxi_keyCreate_counter++;
7870 rxi_keyCreate_destructor = (rx_destructor_t *)
7871 realloc((void *)rxi_keyCreate_destructor,
7872 (key + 1) * sizeof(rx_destructor_t));
7873 rxi_keyCreate_destructor[key] = rtn;
7874 MUTEX_EXIT(&rxi_keyCreate_lock);
7879 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7882 MUTEX_ENTER(&conn->conn_data_lock);
7883 if (!conn->specific) {
7884 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7885 for (i = 0; i < key; i++)
7886 conn->specific[i] = NULL;
7887 conn->nSpecific = key + 1;
7888 conn->specific[key] = ptr;
7889 } else if (key >= conn->nSpecific) {
7890 conn->specific = (void **)
7891 realloc(conn->specific, (key + 1) * sizeof(void *));
7892 for (i = conn->nSpecific; i < key; i++)
7893 conn->specific[i] = NULL;
7894 conn->nSpecific = key + 1;
7895 conn->specific[key] = ptr;
7897 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7898 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7899 conn->specific[key] = ptr;
7901 MUTEX_EXIT(&conn->conn_data_lock);
7905 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7908 MUTEX_ENTER(&svc->svc_data_lock);
7909 if (!svc->specific) {
7910 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7911 for (i = 0; i < key; i++)
7912 svc->specific[i] = NULL;
7913 svc->nSpecific = key + 1;
7914 svc->specific[key] = ptr;
7915 } else if (key >= svc->nSpecific) {
7916 svc->specific = (void **)
7917 realloc(svc->specific, (key + 1) * sizeof(void *));
7918 for (i = svc->nSpecific; i < key; i++)
7919 svc->specific[i] = NULL;
7920 svc->nSpecific = key + 1;
7921 svc->specific[key] = ptr;
7923 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7924 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7925 svc->specific[key] = ptr;
7927 MUTEX_EXIT(&svc->svc_data_lock);
7931 rx_GetSpecific(struct rx_connection *conn, int key)
7934 MUTEX_ENTER(&conn->conn_data_lock);
7935 if (key >= conn->nSpecific)
7938 ptr = conn->specific[key];
7939 MUTEX_EXIT(&conn->conn_data_lock);
7944 rx_GetServiceSpecific(struct rx_service *svc, int key)
7947 MUTEX_ENTER(&svc->svc_data_lock);
7948 if (key >= svc->nSpecific)
7951 ptr = svc->specific[key];
7952 MUTEX_EXIT(&svc->svc_data_lock);
7957 #endif /* !KERNEL */
7960 * processStats is a queue used to store the statistics for the local
7961 * process. Its contents are similar to the contents of the rpcStats
7962 * queue on a rx_peer structure, but the actual data stored within
7963 * this queue contains totals across the lifetime of the process (assuming
7964 * the stats have not been reset) - unlike the per peer structures
7965 * which can come and go based upon the peer lifetime.
7968 static struct rx_queue processStats = { &processStats, &processStats };
7971 * peerStats is a queue used to store the statistics for all peer structs.
7972 * Its contents are the union of all the peer rpcStats queues.
7975 static struct rx_queue peerStats = { &peerStats, &peerStats };
7978 * rxi_monitor_processStats is used to turn process wide stat collection
7982 static int rxi_monitor_processStats = 0;
7985 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7988 static int rxi_monitor_peerStats = 0;
7991 * rxi_AddRpcStat - given all of the information for a particular rpc
7992 * call, create (if needed) and update the stat totals for the rpc.
7996 * IN stats - the queue of stats that will be updated with the new value
7998 * IN rxInterface - a unique number that identifies the rpc interface
8000 * IN currentFunc - the index of the function being invoked
8002 * IN totalFunc - the total number of functions in this interface
8004 * IN queueTime - the amount of time this function waited for a thread
8006 * IN execTime - the amount of time this function invocation took to execute
8008 * IN bytesSent - the number bytes sent by this invocation
8010 * IN bytesRcvd - the number bytes received by this invocation
8012 * IN isServer - if true, this invocation was made to a server
8014 * IN remoteHost - the ip address of the remote host
8016 * IN remotePort - the port of the remote host
8018 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8020 * INOUT counter - if a new stats structure is allocated, the counter will
8021 * be updated with the new number of allocated stat structures
8029 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8030 afs_uint32 currentFunc, afs_uint32 totalFunc,
8031 struct clock *queueTime, struct clock *execTime,
8032 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8033 afs_uint32 remoteHost, afs_uint32 remotePort,
8034 int addToPeerList, unsigned int *counter)
8037 rx_interface_stat_p rpc_stat, nrpc_stat;
8040 * See if there's already a structure for this interface
8043 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8044 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8045 && (rpc_stat->stats[0].remote_is_server == isServer))
8050 * Didn't find a match so allocate a new structure and add it to the
8054 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8055 || (rpc_stat->stats[0].interfaceId != rxInterface)
8056 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8061 sizeof(rx_interface_stat_t) +
8062 totalFunc * sizeof(rx_function_entry_v1_t);
8064 rpc_stat = rxi_Alloc(space);
8065 if (rpc_stat == NULL) {
8069 *counter += totalFunc;
8070 for (i = 0; i < totalFunc; i++) {
8071 rpc_stat->stats[i].remote_peer = remoteHost;
8072 rpc_stat->stats[i].remote_port = remotePort;
8073 rpc_stat->stats[i].remote_is_server = isServer;
8074 rpc_stat->stats[i].interfaceId = rxInterface;
8075 rpc_stat->stats[i].func_total = totalFunc;
8076 rpc_stat->stats[i].func_index = i;
8077 hzero(rpc_stat->stats[i].invocations);
8078 hzero(rpc_stat->stats[i].bytes_sent);
8079 hzero(rpc_stat->stats[i].bytes_rcvd);
8080 rpc_stat->stats[i].queue_time_sum.sec = 0;
8081 rpc_stat->stats[i].queue_time_sum.usec = 0;
8082 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8083 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8084 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8085 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8086 rpc_stat->stats[i].queue_time_max.sec = 0;
8087 rpc_stat->stats[i].queue_time_max.usec = 0;
8088 rpc_stat->stats[i].execution_time_sum.sec = 0;
8089 rpc_stat->stats[i].execution_time_sum.usec = 0;
8090 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8091 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8092 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8093 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8094 rpc_stat->stats[i].execution_time_max.sec = 0;
8095 rpc_stat->stats[i].execution_time_max.usec = 0;
8097 queue_Prepend(stats, rpc_stat);
8098 if (addToPeerList) {
8099 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8104 * Increment the stats for this function
8107 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8108 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8109 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8110 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8111 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8112 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8113 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8115 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8116 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8118 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8119 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8121 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8122 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8124 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8125 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8133 * rx_IncrementTimeAndCount - increment the times and count for a particular
8138 * IN peer - the peer who invoked the rpc
8140 * IN rxInterface - a unique number that identifies the rpc interface
8142 * IN currentFunc - the index of the function being invoked
8144 * IN totalFunc - the total number of functions in this interface
8146 * IN queueTime - the amount of time this function waited for a thread
8148 * IN execTime - the amount of time this function invocation took to execute
8150 * IN bytesSent - the number bytes sent by this invocation
8152 * IN bytesRcvd - the number bytes received by this invocation
8154 * IN isServer - if true, this invocation was made to a server
8162 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8163 afs_uint32 currentFunc, afs_uint32 totalFunc,
8164 struct clock *queueTime, struct clock *execTime,
8165 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8169 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8172 MUTEX_ENTER(&rx_rpc_stats);
8174 if (rxi_monitor_peerStats) {
8175 MUTEX_ENTER(&peer->peer_lock);
8176 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8177 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8178 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8179 MUTEX_EXIT(&peer->peer_lock);
8182 if (rxi_monitor_processStats) {
8183 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8184 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8185 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8188 MUTEX_EXIT(&rx_rpc_stats);
8193 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8197 * IN callerVersion - the rpc stat version of the caller.
8199 * IN count - the number of entries to marshall.
8201 * IN stats - pointer to stats to be marshalled.
8203 * OUT ptr - Where to store the marshalled data.
8210 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8211 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8217 * We only support the first version
8219 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8220 *(ptr++) = stats->remote_peer;
8221 *(ptr++) = stats->remote_port;
8222 *(ptr++) = stats->remote_is_server;
8223 *(ptr++) = stats->interfaceId;
8224 *(ptr++) = stats->func_total;
8225 *(ptr++) = stats->func_index;
8226 *(ptr++) = hgethi(stats->invocations);
8227 *(ptr++) = hgetlo(stats->invocations);
8228 *(ptr++) = hgethi(stats->bytes_sent);
8229 *(ptr++) = hgetlo(stats->bytes_sent);
8230 *(ptr++) = hgethi(stats->bytes_rcvd);
8231 *(ptr++) = hgetlo(stats->bytes_rcvd);
8232 *(ptr++) = stats->queue_time_sum.sec;
8233 *(ptr++) = stats->queue_time_sum.usec;
8234 *(ptr++) = stats->queue_time_sum_sqr.sec;
8235 *(ptr++) = stats->queue_time_sum_sqr.usec;
8236 *(ptr++) = stats->queue_time_min.sec;
8237 *(ptr++) = stats->queue_time_min.usec;
8238 *(ptr++) = stats->queue_time_max.sec;
8239 *(ptr++) = stats->queue_time_max.usec;
8240 *(ptr++) = stats->execution_time_sum.sec;
8241 *(ptr++) = stats->execution_time_sum.usec;
8242 *(ptr++) = stats->execution_time_sum_sqr.sec;
8243 *(ptr++) = stats->execution_time_sum_sqr.usec;
8244 *(ptr++) = stats->execution_time_min.sec;
8245 *(ptr++) = stats->execution_time_min.usec;
8246 *(ptr++) = stats->execution_time_max.sec;
8247 *(ptr++) = stats->execution_time_max.usec;
8253 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8258 * IN callerVersion - the rpc stat version of the caller
8260 * OUT myVersion - the rpc stat version of this function
8262 * OUT clock_sec - local time seconds
8264 * OUT clock_usec - local time microseconds
8266 * OUT allocSize - the number of bytes allocated to contain stats
8268 * OUT statCount - the number stats retrieved from this process.
8270 * OUT stats - the actual stats retrieved from this process.
8274 * Returns void. If successful, stats will != NULL.
8278 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8279 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8280 size_t * allocSize, afs_uint32 * statCount,
8281 afs_uint32 ** stats)
8291 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8294 * Check to see if stats are enabled
8297 MUTEX_ENTER(&rx_rpc_stats);
8298 if (!rxi_monitor_processStats) {
8299 MUTEX_EXIT(&rx_rpc_stats);
8303 clock_GetTime(&now);
8304 *clock_sec = now.sec;
8305 *clock_usec = now.usec;
8308 * Allocate the space based upon the caller version
8310 * If the client is at an older version than we are,
8311 * we return the statistic data in the older data format, but
8312 * we still return our version number so the client knows we
8313 * are maintaining more data than it can retrieve.
8316 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8317 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8318 *statCount = rxi_rpc_process_stat_cnt;
8321 * This can't happen yet, but in the future version changes
8322 * can be handled by adding additional code here
8326 if (space > (size_t) 0) {
8328 ptr = *stats = rxi_Alloc(space);
8331 rx_interface_stat_p rpc_stat, nrpc_stat;
8335 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8337 * Copy the data based upon the caller version
8339 rx_MarshallProcessRPCStats(callerVersion,
8340 rpc_stat->stats[0].func_total,
8341 rpc_stat->stats, &ptr);
8347 MUTEX_EXIT(&rx_rpc_stats);
8352 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8356 * IN callerVersion - the rpc stat version of the caller
8358 * OUT myVersion - the rpc stat version of this function
8360 * OUT clock_sec - local time seconds
8362 * OUT clock_usec - local time microseconds
8364 * OUT allocSize - the number of bytes allocated to contain stats
8366 * OUT statCount - the number of stats retrieved from the individual
8369 * OUT stats - the actual stats retrieved from the individual peer structures.
8373 * Returns void. If successful, stats will != NULL.
8377 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8378 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8379 size_t * allocSize, afs_uint32 * statCount,
8380 afs_uint32 ** stats)
8390 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8393 * Check to see if stats are enabled
8396 MUTEX_ENTER(&rx_rpc_stats);
8397 if (!rxi_monitor_peerStats) {
8398 MUTEX_EXIT(&rx_rpc_stats);
8402 clock_GetTime(&now);
8403 *clock_sec = now.sec;
8404 *clock_usec = now.usec;
8407 * Allocate the space based upon the caller version
8409 * If the client is at an older version than we are,
8410 * we return the statistic data in the older data format, but
8411 * we still return our version number so the client knows we
8412 * are maintaining more data than it can retrieve.
8415 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8416 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8417 *statCount = rxi_rpc_peer_stat_cnt;
8420 * This can't happen yet, but in the future version changes
8421 * can be handled by adding additional code here
8425 if (space > (size_t) 0) {
8427 ptr = *stats = rxi_Alloc(space);
8430 rx_interface_stat_p rpc_stat, nrpc_stat;
8434 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8436 * We have to fix the offset of rpc_stat since we are
8437 * keeping this structure on two rx_queues. The rx_queue
8438 * package assumes that the rx_queue member is the first
8439 * member of the structure. That is, rx_queue assumes that
8440 * any one item is only on one queue at a time. We are
8441 * breaking that assumption and so we have to do a little
8442 * math to fix our pointers.
8445 fix_offset = (char *)rpc_stat;
8446 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8447 rpc_stat = (rx_interface_stat_p) fix_offset;
8450 * Copy the data based upon the caller version
8452 rx_MarshallProcessRPCStats(callerVersion,
8453 rpc_stat->stats[0].func_total,
8454 rpc_stat->stats, &ptr);
8460 MUTEX_EXIT(&rx_rpc_stats);
8465 * rx_FreeRPCStats - free memory allocated by
8466 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8470 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8471 * rx_RetrievePeerRPCStats
8473 * IN allocSize - the number of bytes in stats.
8481 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8483 rxi_Free(stats, allocSize);
8487 * rx_queryProcessRPCStats - see if process rpc stat collection is
8488 * currently enabled.
8494 * Returns 0 if stats are not enabled != 0 otherwise
8498 rx_queryProcessRPCStats(void)
8501 MUTEX_ENTER(&rx_rpc_stats);
8502 rc = rxi_monitor_processStats;
8503 MUTEX_EXIT(&rx_rpc_stats);
8508 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8514 * Returns 0 if stats are not enabled != 0 otherwise
8518 rx_queryPeerRPCStats(void)
8521 MUTEX_ENTER(&rx_rpc_stats);
8522 rc = rxi_monitor_peerStats;
8523 MUTEX_EXIT(&rx_rpc_stats);
8528 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8538 rx_enableProcessRPCStats(void)
8540 MUTEX_ENTER(&rx_rpc_stats);
8541 rx_enable_stats = 1;
8542 rxi_monitor_processStats = 1;
8543 MUTEX_EXIT(&rx_rpc_stats);
8547 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8557 rx_enablePeerRPCStats(void)
8559 MUTEX_ENTER(&rx_rpc_stats);
8560 rx_enable_stats = 1;
8561 rxi_monitor_peerStats = 1;
8562 MUTEX_EXIT(&rx_rpc_stats);
8566 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8576 rx_disableProcessRPCStats(void)
8578 rx_interface_stat_p rpc_stat, nrpc_stat;
8581 MUTEX_ENTER(&rx_rpc_stats);
8584 * Turn off process statistics and if peer stats is also off, turn
8588 rxi_monitor_processStats = 0;
8589 if (rxi_monitor_peerStats == 0) {
8590 rx_enable_stats = 0;
8593 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8594 unsigned int num_funcs = 0;
8597 queue_Remove(rpc_stat);
8598 num_funcs = rpc_stat->stats[0].func_total;
8600 sizeof(rx_interface_stat_t) +
8601 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8603 rxi_Free(rpc_stat, space);
8604 rxi_rpc_process_stat_cnt -= num_funcs;
8606 MUTEX_EXIT(&rx_rpc_stats);
8610 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8620 rx_disablePeerRPCStats(void)
8622 struct rx_peer **peer_ptr, **peer_end;
8626 * Turn off peer statistics and if process stats is also off, turn
8630 rxi_monitor_peerStats = 0;
8631 if (rxi_monitor_processStats == 0) {
8632 rx_enable_stats = 0;
8635 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8636 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8638 struct rx_peer *peer, *next, *prev;
8640 MUTEX_ENTER(&rx_peerHashTable_lock);
8641 MUTEX_ENTER(&rx_rpc_stats);
8642 for (prev = peer = *peer_ptr; peer; peer = next) {
8644 code = MUTEX_TRYENTER(&peer->peer_lock);
8646 rx_interface_stat_p rpc_stat, nrpc_stat;
8649 if (prev == *peer_ptr) {
8660 MUTEX_EXIT(&rx_peerHashTable_lock);
8663 (&peer->rpcStats, rpc_stat, nrpc_stat,
8664 rx_interface_stat)) {
8665 unsigned int num_funcs = 0;
8668 queue_Remove(&rpc_stat->queue_header);
8669 queue_Remove(&rpc_stat->all_peers);
8670 num_funcs = rpc_stat->stats[0].func_total;
8672 sizeof(rx_interface_stat_t) +
8673 rpc_stat->stats[0].func_total *
8674 sizeof(rx_function_entry_v1_t);
8676 rxi_Free(rpc_stat, space);
8677 rxi_rpc_peer_stat_cnt -= num_funcs;
8679 MUTEX_EXIT(&peer->peer_lock);
8681 MUTEX_ENTER(&rx_peerHashTable_lock);
8691 MUTEX_EXIT(&rx_rpc_stats);
8692 MUTEX_EXIT(&rx_peerHashTable_lock);
8697 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8702 * IN clearFlag - flag indicating which stats to clear
8710 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8712 rx_interface_stat_p rpc_stat, nrpc_stat;
8714 MUTEX_ENTER(&rx_rpc_stats);
8716 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8717 unsigned int num_funcs = 0, i;
8718 num_funcs = rpc_stat->stats[0].func_total;
8719 for (i = 0; i < num_funcs; i++) {
8720 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8721 hzero(rpc_stat->stats[i].invocations);
8723 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8724 hzero(rpc_stat->stats[i].bytes_sent);
8726 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8727 hzero(rpc_stat->stats[i].bytes_rcvd);
8729 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8730 rpc_stat->stats[i].queue_time_sum.sec = 0;
8731 rpc_stat->stats[i].queue_time_sum.usec = 0;
8733 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8734 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8735 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8737 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8738 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8739 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8741 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8742 rpc_stat->stats[i].queue_time_max.sec = 0;
8743 rpc_stat->stats[i].queue_time_max.usec = 0;
8745 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8746 rpc_stat->stats[i].execution_time_sum.sec = 0;
8747 rpc_stat->stats[i].execution_time_sum.usec = 0;
8749 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8750 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8751 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8753 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8754 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8755 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8757 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8758 rpc_stat->stats[i].execution_time_max.sec = 0;
8759 rpc_stat->stats[i].execution_time_max.usec = 0;
8764 MUTEX_EXIT(&rx_rpc_stats);
8768 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8773 * IN clearFlag - flag indicating which stats to clear
8781 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8783 rx_interface_stat_p rpc_stat, nrpc_stat;
8785 MUTEX_ENTER(&rx_rpc_stats);
8787 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8788 unsigned int num_funcs = 0, i;
8791 * We have to fix the offset of rpc_stat since we are
8792 * keeping this structure on two rx_queues. The rx_queue
8793 * package assumes that the rx_queue member is the first
8794 * member of the structure. That is, rx_queue assumes that
8795 * any one item is only on one queue at a time. We are
8796 * breaking that assumption and so we have to do a little
8797 * math to fix our pointers.
8800 fix_offset = (char *)rpc_stat;
8801 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8802 rpc_stat = (rx_interface_stat_p) fix_offset;
8804 num_funcs = rpc_stat->stats[0].func_total;
8805 for (i = 0; i < num_funcs; i++) {
8806 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8807 hzero(rpc_stat->stats[i].invocations);
8809 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8810 hzero(rpc_stat->stats[i].bytes_sent);
8812 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8813 hzero(rpc_stat->stats[i].bytes_rcvd);
8815 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8816 rpc_stat->stats[i].queue_time_sum.sec = 0;
8817 rpc_stat->stats[i].queue_time_sum.usec = 0;
8819 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8820 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8821 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8823 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8824 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8825 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8827 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8828 rpc_stat->stats[i].queue_time_max.sec = 0;
8829 rpc_stat->stats[i].queue_time_max.usec = 0;
8831 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8832 rpc_stat->stats[i].execution_time_sum.sec = 0;
8833 rpc_stat->stats[i].execution_time_sum.usec = 0;
8835 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8836 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8837 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8839 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8840 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8841 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8843 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8844 rpc_stat->stats[i].execution_time_max.sec = 0;
8845 rpc_stat->stats[i].execution_time_max.usec = 0;
8850 MUTEX_EXIT(&rx_rpc_stats);
8854 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8855 * is authorized to enable/disable/clear RX statistics.
8857 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8860 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8862 rxi_rxstat_userok = proc;
8866 rx_RxStatUserOk(struct rx_call *call)
8868 if (!rxi_rxstat_userok)
8870 return rxi_rxstat_userok(call);
8875 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8876 * function in the MSVC runtime DLL (msvcrt.dll).
8878 * Note: the system serializes calls to this function.
8881 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8882 DWORD reason, /* reason function is being called */
8883 LPVOID reserved) /* reserved for future use */
8886 case DLL_PROCESS_ATTACH:
8887 /* library is being attached to a process */
8891 case DLL_PROCESS_DETACH:
8898 #endif /* AFS_NT40_ENV */
8901 int rx_DumpCalls(FILE *outputFile, char *cookie)
8903 #ifdef RXDEBUG_PACKET
8904 #ifdef KDUMP_RX_LOCK
8905 struct rx_call_rx_lock *c;
8912 #define RXDPRINTF sprintf
8913 #define RXDPRINTOUT output
8915 #define RXDPRINTF fprintf
8916 #define RXDPRINTOUT outputFile
8919 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8921 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8924 for (c = rx_allCallsp; c; c = c->allNextp) {
8925 u_short rqc, tqc, iovqc;
8926 struct rx_packet *p, *np;
8928 MUTEX_ENTER(&c->lock);
8929 queue_Count(&c->rq, p, np, rx_packet, rqc);
8930 queue_Count(&c->tq, p, np, rx_packet, tqc);
8931 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8933 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, "
8934 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8935 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8936 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8937 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8938 #ifdef RX_ENABLE_LOCKS
8941 #ifdef RX_REFCOUNT_CHECK
8942 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8943 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8946 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,
8947 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8948 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8949 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8950 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8951 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8952 #ifdef RX_ENABLE_LOCKS
8953 , (afs_uint32)c->refCount
8955 #ifdef RX_REFCOUNT_CHECK
8956 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8959 MUTEX_EXIT(&c->lock);
8962 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8965 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8967 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8969 #endif /* RXDEBUG_PACKET */