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"
83 #include <afs/rxgen_consts.h>
86 #ifdef AFS_PTHREAD_ENV
88 int (*registerProgram) (pid_t, char *) = 0;
89 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
92 int (*registerProgram) (PROCESS, char *) = 0;
93 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
97 /* Local static routines */
98 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
99 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
100 struct rx_call *, struct rx_peer *,
102 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
104 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
105 void *dummy, int dummy2);
106 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
107 void *dummy, int dummy2);
108 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
109 void *unused, int unused2);
110 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
111 void *unused2, int unused3);
113 #ifdef RX_ENABLE_LOCKS
114 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
117 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
119 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
120 rx_atomic_t rxi_start_in_error;
122 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
124 /* Constant delay time before sending an acknowledge of the last packet
125 * received. This is to avoid sending an extra acknowledge when the
126 * client is about to make another call, anyway, or the server is
129 * The lastAckDelay may not exceeed 400ms without causing peers to
130 * unecessarily timeout.
132 struct clock rx_lastAckDelay = {0, 400000};
134 /* Constant delay time before sending a soft ack when none was requested.
135 * This is to make sure we send soft acks before the sender times out,
136 * Normally we wait and send a hard ack when the receiver consumes the packet
138 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
139 * will require changes to the peer's RTT calculations.
141 struct clock rx_softAckDelay = {0, 100000};
144 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
145 * currently allocated within rx. This number is used to allocate the
146 * memory required to return the statistics when queried.
147 * Protected by the rx_rpc_stats mutex.
150 static unsigned int rxi_rpc_peer_stat_cnt;
153 * rxi_rpc_process_stat_cnt counts the total number of local process stat
154 * structures currently allocated within rx. The number is used to allocate
155 * the memory required to return the statistics when queried.
156 * Protected by the rx_rpc_stats mutex.
159 static unsigned int rxi_rpc_process_stat_cnt;
162 * rxi_busyChannelError is the error to return to the application when a call
163 * channel appears busy (inferred from the receipt of RX_PACKET_TYPE_BUSY
164 * packets on the channel), and there are other call channels in the
165 * connection that are not busy. If 0, we do not return errors upon receiving
166 * busy packets; we just keep trying on the same call channel until we hit a
169 static afs_int32 rxi_busyChannelError = 0;
171 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
172 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
174 #if !defined(offsetof)
175 #include <stddef.h> /* for definition of offsetof() */
178 #ifdef RX_ENABLE_LOCKS
179 afs_kmutex_t rx_atomic_mutex;
182 /* Forward prototypes */
183 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
185 #ifdef AFS_PTHREAD_ENV
188 * Use procedural initialization of mutexes/condition variables
192 extern afs_kmutex_t rx_quota_mutex;
193 extern afs_kmutex_t rx_pthread_mutex;
194 extern afs_kmutex_t rx_packets_mutex;
195 extern afs_kmutex_t rx_refcnt_mutex;
196 extern afs_kmutex_t des_init_mutex;
197 extern afs_kmutex_t des_random_mutex;
198 extern afs_kmutex_t rx_clock_mutex;
199 extern afs_kmutex_t rxi_connCacheMutex;
200 extern afs_kmutex_t event_handler_mutex;
201 extern afs_kmutex_t listener_mutex;
202 extern afs_kmutex_t rx_if_init_mutex;
203 extern afs_kmutex_t rx_if_mutex;
205 extern afs_kcondvar_t rx_event_handler_cond;
206 extern afs_kcondvar_t rx_listener_cond;
208 static afs_kmutex_t epoch_mutex;
209 static afs_kmutex_t rx_init_mutex;
210 static afs_kmutex_t rx_debug_mutex;
211 static afs_kmutex_t rx_rpc_stats;
214 rxi_InitPthread(void)
216 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
217 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
220 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
222 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
224 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
226 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
228 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
229 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
230 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
232 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
233 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
235 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
236 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
238 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
239 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
240 #ifdef RX_ENABLE_LOCKS
243 #endif /* RX_LOCKS_DB */
244 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
245 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
247 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
249 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
251 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
253 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
254 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
255 #endif /* RX_ENABLE_LOCKS */
258 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
259 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
261 * The rx_stats_mutex mutex protects the following global variables:
262 * rxi_lowConnRefCount
263 * rxi_lowPeerRefCount
272 * The rx_quota_mutex mutex protects the following global variables:
280 * The rx_freePktQ_lock protects the following global variables:
285 * The rx_packets_mutex mutex protects the following global variables:
293 * The rx_pthread_mutex mutex protects the following global variables:
294 * rxi_fcfs_thread_num
297 #define INIT_PTHREAD_LOCKS
301 /* Variables for handling the minProcs implementation. availProcs gives the
302 * number of threads available in the pool at this moment (not counting dudes
303 * executing right now). totalMin gives the total number of procs required
304 * for handling all minProcs requests. minDeficit is a dynamic variable
305 * tracking the # of procs required to satisfy all of the remaining minProcs
307 * For fine grain locking to work, the quota check and the reservation of
308 * a server thread has to come while rxi_availProcs and rxi_minDeficit
309 * are locked. To this end, the code has been modified under #ifdef
310 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
311 * same time. A new function, ReturnToServerPool() returns the allocation.
313 * A call can be on several queue's (but only one at a time). When
314 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
315 * that no one else is touching the queue. To this end, we store the address
316 * of the queue lock in the call structure (under the call lock) when we
317 * put the call on a queue, and we clear the call_queue_lock when the
318 * call is removed from a queue (once the call lock has been obtained).
319 * This allows rxi_ResetCall to safely synchronize with others wishing
320 * to manipulate the queue.
323 #if defined(RX_ENABLE_LOCKS)
324 static afs_kmutex_t rx_rpc_stats;
327 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
328 ** pretty good that the next packet coming in is from the same connection
329 ** as the last packet, since we're send multiple packets in a transmit window.
331 struct rx_connection *rxLastConn = 0;
333 #ifdef RX_ENABLE_LOCKS
334 /* The locking hierarchy for rx fine grain locking is composed of these
337 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
338 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
339 * call->lock - locks call data fields.
340 * These are independent of each other:
341 * rx_freeCallQueue_lock
346 * serverQueueEntry->lock
347 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
349 * peer->lock - locks peer data fields.
350 * conn_data_lock - that more than one thread is not updating a conn data
351 * field at the same time.
362 * Do we need a lock to protect the peer field in the conn structure?
363 * conn->peer was previously a constant for all intents and so has no
364 * lock protecting this field. The multihomed client delta introduced
365 * a RX code change : change the peer field in the connection structure
366 * to that remote interface from which the last packet for this
367 * connection was sent out. This may become an issue if further changes
370 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
371 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
373 /* rxdb_fileID is used to identify the lock location, along with line#. */
374 static int rxdb_fileID = RXDB_FILE_RX;
375 #endif /* RX_LOCKS_DB */
376 #else /* RX_ENABLE_LOCKS */
377 #define SET_CALL_QUEUE_LOCK(C, L)
378 #define CLEAR_CALL_QUEUE_LOCK(C)
379 #endif /* RX_ENABLE_LOCKS */
380 struct rx_serverQueueEntry *rx_waitForPacket = 0;
381 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
383 /* ------------Exported Interfaces------------- */
385 /* This function allows rxkad to set the epoch to a suitably random number
386 * which rx_NewConnection will use in the future. The principle purpose is to
387 * get rxnull connections to use the same epoch as the rxkad connections do, at
388 * least once the first rxkad connection is established. This is important now
389 * that the host/port addresses aren't used in FindConnection: the uniqueness
390 * of epoch/cid matters and the start time won't do. */
392 #ifdef AFS_PTHREAD_ENV
394 * This mutex protects the following global variables:
398 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
399 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
403 #endif /* AFS_PTHREAD_ENV */
406 rx_SetEpoch(afs_uint32 epoch)
413 /* Initialize rx. A port number may be mentioned, in which case this
414 * becomes the default port number for any service installed later.
415 * If 0 is provided for the port number, a random port will be chosen
416 * by the kernel. Whether this will ever overlap anything in
417 * /etc/services is anybody's guess... Returns 0 on success, -1 on
422 int rxinit_status = 1;
423 #ifdef AFS_PTHREAD_ENV
425 * This mutex protects the following global variables:
429 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
430 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
433 #define UNLOCK_RX_INIT
437 rx_InitHost(u_int host, u_int port)
444 char *htable, *ptable;
451 if (rxinit_status == 0) {
452 tmp_status = rxinit_status;
454 return tmp_status; /* Already started; return previous error code. */
460 if (afs_winsockInit() < 0)
466 * Initialize anything necessary to provide a non-premptive threading
469 rxi_InitializeThreadSupport();
472 /* Allocate and initialize a socket for client and perhaps server
475 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
476 if (rx_socket == OSI_NULLSOCKET) {
480 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
483 #endif /* RX_LOCKS_DB */
484 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
485 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
486 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
487 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
488 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
489 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
490 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
491 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
492 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
494 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
496 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
498 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
500 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
501 #if defined(AFS_HPUX110_ENV)
503 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
504 #endif /* AFS_HPUX110_ENV */
505 #endif /* RX_ENABLE_LOCKS && KERNEL */
508 rx_connDeadTime = 12;
509 rx_tranquil = 0; /* reset flag */
510 rxi_ResetStatistics();
512 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
513 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
514 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
515 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
516 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
517 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
519 /* Malloc up a bunch of packets & buffers */
521 queue_Init(&rx_freePacketQueue);
522 rxi_NeedMorePackets = FALSE;
523 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
525 /* enforce a minimum number of allocated packets */
526 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
527 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
529 /* allocate the initial free packet pool */
530 #ifdef RX_ENABLE_TSFPQ
531 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
532 #else /* RX_ENABLE_TSFPQ */
533 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
534 #endif /* RX_ENABLE_TSFPQ */
541 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
542 tv.tv_sec = clock_now.sec;
543 tv.tv_usec = clock_now.usec;
544 srand((unsigned int)tv.tv_usec);
551 #if defined(KERNEL) && !defined(UKERNEL)
552 /* Really, this should never happen in a real kernel */
555 struct sockaddr_in addr;
557 int addrlen = sizeof(addr);
559 socklen_t addrlen = sizeof(addr);
561 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
565 rx_port = addr.sin_port;
568 rx_stats.minRtt.sec = 9999999;
570 rx_SetEpoch(tv.tv_sec | 0x80000000);
572 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
573 * will provide a randomer value. */
575 MUTEX_ENTER(&rx_quota_mutex);
576 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
577 MUTEX_EXIT(&rx_quota_mutex);
578 /* *Slightly* random start time for the cid. This is just to help
579 * out with the hashing function at the peer */
580 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
581 rx_connHashTable = (struct rx_connection **)htable;
582 rx_peerHashTable = (struct rx_peer **)ptable;
584 rx_hardAckDelay.sec = 0;
585 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
587 rxevent_Init(20, rxi_ReScheduleEvents);
589 /* Initialize various global queues */
590 queue_Init(&rx_idleServerQueue);
591 queue_Init(&rx_incomingCallQueue);
592 queue_Init(&rx_freeCallQueue);
594 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
595 /* Initialize our list of usable IP addresses. */
599 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
600 /* Start listener process (exact function is dependent on the
601 * implementation environment--kernel or user space) */
606 tmp_status = rxinit_status = 0;
614 return rx_InitHost(htonl(INADDR_ANY), port);
620 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
621 * maintaing the round trip timer.
626 * Start a new RTT timer for a given call and packet.
628 * There must be no resendEvent already listed for this call, otherwise this
629 * will leak events - intended for internal use within the RTO code only
632 * the RX call to start the timer for
633 * @param[in] lastPacket
634 * a flag indicating whether the last packet has been sent or not
636 * @pre call must be locked before calling this function
640 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
642 struct clock now, retryTime;
647 clock_Add(&retryTime, &call->rto);
649 /* If we're sending the last packet, and we're the client, then the server
650 * may wait for an additional 400ms before returning the ACK, wait for it
651 * rather than hitting a timeout */
652 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
653 clock_Addmsec(&retryTime, 400);
655 MUTEX_ENTER(&rx_refcnt_mutex);
656 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
657 MUTEX_EXIT(&rx_refcnt_mutex);
658 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
663 * Cancel an RTT timer for a given call.
667 * the RX call to cancel the timer for
669 * @pre call must be locked before calling this function
674 rxi_rto_cancel(struct rx_call *call)
676 rxevent_Cancel(&call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
680 * Tell the RTO timer that we have sent a packet.
682 * If the timer isn't already running, then start it. If the timer is running,
686 * the RX call that the packet has been sent on
687 * @param[in] lastPacket
688 * A flag which is true if this is the last packet for the call
690 * @pre The call must be locked before calling this function
695 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
697 if (call->resendEvent)
700 rxi_rto_startTimer(call, lastPacket, istack);
704 * Tell the RTO timer that we have received an new ACK message
706 * This function should be called whenever a call receives an ACK that
707 * acknowledges new packets. Whatever happens, we stop the current timer.
708 * If there are unacked packets in the queue which have been sent, then
709 * we restart the timer from now. Otherwise, we leave it stopped.
712 * the RX call that the ACK has been received on
716 rxi_rto_packet_acked(struct rx_call *call, int istack)
718 struct rx_packet *p, *nxp;
720 rxi_rto_cancel(call);
722 if (queue_IsEmpty(&call->tq))
725 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
726 if (p->header.seq > call->tfirst + call->twind)
729 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
730 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
738 * Set an initial round trip timeout for a peer connection
740 * @param[in] secs The timeout to set in seconds
744 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
745 peer->rtt = secs * 8000;
749 * Sets the error generated when a busy call channel is detected.
751 * @param[in] error The error to return for a call on a busy channel.
753 * @pre Neither rx_Init nor rx_InitHost have been called yet
756 rx_SetBusyChannelError(afs_int32 error)
758 osi_Assert(rxinit_status != 0);
759 rxi_busyChannelError = error;
763 * Set a delayed ack event on the specified call for the given time
765 * @param[in] call - the call on which to set the event
766 * @param[in] offset - the delay from now after which the event fires
769 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
771 struct clock now, when;
775 clock_Add(&when, offset);
777 if (!call->delayedAckEvent
778 || clock_Gt(&call->delayedAckTime, &when)) {
780 rxevent_Cancel(&call->delayedAckEvent, call,
781 RX_CALL_REFCOUNT_DELAY);
782 MUTEX_ENTER(&rx_refcnt_mutex);
783 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
784 MUTEX_EXIT(&rx_refcnt_mutex);
786 call->delayedAckEvent = rxevent_Post(&when, &now,
789 call->delayedAckTime = when;
793 /* called with unincremented nRequestsRunning to see if it is OK to start
794 * a new thread in this service. Could be "no" for two reasons: over the
795 * max quota, or would prevent others from reaching their min quota.
797 #ifdef RX_ENABLE_LOCKS
798 /* This verion of QuotaOK reserves quota if it's ok while the
799 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
802 QuotaOK(struct rx_service *aservice)
804 /* check if over max quota */
805 if (aservice->nRequestsRunning >= aservice->maxProcs) {
809 /* under min quota, we're OK */
810 /* otherwise, can use only if there are enough to allow everyone
811 * to go to their min quota after this guy starts.
814 MUTEX_ENTER(&rx_quota_mutex);
815 if ((aservice->nRequestsRunning < aservice->minProcs)
816 || (rxi_availProcs > rxi_minDeficit)) {
817 aservice->nRequestsRunning++;
818 /* just started call in minProcs pool, need fewer to maintain
820 if (aservice->nRequestsRunning <= aservice->minProcs)
823 MUTEX_EXIT(&rx_quota_mutex);
826 MUTEX_EXIT(&rx_quota_mutex);
832 ReturnToServerPool(struct rx_service *aservice)
834 aservice->nRequestsRunning--;
835 MUTEX_ENTER(&rx_quota_mutex);
836 if (aservice->nRequestsRunning < aservice->minProcs)
839 MUTEX_EXIT(&rx_quota_mutex);
842 #else /* RX_ENABLE_LOCKS */
844 QuotaOK(struct rx_service *aservice)
847 /* under min quota, we're OK */
848 if (aservice->nRequestsRunning < aservice->minProcs)
851 /* check if over max quota */
852 if (aservice->nRequestsRunning >= aservice->maxProcs)
855 /* otherwise, can use only if there are enough to allow everyone
856 * to go to their min quota after this guy starts.
858 MUTEX_ENTER(&rx_quota_mutex);
859 if (rxi_availProcs > rxi_minDeficit)
861 MUTEX_EXIT(&rx_quota_mutex);
864 #endif /* RX_ENABLE_LOCKS */
867 /* Called by rx_StartServer to start up lwp's to service calls.
868 NExistingProcs gives the number of procs already existing, and which
869 therefore needn't be created. */
871 rxi_StartServerProcs(int nExistingProcs)
873 struct rx_service *service;
878 /* For each service, reserve N processes, where N is the "minimum"
879 * number of processes that MUST be able to execute a request in parallel,
880 * at any time, for that process. Also compute the maximum difference
881 * between any service's maximum number of processes that can run
882 * (i.e. the maximum number that ever will be run, and a guarantee
883 * that this number will run if other services aren't running), and its
884 * minimum number. The result is the extra number of processes that
885 * we need in order to provide the latter guarantee */
886 for (i = 0; i < RX_MAX_SERVICES; i++) {
888 service = rx_services[i];
889 if (service == (struct rx_service *)0)
891 nProcs += service->minProcs;
892 diff = service->maxProcs - service->minProcs;
896 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
897 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
898 for (i = 0; i < nProcs; i++) {
899 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
905 /* This routine is only required on Windows */
907 rx_StartClientThread(void)
909 #ifdef AFS_PTHREAD_ENV
911 pid = pthread_self();
912 #endif /* AFS_PTHREAD_ENV */
914 #endif /* AFS_NT40_ENV */
916 /* This routine must be called if any services are exported. If the
917 * donateMe flag is set, the calling process is donated to the server
920 rx_StartServer(int donateMe)
922 struct rx_service *service;
928 /* Start server processes, if necessary (exact function is dependent
929 * on the implementation environment--kernel or user space). DonateMe
930 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
931 * case, one less new proc will be created rx_StartServerProcs.
933 rxi_StartServerProcs(donateMe);
935 /* count up the # of threads in minProcs, and add set the min deficit to
936 * be that value, too.
938 for (i = 0; i < RX_MAX_SERVICES; i++) {
939 service = rx_services[i];
940 if (service == (struct rx_service *)0)
942 MUTEX_ENTER(&rx_quota_mutex);
943 rxi_totalMin += service->minProcs;
944 /* below works even if a thread is running, since minDeficit would
945 * still have been decremented and later re-incremented.
947 rxi_minDeficit += service->minProcs;
948 MUTEX_EXIT(&rx_quota_mutex);
951 /* Turn on reaping of idle server connections */
952 rxi_ReapConnections(NULL, NULL, NULL, 0);
961 #ifdef AFS_PTHREAD_ENV
963 pid = afs_pointer_to_int(pthread_self());
964 #else /* AFS_PTHREAD_ENV */
966 LWP_CurrentProcess(&pid);
967 #endif /* AFS_PTHREAD_ENV */
969 sprintf(name, "srv_%d", ++nProcs);
971 (*registerProgram) (pid, name);
973 #endif /* AFS_NT40_ENV */
974 rx_ServerProc(NULL); /* Never returns */
976 #ifdef RX_ENABLE_TSFPQ
977 /* no use leaving packets around in this thread's local queue if
978 * it isn't getting donated to the server thread pool.
980 rxi_FlushLocalPacketsTSFPQ();
981 #endif /* RX_ENABLE_TSFPQ */
985 /* Create a new client connection to the specified service, using the
986 * specified security object to implement the security model for this
988 struct rx_connection *
989 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
990 struct rx_securityClass *securityObject,
991 int serviceSecurityIndex)
995 struct rx_connection *conn;
1000 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1001 "serviceSecurityIndex %d)\n",
1002 ntohl(shost), ntohs(sport), sservice, securityObject,
1003 serviceSecurityIndex));
1005 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1006 * the case of kmem_alloc? */
1007 conn = rxi_AllocConnection();
1008 #ifdef RX_ENABLE_LOCKS
1009 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1010 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1011 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1014 MUTEX_ENTER(&rx_connHashTable_lock);
1015 cid = (rx_nextCid += RX_MAXCALLS);
1016 conn->type = RX_CLIENT_CONNECTION;
1018 conn->epoch = rx_epoch;
1019 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
1020 conn->serviceId = sservice;
1021 conn->securityObject = securityObject;
1022 conn->securityData = (void *) 0;
1023 conn->securityIndex = serviceSecurityIndex;
1024 rx_SetConnDeadTime(conn, rx_connDeadTime);
1025 rx_SetConnSecondsUntilNatPing(conn, 0);
1026 conn->ackRate = RX_FAST_ACK_RATE;
1027 conn->nSpecific = 0;
1028 conn->specific = NULL;
1029 conn->challengeEvent = NULL;
1030 conn->delayedAbortEvent = NULL;
1031 conn->abortCount = 0;
1033 for (i = 0; i < RX_MAXCALLS; i++) {
1034 conn->twind[i] = rx_initSendWindow;
1035 conn->rwind[i] = rx_initReceiveWindow;
1036 conn->lastBusy[i] = 0;
1039 RXS_NewConnection(securityObject, conn);
1041 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1043 conn->refCount++; /* no lock required since only this thread knows... */
1044 conn->next = rx_connHashTable[hashindex];
1045 rx_connHashTable[hashindex] = conn;
1046 if (rx_stats_active)
1047 rx_atomic_inc(&rx_stats.nClientConns);
1048 MUTEX_EXIT(&rx_connHashTable_lock);
1054 * Ensure a connection's timeout values are valid.
1056 * @param[in] conn The connection to check
1058 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1059 * unless idleDeadTime and/or hardDeadTime are not set
1063 rxi_CheckConnTimeouts(struct rx_connection *conn)
1065 /* a connection's timeouts must have the relationship
1066 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1067 * total loss of network to a peer may cause an idle timeout instead of a
1068 * dead timeout, simply because the idle timeout gets hit first. Also set
1069 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1070 /* this logic is slightly complicated by the fact that
1071 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1073 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1074 if (conn->idleDeadTime) {
1075 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1077 if (conn->hardDeadTime) {
1078 if (conn->idleDeadTime) {
1079 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1081 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1087 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1089 /* The idea is to set the dead time to a value that allows several
1090 * keepalives to be dropped without timing out the connection. */
1091 conn->secondsUntilDead = seconds;
1092 rxi_CheckConnTimeouts(conn);
1093 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1097 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1099 conn->hardDeadTime = seconds;
1100 rxi_CheckConnTimeouts(conn);
1104 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1106 conn->idleDeadTime = seconds;
1107 rxi_CheckConnTimeouts(conn);
1110 int rxi_lowPeerRefCount = 0;
1111 int rxi_lowConnRefCount = 0;
1114 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1115 * NOTE: must not be called with rx_connHashTable_lock held.
1118 rxi_CleanupConnection(struct rx_connection *conn)
1120 /* Notify the service exporter, if requested, that this connection
1121 * is being destroyed */
1122 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1123 (*conn->service->destroyConnProc) (conn);
1125 /* Notify the security module that this connection is being destroyed */
1126 RXS_DestroyConnection(conn->securityObject, conn);
1128 /* If this is the last connection using the rx_peer struct, set its
1129 * idle time to now. rxi_ReapConnections will reap it if it's still
1130 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1132 MUTEX_ENTER(&rx_peerHashTable_lock);
1133 if (conn->peer->refCount < 2) {
1134 conn->peer->idleWhen = clock_Sec();
1135 if (conn->peer->refCount < 1) {
1136 conn->peer->refCount = 1;
1137 if (rx_stats_active) {
1138 MUTEX_ENTER(&rx_stats_mutex);
1139 rxi_lowPeerRefCount++;
1140 MUTEX_EXIT(&rx_stats_mutex);
1144 conn->peer->refCount--;
1145 MUTEX_EXIT(&rx_peerHashTable_lock);
1147 if (rx_stats_active)
1149 if (conn->type == RX_SERVER_CONNECTION)
1150 rx_atomic_dec(&rx_stats.nServerConns);
1152 rx_atomic_dec(&rx_stats.nClientConns);
1155 if (conn->specific) {
1157 for (i = 0; i < conn->nSpecific; i++) {
1158 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1159 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1160 conn->specific[i] = NULL;
1162 free(conn->specific);
1164 conn->specific = NULL;
1165 conn->nSpecific = 0;
1166 #endif /* !KERNEL */
1168 MUTEX_DESTROY(&conn->conn_call_lock);
1169 MUTEX_DESTROY(&conn->conn_data_lock);
1170 CV_DESTROY(&conn->conn_call_cv);
1172 rxi_FreeConnection(conn);
1175 /* Destroy the specified connection */
1177 rxi_DestroyConnection(struct rx_connection *conn)
1179 MUTEX_ENTER(&rx_connHashTable_lock);
1180 rxi_DestroyConnectionNoLock(conn);
1181 /* conn should be at the head of the cleanup list */
1182 if (conn == rx_connCleanup_list) {
1183 rx_connCleanup_list = rx_connCleanup_list->next;
1184 MUTEX_EXIT(&rx_connHashTable_lock);
1185 rxi_CleanupConnection(conn);
1187 #ifdef RX_ENABLE_LOCKS
1189 MUTEX_EXIT(&rx_connHashTable_lock);
1191 #endif /* RX_ENABLE_LOCKS */
1195 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1197 struct rx_connection **conn_ptr;
1199 struct rx_packet *packet;
1206 MUTEX_ENTER(&conn->conn_data_lock);
1207 MUTEX_ENTER(&rx_refcnt_mutex);
1208 if (conn->refCount > 0)
1211 if (rx_stats_active) {
1212 MUTEX_ENTER(&rx_stats_mutex);
1213 rxi_lowConnRefCount++;
1214 MUTEX_EXIT(&rx_stats_mutex);
1218 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1219 /* Busy; wait till the last guy before proceeding */
1220 MUTEX_EXIT(&rx_refcnt_mutex);
1221 MUTEX_EXIT(&conn->conn_data_lock);
1226 /* If the client previously called rx_NewCall, but it is still
1227 * waiting, treat this as a running call, and wait to destroy the
1228 * connection later when the call completes. */
1229 if ((conn->type == RX_CLIENT_CONNECTION)
1230 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1231 conn->flags |= RX_CONN_DESTROY_ME;
1232 MUTEX_EXIT(&conn->conn_data_lock);
1236 MUTEX_EXIT(&rx_refcnt_mutex);
1237 MUTEX_EXIT(&conn->conn_data_lock);
1239 /* Check for extant references to this connection */
1240 MUTEX_ENTER(&conn->conn_call_lock);
1241 for (i = 0; i < RX_MAXCALLS; i++) {
1242 struct rx_call *call = conn->call[i];
1245 if (conn->type == RX_CLIENT_CONNECTION) {
1246 MUTEX_ENTER(&call->lock);
1247 if (call->delayedAckEvent) {
1248 /* Push the final acknowledgment out now--there
1249 * won't be a subsequent call to acknowledge the
1250 * last reply packets */
1251 rxevent_Cancel(&call->delayedAckEvent, call,
1252 RX_CALL_REFCOUNT_DELAY);
1253 if (call->state == RX_STATE_PRECALL
1254 || call->state == RX_STATE_ACTIVE) {
1255 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1257 rxi_AckAll(NULL, call, 0);
1260 MUTEX_EXIT(&call->lock);
1264 MUTEX_EXIT(&conn->conn_call_lock);
1266 #ifdef RX_ENABLE_LOCKS
1268 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1269 MUTEX_EXIT(&conn->conn_data_lock);
1271 /* Someone is accessing a packet right now. */
1275 #endif /* RX_ENABLE_LOCKS */
1278 /* Don't destroy the connection if there are any call
1279 * structures still in use */
1280 MUTEX_ENTER(&conn->conn_data_lock);
1281 conn->flags |= RX_CONN_DESTROY_ME;
1282 MUTEX_EXIT(&conn->conn_data_lock);
1287 if (conn->natKeepAliveEvent) {
1288 rxi_NatKeepAliveOff(conn);
1291 if (conn->delayedAbortEvent) {
1292 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
1293 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1295 MUTEX_ENTER(&conn->conn_data_lock);
1296 rxi_SendConnectionAbort(conn, packet, 0, 1);
1297 MUTEX_EXIT(&conn->conn_data_lock);
1298 rxi_FreePacket(packet);
1302 /* Remove from connection hash table before proceeding */
1304 &rx_connHashTable[CONN_HASH
1305 (peer->host, peer->port, conn->cid, conn->epoch,
1307 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1308 if (*conn_ptr == conn) {
1309 *conn_ptr = conn->next;
1313 /* if the conn that we are destroying was the last connection, then we
1314 * clear rxLastConn as well */
1315 if (rxLastConn == conn)
1318 /* Make sure the connection is completely reset before deleting it. */
1319 /* get rid of pending events that could zap us later */
1320 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
1321 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
1322 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
1324 /* Add the connection to the list of destroyed connections that
1325 * need to be cleaned up. This is necessary to avoid deadlocks
1326 * in the routines we call to inform others that this connection is
1327 * being destroyed. */
1328 conn->next = rx_connCleanup_list;
1329 rx_connCleanup_list = conn;
1332 /* Externally available version */
1334 rx_DestroyConnection(struct rx_connection *conn)
1339 rxi_DestroyConnection(conn);
1344 rx_GetConnection(struct rx_connection *conn)
1349 MUTEX_ENTER(&rx_refcnt_mutex);
1351 MUTEX_EXIT(&rx_refcnt_mutex);
1355 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1356 /* Wait for the transmit queue to no longer be busy.
1357 * requires the call->lock to be held */
1359 rxi_WaitforTQBusy(struct rx_call *call) {
1360 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1361 call->flags |= RX_CALL_TQ_WAIT;
1363 #ifdef RX_ENABLE_LOCKS
1364 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1365 CV_WAIT(&call->cv_tq, &call->lock);
1366 #else /* RX_ENABLE_LOCKS */
1367 osi_rxSleep(&call->tq);
1368 #endif /* RX_ENABLE_LOCKS */
1370 if (call->tqWaiters == 0) {
1371 call->flags &= ~RX_CALL_TQ_WAIT;
1378 rxi_WakeUpTransmitQueue(struct rx_call *call)
1380 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1381 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1382 call, call->tqWaiters, call->flags));
1383 #ifdef RX_ENABLE_LOCKS
1384 osirx_AssertMine(&call->lock, "rxi_Start start");
1385 CV_BROADCAST(&call->cv_tq);
1386 #else /* RX_ENABLE_LOCKS */
1387 osi_rxWakeup(&call->tq);
1388 #endif /* RX_ENABLE_LOCKS */
1392 /* Start a new rx remote procedure call, on the specified connection.
1393 * If wait is set to 1, wait for a free call channel; otherwise return
1394 * 0. Maxtime gives the maximum number of seconds this call may take,
1395 * after rx_NewCall returns. After this time interval, a call to any
1396 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1397 * For fine grain locking, we hold the conn_call_lock in order to
1398 * to ensure that we don't get signalle after we found a call in an active
1399 * state and before we go to sleep.
1402 rx_NewCall(struct rx_connection *conn)
1404 int i, wait, ignoreBusy = 1;
1405 struct rx_call *call;
1406 struct clock queueTime;
1407 afs_uint32 leastBusy = 0;
1411 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1414 clock_GetTime(&queueTime);
1416 * Check if there are others waiting for a new call.
1417 * If so, let them go first to avoid starving them.
1418 * This is a fairly simple scheme, and might not be
1419 * a complete solution for large numbers of waiters.
1421 * makeCallWaiters keeps track of the number of
1422 * threads waiting to make calls and the
1423 * RX_CONN_MAKECALL_WAITING flag bit is used to
1424 * indicate that there are indeed calls waiting.
1425 * The flag is set when the waiter is incremented.
1426 * It is only cleared when makeCallWaiters is 0.
1427 * This prevents us from accidently destroying the
1428 * connection while it is potentially about to be used.
1430 MUTEX_ENTER(&conn->conn_call_lock);
1431 MUTEX_ENTER(&conn->conn_data_lock);
1432 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1433 conn->flags |= RX_CONN_MAKECALL_WAITING;
1434 conn->makeCallWaiters++;
1435 MUTEX_EXIT(&conn->conn_data_lock);
1437 #ifdef RX_ENABLE_LOCKS
1438 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1442 MUTEX_ENTER(&conn->conn_data_lock);
1443 conn->makeCallWaiters--;
1444 if (conn->makeCallWaiters == 0)
1445 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1448 /* We are now the active thread in rx_NewCall */
1449 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1450 MUTEX_EXIT(&conn->conn_data_lock);
1455 for (i = 0; i < RX_MAXCALLS; i++) {
1456 call = conn->call[i];
1458 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1459 /* we're not ignoring busy call slots; only look at the
1460 * call slot that is the "least" busy */
1464 if (call->state == RX_STATE_DALLY) {
1465 MUTEX_ENTER(&call->lock);
1466 if (call->state == RX_STATE_DALLY) {
1467 if (ignoreBusy && conn->lastBusy[i]) {
1468 /* if we're ignoring busy call slots, skip any ones that
1469 * have lastBusy set */
1470 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1471 leastBusy = conn->lastBusy[i];
1473 MUTEX_EXIT(&call->lock);
1478 * We are setting the state to RX_STATE_RESET to
1479 * ensure that no one else will attempt to use this
1480 * call once we drop the conn->conn_call_lock and
1481 * call->lock. We must drop the conn->conn_call_lock
1482 * before calling rxi_ResetCall because the process
1483 * of clearing the transmit queue can block for an
1484 * extended period of time. If we block while holding
1485 * the conn->conn_call_lock, then all rx_EndCall
1486 * processing will block as well. This has a detrimental
1487 * effect on overall system performance.
1489 call->state = RX_STATE_RESET;
1490 MUTEX_EXIT(&conn->conn_call_lock);
1491 MUTEX_ENTER(&rx_refcnt_mutex);
1492 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1493 MUTEX_EXIT(&rx_refcnt_mutex);
1494 rxi_ResetCall(call, 0);
1495 (*call->callNumber)++;
1496 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1500 * If we failed to be able to safely obtain the
1501 * conn->conn_call_lock we will have to drop the
1502 * call->lock to avoid a deadlock. When the call->lock
1503 * is released the state of the call can change. If it
1504 * is no longer RX_STATE_RESET then some other thread is
1507 MUTEX_EXIT(&call->lock);
1508 MUTEX_ENTER(&conn->conn_call_lock);
1509 MUTEX_ENTER(&call->lock);
1511 if (call->state == RX_STATE_RESET)
1515 * If we get here it means that after dropping
1516 * the conn->conn_call_lock and call->lock that
1517 * the call is no longer ours. If we can't find
1518 * a free call in the remaining slots we should
1519 * not go immediately to RX_CONN_MAKECALL_WAITING
1520 * because by dropping the conn->conn_call_lock
1521 * we have given up synchronization with rx_EndCall.
1522 * Instead, cycle through one more time to see if
1523 * we can find a call that can call our own.
1525 MUTEX_ENTER(&rx_refcnt_mutex);
1526 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1527 MUTEX_EXIT(&rx_refcnt_mutex);
1530 MUTEX_EXIT(&call->lock);
1533 if (ignoreBusy && conn->lastBusy[i]) {
1534 /* if we're ignoring busy call slots, skip any ones that
1535 * have lastBusy set */
1536 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1537 leastBusy = conn->lastBusy[i];
1542 /* rxi_NewCall returns with mutex locked */
1543 call = rxi_NewCall(conn, i);
1544 MUTEX_ENTER(&rx_refcnt_mutex);
1545 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1546 MUTEX_EXIT(&rx_refcnt_mutex);
1550 if (i < RX_MAXCALLS) {
1551 conn->lastBusy[i] = 0;
1556 if (leastBusy && ignoreBusy) {
1557 /* we didn't find a useable call slot, but we did see at least one
1558 * 'busy' slot; look again and only use a slot with the 'least
1564 MUTEX_ENTER(&conn->conn_data_lock);
1565 conn->flags |= RX_CONN_MAKECALL_WAITING;
1566 conn->makeCallWaiters++;
1567 MUTEX_EXIT(&conn->conn_data_lock);
1569 #ifdef RX_ENABLE_LOCKS
1570 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1574 MUTEX_ENTER(&conn->conn_data_lock);
1575 conn->makeCallWaiters--;
1576 if (conn->makeCallWaiters == 0)
1577 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1578 MUTEX_EXIT(&conn->conn_data_lock);
1580 /* Client is initially in send mode */
1581 call->state = RX_STATE_ACTIVE;
1582 call->error = conn->error;
1584 call->mode = RX_MODE_ERROR;
1586 call->mode = RX_MODE_SENDING;
1588 /* remember start time for call in case we have hard dead time limit */
1589 call->queueTime = queueTime;
1590 clock_GetTime(&call->startTime);
1591 hzero(call->bytesSent);
1592 hzero(call->bytesRcvd);
1594 /* Turn on busy protocol. */
1595 rxi_KeepAliveOn(call);
1597 /* Attempt MTU discovery */
1598 rxi_GrowMTUOn(call);
1601 * We are no longer the active thread in rx_NewCall
1603 MUTEX_ENTER(&conn->conn_data_lock);
1604 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1605 MUTEX_EXIT(&conn->conn_data_lock);
1608 * Wake up anyone else who might be giving us a chance to
1609 * run (see code above that avoids resource starvation).
1611 #ifdef RX_ENABLE_LOCKS
1612 CV_BROADCAST(&conn->conn_call_cv);
1616 MUTEX_EXIT(&conn->conn_call_lock);
1618 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1619 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1620 osi_Panic("rx_NewCall call about to be used without an empty tq");
1622 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1624 MUTEX_EXIT(&call->lock);
1627 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1632 rxi_HasActiveCalls(struct rx_connection *aconn)
1635 struct rx_call *tcall;
1639 for (i = 0; i < RX_MAXCALLS; i++) {
1640 if ((tcall = aconn->call[i])) {
1641 if ((tcall->state == RX_STATE_ACTIVE)
1642 || (tcall->state == RX_STATE_PRECALL)) {
1653 rxi_GetCallNumberVector(struct rx_connection *aconn,
1654 afs_int32 * aint32s)
1657 struct rx_call *tcall;
1661 for (i = 0; i < RX_MAXCALLS; i++) {
1662 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1663 aint32s[i] = aconn->callNumber[i] + 1;
1665 aint32s[i] = aconn->callNumber[i];
1672 rxi_SetCallNumberVector(struct rx_connection *aconn,
1673 afs_int32 * aint32s)
1676 struct rx_call *tcall;
1680 for (i = 0; i < RX_MAXCALLS; i++) {
1681 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1682 aconn->callNumber[i] = aint32s[i] - 1;
1684 aconn->callNumber[i] = aint32s[i];
1690 /* Advertise a new service. A service is named locally by a UDP port
1691 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1694 char *serviceName; Name for identification purposes (e.g. the
1695 service name might be used for probing for
1698 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1699 char *serviceName, struct rx_securityClass **securityObjects,
1700 int nSecurityObjects,
1701 afs_int32(*serviceProc) (struct rx_call * acall))
1703 osi_socket socket = OSI_NULLSOCKET;
1704 struct rx_service *tservice;
1710 if (serviceId == 0) {
1712 "rx_NewService: service id for service %s is not non-zero.\n",
1719 "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",
1727 tservice = rxi_AllocService();
1730 #ifdef RX_ENABLE_LOCKS
1731 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1734 for (i = 0; i < RX_MAX_SERVICES; i++) {
1735 struct rx_service *service = rx_services[i];
1737 if (port == service->servicePort && host == service->serviceHost) {
1738 if (service->serviceId == serviceId) {
1739 /* The identical service has already been
1740 * installed; if the caller was intending to
1741 * change the security classes used by this
1742 * service, he/she loses. */
1744 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1745 serviceName, serviceId, service->serviceName);
1747 rxi_FreeService(tservice);
1750 /* Different service, same port: re-use the socket
1751 * which is bound to the same port */
1752 socket = service->socket;
1755 if (socket == OSI_NULLSOCKET) {
1756 /* If we don't already have a socket (from another
1757 * service on same port) get a new one */
1758 socket = rxi_GetHostUDPSocket(host, port);
1759 if (socket == OSI_NULLSOCKET) {
1761 rxi_FreeService(tservice);
1766 service->socket = socket;
1767 service->serviceHost = host;
1768 service->servicePort = port;
1769 service->serviceId = serviceId;
1770 service->serviceName = serviceName;
1771 service->nSecurityObjects = nSecurityObjects;
1772 service->securityObjects = securityObjects;
1773 service->minProcs = 0;
1774 service->maxProcs = 1;
1775 service->idleDeadTime = 60;
1776 service->idleDeadErr = 0;
1777 service->connDeadTime = rx_connDeadTime;
1778 service->executeRequestProc = serviceProc;
1779 service->checkReach = 0;
1780 service->nSpecific = 0;
1781 service->specific = NULL;
1782 rx_services[i] = service; /* not visible until now */
1788 rxi_FreeService(tservice);
1789 (osi_Msg "rx_NewService: cannot support > %d services\n",
1794 /* Set configuration options for all of a service's security objects */
1797 rx_SetSecurityConfiguration(struct rx_service *service,
1798 rx_securityConfigVariables type,
1802 for (i = 0; i<service->nSecurityObjects; i++) {
1803 if (service->securityObjects[i]) {
1804 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1812 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1813 struct rx_securityClass **securityObjects, int nSecurityObjects,
1814 afs_int32(*serviceProc) (struct rx_call * acall))
1816 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1819 /* Generic request processing loop. This routine should be called
1820 * by the implementation dependent rx_ServerProc. If socketp is
1821 * non-null, it will be set to the file descriptor that this thread
1822 * is now listening on. If socketp is null, this routine will never
1825 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1827 struct rx_call *call;
1829 struct rx_service *tservice = NULL;
1836 call = rx_GetCall(threadID, tservice, socketp);
1837 if (socketp && *socketp != OSI_NULLSOCKET) {
1838 /* We are now a listener thread */
1844 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1845 #ifdef RX_ENABLE_LOCKS
1847 #endif /* RX_ENABLE_LOCKS */
1848 afs_termState = AFSOP_STOP_AFS;
1849 afs_osi_Wakeup(&afs_termState);
1850 #ifdef RX_ENABLE_LOCKS
1852 #endif /* RX_ENABLE_LOCKS */
1857 /* if server is restarting( typically smooth shutdown) then do not
1858 * allow any new calls.
1861 if (rx_tranquil && (call != NULL)) {
1865 MUTEX_ENTER(&call->lock);
1867 rxi_CallError(call, RX_RESTARTING);
1868 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1870 MUTEX_EXIT(&call->lock);
1875 tservice = call->conn->service;
1877 if (tservice->beforeProc)
1878 (*tservice->beforeProc) (call);
1880 code = tservice->executeRequestProc(call);
1882 if (tservice->afterProc)
1883 (*tservice->afterProc) (call, code);
1885 rx_EndCall(call, code);
1887 if (tservice->postProc)
1888 (*tservice->postProc) (code);
1890 if (rx_stats_active) {
1891 MUTEX_ENTER(&rx_stats_mutex);
1893 MUTEX_EXIT(&rx_stats_mutex);
1900 rx_WakeupServerProcs(void)
1902 struct rx_serverQueueEntry *np, *tqp;
1906 MUTEX_ENTER(&rx_serverPool_lock);
1908 #ifdef RX_ENABLE_LOCKS
1909 if (rx_waitForPacket)
1910 CV_BROADCAST(&rx_waitForPacket->cv);
1911 #else /* RX_ENABLE_LOCKS */
1912 if (rx_waitForPacket)
1913 osi_rxWakeup(rx_waitForPacket);
1914 #endif /* RX_ENABLE_LOCKS */
1915 MUTEX_ENTER(&freeSQEList_lock);
1916 for (np = rx_FreeSQEList; np; np = tqp) {
1917 tqp = *(struct rx_serverQueueEntry **)np;
1918 #ifdef RX_ENABLE_LOCKS
1919 CV_BROADCAST(&np->cv);
1920 #else /* RX_ENABLE_LOCKS */
1922 #endif /* RX_ENABLE_LOCKS */
1924 MUTEX_EXIT(&freeSQEList_lock);
1925 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1926 #ifdef RX_ENABLE_LOCKS
1927 CV_BROADCAST(&np->cv);
1928 #else /* RX_ENABLE_LOCKS */
1930 #endif /* RX_ENABLE_LOCKS */
1932 MUTEX_EXIT(&rx_serverPool_lock);
1937 * One thing that seems to happen is that all the server threads get
1938 * tied up on some empty or slow call, and then a whole bunch of calls
1939 * arrive at once, using up the packet pool, so now there are more
1940 * empty calls. The most critical resources here are server threads
1941 * and the free packet pool. The "doreclaim" code seems to help in
1942 * general. I think that eventually we arrive in this state: there
1943 * are lots of pending calls which do have all their packets present,
1944 * so they won't be reclaimed, are multi-packet calls, so they won't
1945 * be scheduled until later, and thus are tying up most of the free
1946 * packet pool for a very long time.
1948 * 1. schedule multi-packet calls if all the packets are present.
1949 * Probably CPU-bound operation, useful to return packets to pool.
1950 * Do what if there is a full window, but the last packet isn't here?
1951 * 3. preserve one thread which *only* runs "best" calls, otherwise
1952 * it sleeps and waits for that type of call.
1953 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1954 * the current dataquota business is badly broken. The quota isn't adjusted
1955 * to reflect how many packets are presently queued for a running call.
1956 * So, when we schedule a queued call with a full window of packets queued
1957 * up for it, that *should* free up a window full of packets for other 2d-class
1958 * calls to be able to use from the packet pool. But it doesn't.
1960 * NB. Most of the time, this code doesn't run -- since idle server threads
1961 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1962 * as a new call arrives.
1964 /* Sleep until a call arrives. Returns a pointer to the call, ready
1965 * for an rx_Read. */
1966 #ifdef RX_ENABLE_LOCKS
1968 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1970 struct rx_serverQueueEntry *sq;
1971 struct rx_call *call = (struct rx_call *)0;
1972 struct rx_service *service = NULL;
1974 MUTEX_ENTER(&freeSQEList_lock);
1976 if ((sq = rx_FreeSQEList)) {
1977 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1978 MUTEX_EXIT(&freeSQEList_lock);
1979 } else { /* otherwise allocate a new one and return that */
1980 MUTEX_EXIT(&freeSQEList_lock);
1981 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1982 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1983 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1986 MUTEX_ENTER(&rx_serverPool_lock);
1987 if (cur_service != NULL) {
1988 ReturnToServerPool(cur_service);
1991 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1992 struct rx_call *tcall, *ncall, *choice2 = NULL;
1994 /* Scan for eligible incoming calls. A call is not eligible
1995 * if the maximum number of calls for its service type are
1996 * already executing */
1997 /* One thread will process calls FCFS (to prevent starvation),
1998 * while the other threads may run ahead looking for calls which
1999 * have all their input data available immediately. This helps
2000 * keep threads from blocking, waiting for data from the client. */
2001 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2002 service = tcall->conn->service;
2003 if (!QuotaOK(service)) {
2006 MUTEX_ENTER(&rx_pthread_mutex);
2007 if (tno == rxi_fcfs_thread_num
2008 || !tcall->queue_item_header.next) {
2009 MUTEX_EXIT(&rx_pthread_mutex);
2010 /* If we're the fcfs thread , then we'll just use
2011 * this call. If we haven't been able to find an optimal
2012 * choice, and we're at the end of the list, then use a
2013 * 2d choice if one has been identified. Otherwise... */
2014 call = (choice2 ? choice2 : tcall);
2015 service = call->conn->service;
2017 MUTEX_EXIT(&rx_pthread_mutex);
2018 if (!queue_IsEmpty(&tcall->rq)) {
2019 struct rx_packet *rp;
2020 rp = queue_First(&tcall->rq, rx_packet);
2021 if (rp->header.seq == 1) {
2023 || (rp->header.flags & RX_LAST_PACKET)) {
2025 } else if (rxi_2dchoice && !choice2
2026 && !(tcall->flags & RX_CALL_CLEARED)
2027 && (tcall->rprev > rxi_HardAckRate)) {
2037 ReturnToServerPool(service);
2044 MUTEX_EXIT(&rx_serverPool_lock);
2045 MUTEX_ENTER(&call->lock);
2047 if (call->flags & RX_CALL_WAIT_PROC) {
2048 call->flags &= ~RX_CALL_WAIT_PROC;
2049 rx_atomic_dec(&rx_nWaiting);
2052 if (call->state != RX_STATE_PRECALL || call->error) {
2053 MUTEX_EXIT(&call->lock);
2054 MUTEX_ENTER(&rx_serverPool_lock);
2055 ReturnToServerPool(service);
2060 if (queue_IsEmpty(&call->rq)
2061 || queue_First(&call->rq, rx_packet)->header.seq != 1)
2062 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2064 CLEAR_CALL_QUEUE_LOCK(call);
2067 /* If there are no eligible incoming calls, add this process
2068 * to the idle server queue, to wait for one */
2072 *socketp = OSI_NULLSOCKET;
2074 sq->socketp = socketp;
2075 queue_Append(&rx_idleServerQueue, sq);
2076 #ifndef AFS_AIX41_ENV
2077 rx_waitForPacket = sq;
2079 rx_waitingForPacket = sq;
2080 #endif /* AFS_AIX41_ENV */
2082 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2084 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2085 MUTEX_EXIT(&rx_serverPool_lock);
2086 return (struct rx_call *)0;
2089 } while (!(call = sq->newcall)
2090 && !(socketp && *socketp != OSI_NULLSOCKET));
2091 MUTEX_EXIT(&rx_serverPool_lock);
2093 MUTEX_ENTER(&call->lock);
2099 MUTEX_ENTER(&freeSQEList_lock);
2100 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2101 rx_FreeSQEList = sq;
2102 MUTEX_EXIT(&freeSQEList_lock);
2105 clock_GetTime(&call->startTime);
2106 call->state = RX_STATE_ACTIVE;
2107 call->mode = RX_MODE_RECEIVING;
2108 #ifdef RX_KERNEL_TRACE
2109 if (ICL_SETACTIVE(afs_iclSetp)) {
2110 int glockOwner = ISAFS_GLOCK();
2113 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2114 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2121 rxi_calltrace(RX_CALL_START, call);
2122 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2123 call->conn->service->servicePort, call->conn->service->serviceId,
2126 MUTEX_EXIT(&call->lock);
2127 MUTEX_ENTER(&rx_refcnt_mutex);
2128 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2129 MUTEX_EXIT(&rx_refcnt_mutex);
2131 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2136 #else /* RX_ENABLE_LOCKS */
2138 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2140 struct rx_serverQueueEntry *sq;
2141 struct rx_call *call = (struct rx_call *)0, *choice2;
2142 struct rx_service *service = NULL;
2146 MUTEX_ENTER(&freeSQEList_lock);
2148 if ((sq = rx_FreeSQEList)) {
2149 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2150 MUTEX_EXIT(&freeSQEList_lock);
2151 } else { /* otherwise allocate a new one and return that */
2152 MUTEX_EXIT(&freeSQEList_lock);
2153 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2154 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2155 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2157 MUTEX_ENTER(&sq->lock);
2159 if (cur_service != NULL) {
2160 cur_service->nRequestsRunning--;
2161 MUTEX_ENTER(&rx_quota_mutex);
2162 if (cur_service->nRequestsRunning < cur_service->minProcs)
2165 MUTEX_EXIT(&rx_quota_mutex);
2167 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2168 struct rx_call *tcall, *ncall;
2169 /* Scan for eligible incoming calls. A call is not eligible
2170 * if the maximum number of calls for its service type are
2171 * already executing */
2172 /* One thread will process calls FCFS (to prevent starvation),
2173 * while the other threads may run ahead looking for calls which
2174 * have all their input data available immediately. This helps
2175 * keep threads from blocking, waiting for data from the client. */
2176 choice2 = (struct rx_call *)0;
2177 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2178 service = tcall->conn->service;
2179 if (QuotaOK(service)) {
2180 MUTEX_ENTER(&rx_pthread_mutex);
2181 if (tno == rxi_fcfs_thread_num
2182 || !tcall->queue_item_header.next) {
2183 MUTEX_EXIT(&rx_pthread_mutex);
2184 /* If we're the fcfs thread, then we'll just use
2185 * this call. If we haven't been able to find an optimal
2186 * choice, and we're at the end of the list, then use a
2187 * 2d choice if one has been identified. Otherwise... */
2188 call = (choice2 ? choice2 : tcall);
2189 service = call->conn->service;
2191 MUTEX_EXIT(&rx_pthread_mutex);
2192 if (!queue_IsEmpty(&tcall->rq)) {
2193 struct rx_packet *rp;
2194 rp = queue_First(&tcall->rq, rx_packet);
2195 if (rp->header.seq == 1
2197 || (rp->header.flags & RX_LAST_PACKET))) {
2199 } else if (rxi_2dchoice && !choice2
2200 && !(tcall->flags & RX_CALL_CLEARED)
2201 && (tcall->rprev > rxi_HardAckRate)) {
2215 /* we can't schedule a call if there's no data!!! */
2216 /* send an ack if there's no data, if we're missing the
2217 * first packet, or we're missing something between first
2218 * and last -- there's a "hole" in the incoming data. */
2219 if (queue_IsEmpty(&call->rq)
2220 || queue_First(&call->rq, rx_packet)->header.seq != 1
2221 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2222 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2224 call->flags &= (~RX_CALL_WAIT_PROC);
2225 service->nRequestsRunning++;
2226 /* just started call in minProcs pool, need fewer to maintain
2228 MUTEX_ENTER(&rx_quota_mutex);
2229 if (service->nRequestsRunning <= service->minProcs)
2232 MUTEX_EXIT(&rx_quota_mutex);
2233 rx_atomic_dec(&rx_nWaiting);
2234 /* MUTEX_EXIT(&call->lock); */
2236 /* If there are no eligible incoming calls, add this process
2237 * to the idle server queue, to wait for one */
2240 *socketp = OSI_NULLSOCKET;
2242 sq->socketp = socketp;
2243 queue_Append(&rx_idleServerQueue, sq);
2247 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2249 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2250 return (struct rx_call *)0;
2253 } while (!(call = sq->newcall)
2254 && !(socketp && *socketp != OSI_NULLSOCKET));
2256 MUTEX_EXIT(&sq->lock);
2258 MUTEX_ENTER(&freeSQEList_lock);
2259 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2260 rx_FreeSQEList = sq;
2261 MUTEX_EXIT(&freeSQEList_lock);
2264 clock_GetTime(&call->startTime);
2265 call->state = RX_STATE_ACTIVE;
2266 call->mode = RX_MODE_RECEIVING;
2267 #ifdef RX_KERNEL_TRACE
2268 if (ICL_SETACTIVE(afs_iclSetp)) {
2269 int glockOwner = ISAFS_GLOCK();
2272 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2273 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2280 rxi_calltrace(RX_CALL_START, call);
2281 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2282 call->conn->service->servicePort, call->conn->service->serviceId,
2285 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2292 #endif /* RX_ENABLE_LOCKS */
2296 /* Establish a procedure to be called when a packet arrives for a
2297 * call. This routine will be called at most once after each call,
2298 * and will also be called if there is an error condition on the or
2299 * the call is complete. Used by multi rx to build a selection
2300 * function which determines which of several calls is likely to be a
2301 * good one to read from.
2302 * NOTE: the way this is currently implemented it is probably only a
2303 * good idea to (1) use it immediately after a newcall (clients only)
2304 * and (2) only use it once. Other uses currently void your warranty
2307 rx_SetArrivalProc(struct rx_call *call,
2308 void (*proc) (struct rx_call * call,
2311 void * handle, int arg)
2313 call->arrivalProc = proc;
2314 call->arrivalProcHandle = handle;
2315 call->arrivalProcArg = arg;
2318 /* Call is finished (possibly prematurely). Return rc to the peer, if
2319 * appropriate, and return the final error code from the conversation
2323 rx_EndCall(struct rx_call *call, afs_int32 rc)
2325 struct rx_connection *conn = call->conn;
2329 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2330 call, rc, call->error, call->abortCode));
2333 MUTEX_ENTER(&call->lock);
2335 if (rc == 0 && call->error == 0) {
2336 call->abortCode = 0;
2337 call->abortCount = 0;
2340 call->arrivalProc = (void (*)())0;
2341 if (rc && call->error == 0) {
2342 rxi_CallError(call, rc);
2343 call->mode = RX_MODE_ERROR;
2344 /* Send an abort message to the peer if this error code has
2345 * only just been set. If it was set previously, assume the
2346 * peer has already been sent the error code or will request it
2348 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2350 if (conn->type == RX_SERVER_CONNECTION) {
2351 /* Make sure reply or at least dummy reply is sent */
2352 if (call->mode == RX_MODE_RECEIVING) {
2353 MUTEX_EXIT(&call->lock);
2354 rxi_WriteProc(call, 0, 0);
2355 MUTEX_ENTER(&call->lock);
2357 if (call->mode == RX_MODE_SENDING) {
2358 MUTEX_EXIT(&call->lock);
2359 rxi_FlushWrite(call);
2360 MUTEX_ENTER(&call->lock);
2362 rxi_calltrace(RX_CALL_END, call);
2363 /* Call goes to hold state until reply packets are acknowledged */
2364 if (call->tfirst + call->nSoftAcked < call->tnext) {
2365 call->state = RX_STATE_HOLD;
2367 call->state = RX_STATE_DALLY;
2368 rxi_ClearTransmitQueue(call, 0);
2369 rxi_rto_cancel(call);
2370 rxevent_Cancel(&call->keepAliveEvent, call,
2371 RX_CALL_REFCOUNT_ALIVE);
2373 } else { /* Client connection */
2375 /* Make sure server receives input packets, in the case where
2376 * no reply arguments are expected */
2377 if ((call->mode == RX_MODE_SENDING)
2378 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2379 MUTEX_EXIT(&call->lock);
2380 (void)rxi_ReadProc(call, &dummy, 1);
2381 MUTEX_ENTER(&call->lock);
2384 /* If we had an outstanding delayed ack, be nice to the server
2385 * and force-send it now.
2387 if (call->delayedAckEvent) {
2388 rxevent_Cancel(&call->delayedAckEvent, call,
2389 RX_CALL_REFCOUNT_DELAY);
2390 rxi_SendDelayedAck(NULL, call, NULL, 0);
2393 /* We need to release the call lock since it's lower than the
2394 * conn_call_lock and we don't want to hold the conn_call_lock
2395 * over the rx_ReadProc call. The conn_call_lock needs to be held
2396 * here for the case where rx_NewCall is perusing the calls on
2397 * the connection structure. We don't want to signal until
2398 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2399 * have checked this call, found it active and by the time it
2400 * goes to sleep, will have missed the signal.
2402 MUTEX_EXIT(&call->lock);
2403 MUTEX_ENTER(&conn->conn_call_lock);
2404 MUTEX_ENTER(&call->lock);
2406 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2407 conn->lastBusy[call->channel] = 0;
2410 MUTEX_ENTER(&conn->conn_data_lock);
2411 conn->flags |= RX_CONN_BUSY;
2412 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2413 MUTEX_EXIT(&conn->conn_data_lock);
2414 #ifdef RX_ENABLE_LOCKS
2415 CV_BROADCAST(&conn->conn_call_cv);
2420 #ifdef RX_ENABLE_LOCKS
2422 MUTEX_EXIT(&conn->conn_data_lock);
2424 #endif /* RX_ENABLE_LOCKS */
2425 call->state = RX_STATE_DALLY;
2427 error = call->error;
2429 /* currentPacket, nLeft, and NFree must be zeroed here, because
2430 * ResetCall cannot: ResetCall may be called at splnet(), in the
2431 * kernel version, and may interrupt the macros rx_Read or
2432 * rx_Write, which run at normal priority for efficiency. */
2433 if (call->currentPacket) {
2434 #ifdef RX_TRACK_PACKETS
2435 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2437 rxi_FreePacket(call->currentPacket);
2438 call->currentPacket = (struct rx_packet *)0;
2441 call->nLeft = call->nFree = call->curlen = 0;
2443 /* Free any packets from the last call to ReadvProc/WritevProc */
2444 #ifdef RXDEBUG_PACKET
2446 #endif /* RXDEBUG_PACKET */
2447 rxi_FreePackets(0, &call->iovq);
2448 MUTEX_EXIT(&call->lock);
2450 MUTEX_ENTER(&rx_refcnt_mutex);
2451 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2452 MUTEX_EXIT(&rx_refcnt_mutex);
2453 if (conn->type == RX_CLIENT_CONNECTION) {
2454 MUTEX_ENTER(&conn->conn_data_lock);
2455 conn->flags &= ~RX_CONN_BUSY;
2456 MUTEX_EXIT(&conn->conn_data_lock);
2457 MUTEX_EXIT(&conn->conn_call_lock);
2461 * Map errors to the local host's errno.h format.
2463 error = ntoh_syserr_conv(error);
2467 #if !defined(KERNEL)
2469 /* Call this routine when shutting down a server or client (especially
2470 * clients). This will allow Rx to gracefully garbage collect server
2471 * connections, and reduce the number of retries that a server might
2472 * make to a dead client.
2473 * This is not quite right, since some calls may still be ongoing and
2474 * we can't lock them to destroy them. */
2478 struct rx_connection **conn_ptr, **conn_end;
2482 if (rxinit_status == 1) {
2484 return; /* Already shutdown. */
2486 rxi_DeleteCachedConnections();
2487 if (rx_connHashTable) {
2488 MUTEX_ENTER(&rx_connHashTable_lock);
2489 for (conn_ptr = &rx_connHashTable[0], conn_end =
2490 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2492 struct rx_connection *conn, *next;
2493 for (conn = *conn_ptr; conn; conn = next) {
2495 if (conn->type == RX_CLIENT_CONNECTION) {
2496 MUTEX_ENTER(&rx_refcnt_mutex);
2498 MUTEX_EXIT(&rx_refcnt_mutex);
2499 #ifdef RX_ENABLE_LOCKS
2500 rxi_DestroyConnectionNoLock(conn);
2501 #else /* RX_ENABLE_LOCKS */
2502 rxi_DestroyConnection(conn);
2503 #endif /* RX_ENABLE_LOCKS */
2507 #ifdef RX_ENABLE_LOCKS
2508 while (rx_connCleanup_list) {
2509 struct rx_connection *conn;
2510 conn = rx_connCleanup_list;
2511 rx_connCleanup_list = rx_connCleanup_list->next;
2512 MUTEX_EXIT(&rx_connHashTable_lock);
2513 rxi_CleanupConnection(conn);
2514 MUTEX_ENTER(&rx_connHashTable_lock);
2516 MUTEX_EXIT(&rx_connHashTable_lock);
2517 #endif /* RX_ENABLE_LOCKS */
2522 afs_winsockCleanup();
2530 /* if we wakeup packet waiter too often, can get in loop with two
2531 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2533 rxi_PacketsUnWait(void)
2535 if (!rx_waitingForPackets) {
2539 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2540 return; /* still over quota */
2543 rx_waitingForPackets = 0;
2544 #ifdef RX_ENABLE_LOCKS
2545 CV_BROADCAST(&rx_waitingForPackets_cv);
2547 osi_rxWakeup(&rx_waitingForPackets);
2553 /* ------------------Internal interfaces------------------------- */
2555 /* Return this process's service structure for the
2556 * specified socket and service */
2557 static struct rx_service *
2558 rxi_FindService(osi_socket socket, u_short serviceId)
2560 struct rx_service **sp;
2561 for (sp = &rx_services[0]; *sp; sp++) {
2562 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2568 #ifdef RXDEBUG_PACKET
2569 #ifdef KDUMP_RX_LOCK
2570 static struct rx_call_rx_lock *rx_allCallsp = 0;
2572 static struct rx_call *rx_allCallsp = 0;
2574 #endif /* RXDEBUG_PACKET */
2576 /* Allocate a call structure, for the indicated channel of the
2577 * supplied connection. The mode and state of the call must be set by
2578 * the caller. Returns the call with mutex locked. */
2579 static struct rx_call *
2580 rxi_NewCall(struct rx_connection *conn, int channel)
2582 struct rx_call *call;
2583 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2584 struct rx_call *cp; /* Call pointer temp */
2585 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2586 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2588 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2590 /* Grab an existing call structure, or allocate a new one.
2591 * Existing call structures are assumed to have been left reset by
2593 MUTEX_ENTER(&rx_freeCallQueue_lock);
2595 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2597 * EXCEPT that the TQ might not yet be cleared out.
2598 * Skip over those with in-use TQs.
2601 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2602 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2608 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2609 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2610 call = queue_First(&rx_freeCallQueue, rx_call);
2611 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2613 if (rx_stats_active)
2614 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2615 MUTEX_EXIT(&rx_freeCallQueue_lock);
2616 MUTEX_ENTER(&call->lock);
2617 CLEAR_CALL_QUEUE_LOCK(call);
2618 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2619 /* Now, if TQ wasn't cleared earlier, do it now. */
2620 rxi_WaitforTQBusy(call);
2621 if (call->flags & RX_CALL_TQ_CLEARME) {
2622 rxi_ClearTransmitQueue(call, 1);
2623 /*queue_Init(&call->tq);*/
2625 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2626 /* Bind the call to its connection structure */
2628 rxi_ResetCall(call, 1);
2631 call = rxi_Alloc(sizeof(struct rx_call));
2632 #ifdef RXDEBUG_PACKET
2633 call->allNextp = rx_allCallsp;
2634 rx_allCallsp = call;
2636 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2637 #else /* RXDEBUG_PACKET */
2638 rx_atomic_inc(&rx_stats.nCallStructs);
2639 #endif /* RXDEBUG_PACKET */
2641 MUTEX_EXIT(&rx_freeCallQueue_lock);
2642 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2643 MUTEX_ENTER(&call->lock);
2644 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2645 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2646 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2648 /* Initialize once-only items */
2649 queue_Init(&call->tq);
2650 queue_Init(&call->rq);
2651 queue_Init(&call->iovq);
2652 #ifdef RXDEBUG_PACKET
2653 call->rqc = call->tqc = call->iovqc = 0;
2654 #endif /* RXDEBUG_PACKET */
2655 /* Bind the call to its connection structure (prereq for reset) */
2657 rxi_ResetCall(call, 1);
2659 call->channel = channel;
2660 call->callNumber = &conn->callNumber[channel];
2661 call->rwind = conn->rwind[channel];
2662 call->twind = conn->twind[channel];
2663 /* Note that the next expected call number is retained (in
2664 * conn->callNumber[i]), even if we reallocate the call structure
2666 conn->call[channel] = call;
2667 /* if the channel's never been used (== 0), we should start at 1, otherwise
2668 * the call number is valid from the last time this channel was used */
2669 if (*call->callNumber == 0)
2670 *call->callNumber = 1;
2675 /* A call has been inactive long enough that so we can throw away
2676 * state, including the call structure, which is placed on the call
2679 * call->lock amd rx_refcnt_mutex are held upon entry.
2680 * haveCTLock is set when called from rxi_ReapConnections.
2683 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2685 int channel = call->channel;
2686 struct rx_connection *conn = call->conn;
2689 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2690 (*call->callNumber)++;
2692 * We are setting the state to RX_STATE_RESET to
2693 * ensure that no one else will attempt to use this
2694 * call once we drop the refcnt lock. We must drop
2695 * the refcnt lock before calling rxi_ResetCall
2696 * because it cannot be held across acquiring the
2697 * freepktQ lock. NewCall does the same.
2699 call->state = RX_STATE_RESET;
2700 MUTEX_EXIT(&rx_refcnt_mutex);
2701 rxi_ResetCall(call, 0);
2703 MUTEX_ENTER(&conn->conn_call_lock);
2704 if (call->conn->call[channel] == call)
2705 call->conn->call[channel] = 0;
2706 MUTEX_EXIT(&conn->conn_call_lock);
2708 MUTEX_ENTER(&rx_freeCallQueue_lock);
2709 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2710 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2711 /* A call may be free even though its transmit queue is still in use.
2712 * Since we search the call list from head to tail, put busy calls at
2713 * the head of the list, and idle calls at the tail.
2715 if (call->flags & RX_CALL_TQ_BUSY)
2716 queue_Prepend(&rx_freeCallQueue, call);
2718 queue_Append(&rx_freeCallQueue, call);
2719 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2720 queue_Append(&rx_freeCallQueue, call);
2721 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2722 if (rx_stats_active)
2723 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2724 MUTEX_EXIT(&rx_freeCallQueue_lock);
2726 /* Destroy the connection if it was previously slated for
2727 * destruction, i.e. the Rx client code previously called
2728 * rx_DestroyConnection (client connections), or
2729 * rxi_ReapConnections called the same routine (server
2730 * connections). Only do this, however, if there are no
2731 * outstanding calls. Note that for fine grain locking, there appears
2732 * to be a deadlock in that rxi_FreeCall has a call locked and
2733 * DestroyConnectionNoLock locks each call in the conn. But note a
2734 * few lines up where we have removed this call from the conn.
2735 * If someone else destroys a connection, they either have no
2736 * call lock held or are going through this section of code.
2738 MUTEX_ENTER(&conn->conn_data_lock);
2739 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2740 MUTEX_ENTER(&rx_refcnt_mutex);
2742 MUTEX_EXIT(&rx_refcnt_mutex);
2743 MUTEX_EXIT(&conn->conn_data_lock);
2744 #ifdef RX_ENABLE_LOCKS
2746 rxi_DestroyConnectionNoLock(conn);
2748 rxi_DestroyConnection(conn);
2749 #else /* RX_ENABLE_LOCKS */
2750 rxi_DestroyConnection(conn);
2751 #endif /* RX_ENABLE_LOCKS */
2753 MUTEX_EXIT(&conn->conn_data_lock);
2755 MUTEX_ENTER(&rx_refcnt_mutex);
2758 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2759 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2762 rxi_Alloc(size_t size)
2766 if (rx_stats_active) {
2767 rx_atomic_add(&rxi_Allocsize, (int) size);
2768 rx_atomic_inc(&rxi_Alloccnt);
2772 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2773 afs_osi_Alloc_NoSleep(size);
2778 osi_Panic("rxi_Alloc error");
2784 rxi_Free(void *addr, size_t size)
2786 if (rx_stats_active) {
2787 rx_atomic_sub(&rxi_Allocsize, (int) size);
2788 rx_atomic_dec(&rxi_Alloccnt);
2790 osi_Free(addr, size);
2794 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2796 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2797 struct rx_peer *next = NULL;
2801 MUTEX_ENTER(&rx_peerHashTable_lock);
2803 peer_ptr = &rx_peerHashTable[0];
2804 peer_end = &rx_peerHashTable[rx_hashTableSize];
2807 for ( ; peer_ptr < peer_end; peer_ptr++) {
2810 for ( ; peer; peer = next) {
2812 if (host == peer->host)
2817 hashIndex = PEER_HASH(host, port);
2818 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2819 if ((peer->host == host) && (peer->port == port))
2824 MUTEX_ENTER(&rx_peerHashTable_lock);
2829 MUTEX_EXIT(&rx_peerHashTable_lock);
2831 MUTEX_ENTER(&peer->peer_lock);
2832 /* We don't handle dropping below min, so don't */
2833 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2834 peer->ifMTU=MIN(mtu, peer->ifMTU);
2835 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2836 /* if we tweaked this down, need to tune our peer MTU too */
2837 peer->MTU = MIN(peer->MTU, peer->natMTU);
2838 /* if we discovered a sub-1500 mtu, degrade */
2839 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2840 peer->maxDgramPackets = 1;
2841 /* We no longer have valid peer packet information */
2842 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2843 peer->maxPacketSize = 0;
2844 MUTEX_EXIT(&peer->peer_lock);
2846 MUTEX_ENTER(&rx_peerHashTable_lock);
2848 if (host && !port) {
2850 /* pick up where we left off */
2854 MUTEX_EXIT(&rx_peerHashTable_lock);
2857 /* Find the peer process represented by the supplied (host,port)
2858 * combination. If there is no appropriate active peer structure, a
2859 * new one will be allocated and initialized
2860 * The origPeer, if set, is a pointer to a peer structure on which the
2861 * refcount will be be decremented. This is used to replace the peer
2862 * structure hanging off a connection structure */
2864 rxi_FindPeer(afs_uint32 host, u_short port,
2865 struct rx_peer *origPeer, int create)
2869 hashIndex = PEER_HASH(host, port);
2870 MUTEX_ENTER(&rx_peerHashTable_lock);
2871 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2872 if ((pp->host == host) && (pp->port == port))
2877 pp = rxi_AllocPeer(); /* This bzero's *pp */
2878 pp->host = host; /* set here or in InitPeerParams is zero */
2880 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2881 queue_Init(&pp->congestionQueue);
2882 queue_Init(&pp->rpcStats);
2883 pp->next = rx_peerHashTable[hashIndex];
2884 rx_peerHashTable[hashIndex] = pp;
2885 rxi_InitPeerParams(pp);
2886 if (rx_stats_active)
2887 rx_atomic_inc(&rx_stats.nPeerStructs);
2894 origPeer->refCount--;
2895 MUTEX_EXIT(&rx_peerHashTable_lock);
2900 /* Find the connection at (host, port) started at epoch, and with the
2901 * given connection id. Creates the server connection if necessary.
2902 * The type specifies whether a client connection or a server
2903 * connection is desired. In both cases, (host, port) specify the
2904 * peer's (host, pair) pair. Client connections are not made
2905 * automatically by this routine. The parameter socket gives the
2906 * socket descriptor on which the packet was received. This is used,
2907 * in the case of server connections, to check that *new* connections
2908 * come via a valid (port, serviceId). Finally, the securityIndex
2909 * parameter must match the existing index for the connection. If a
2910 * server connection is created, it will be created using the supplied
2911 * index, if the index is valid for this service */
2912 struct rx_connection *
2913 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2914 u_short port, u_short serviceId, afs_uint32 cid,
2915 afs_uint32 epoch, int type, u_int securityIndex)
2917 int hashindex, flag, i;
2918 struct rx_connection *conn;
2919 hashindex = CONN_HASH(host, port, cid, epoch, type);
2920 MUTEX_ENTER(&rx_connHashTable_lock);
2921 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2922 rx_connHashTable[hashindex],
2925 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2926 && (epoch == conn->epoch)) {
2927 struct rx_peer *pp = conn->peer;
2928 if (securityIndex != conn->securityIndex) {
2929 /* this isn't supposed to happen, but someone could forge a packet
2930 * like this, and there seems to be some CM bug that makes this
2931 * happen from time to time -- in which case, the fileserver
2933 MUTEX_EXIT(&rx_connHashTable_lock);
2934 return (struct rx_connection *)0;
2936 if (pp->host == host && pp->port == port)
2938 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2940 /* So what happens when it's a callback connection? */
2941 if ( /*type == RX_CLIENT_CONNECTION && */
2942 (conn->epoch & 0x80000000))
2946 /* the connection rxLastConn that was used the last time is not the
2947 ** one we are looking for now. Hence, start searching in the hash */
2949 conn = rx_connHashTable[hashindex];
2954 struct rx_service *service;
2955 if (type == RX_CLIENT_CONNECTION) {
2956 MUTEX_EXIT(&rx_connHashTable_lock);
2957 return (struct rx_connection *)0;
2959 service = rxi_FindService(socket, serviceId);
2960 if (!service || (securityIndex >= service->nSecurityObjects)
2961 || (service->securityObjects[securityIndex] == 0)) {
2962 MUTEX_EXIT(&rx_connHashTable_lock);
2963 return (struct rx_connection *)0;
2965 conn = rxi_AllocConnection(); /* This bzero's the connection */
2966 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2967 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2968 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2969 conn->next = rx_connHashTable[hashindex];
2970 rx_connHashTable[hashindex] = conn;
2971 conn->peer = rxi_FindPeer(host, port, 0, 1);
2972 conn->type = RX_SERVER_CONNECTION;
2973 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2974 conn->epoch = epoch;
2975 conn->cid = cid & RX_CIDMASK;
2976 /* conn->serial = conn->lastSerial = 0; */
2977 /* conn->timeout = 0; */
2978 conn->ackRate = RX_FAST_ACK_RATE;
2979 conn->service = service;
2980 conn->serviceId = serviceId;
2981 conn->securityIndex = securityIndex;
2982 conn->securityObject = service->securityObjects[securityIndex];
2983 conn->nSpecific = 0;
2984 conn->specific = NULL;
2985 rx_SetConnDeadTime(conn, service->connDeadTime);
2986 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2987 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2988 for (i = 0; i < RX_MAXCALLS; i++) {
2989 conn->twind[i] = rx_initSendWindow;
2990 conn->rwind[i] = rx_initReceiveWindow;
2992 /* Notify security object of the new connection */
2993 RXS_NewConnection(conn->securityObject, conn);
2994 /* XXXX Connection timeout? */
2995 if (service->newConnProc)
2996 (*service->newConnProc) (conn);
2997 if (rx_stats_active)
2998 rx_atomic_inc(&rx_stats.nServerConns);
3001 MUTEX_ENTER(&rx_refcnt_mutex);
3003 MUTEX_EXIT(&rx_refcnt_mutex);
3005 rxLastConn = conn; /* store this connection as the last conn used */
3006 MUTEX_EXIT(&rx_connHashTable_lock);
3011 * Timeout a call on a busy call channel if appropriate.
3013 * @param[in] call The busy call.
3015 * @pre 'call' is marked as busy (namely,
3016 * call->conn->lastBusy[call->channel] != 0)
3018 * @pre call->lock is held
3019 * @pre rxi_busyChannelError is nonzero
3021 * @note call->lock is dropped and reacquired
3024 rxi_CheckBusy(struct rx_call *call)
3026 struct rx_connection *conn = call->conn;
3027 int channel = call->channel;
3028 int freechannel = 0;
3030 afs_uint32 callNumber = *call->callNumber;
3032 MUTEX_EXIT(&call->lock);
3034 MUTEX_ENTER(&conn->conn_call_lock);
3036 /* Are there any other call slots on this conn that we should try? Look for
3037 * slots that are empty and are either non-busy, or were marked as busy
3038 * longer than conn->secondsUntilDead seconds before this call started. */
3040 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
3042 /* only look at channels that aren't us */
3046 if (conn->lastBusy[i]) {
3047 /* if this channel looked busy too recently, don't look at it */
3048 if (conn->lastBusy[i] >= call->startTime.sec) {
3051 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
3056 if (conn->call[i]) {
3057 struct rx_call *tcall = conn->call[i];
3058 MUTEX_ENTER(&tcall->lock);
3059 if (tcall->state == RX_STATE_DALLY) {
3062 MUTEX_EXIT(&tcall->lock);
3068 MUTEX_EXIT(&conn->conn_call_lock);
3070 MUTEX_ENTER(&call->lock);
3072 /* Since the call->lock and conn->conn_call_lock have been released it is
3073 * possible that (1) the call may no longer be busy and/or (2) the call may
3074 * have been reused by another waiting thread. Therefore, we must confirm
3075 * that the call state has not changed when deciding whether or not to
3076 * force this application thread to retry by forcing a Timeout error. */
3078 if (freechannel && *call->callNumber == callNumber &&
3079 (call->flags & RX_CALL_PEER_BUSY)) {
3080 /* Since 'freechannel' is set, there exists another channel in this
3081 * rx_conn that the application thread might be able to use. We know
3082 * that we have the correct call since callNumber is unchanged, and we
3083 * know that the call is still busy. So, set the call error state to
3084 * rxi_busyChannelError so the application can retry the request,
3085 * presumably on a less-busy call channel. */
3087 rxi_CallError(call, rxi_busyChannelError);
3091 /* There are two packet tracing routines available for testing and monitoring
3092 * Rx. One is called just after every packet is received and the other is
3093 * called just before every packet is sent. Received packets, have had their
3094 * headers decoded, and packets to be sent have not yet had their headers
3095 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3096 * containing the network address. Both can be modified. The return value, if
3097 * non-zero, indicates that the packet should be dropped. */
3099 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3100 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3102 /* A packet has been received off the interface. Np is the packet, socket is
3103 * the socket number it was received from (useful in determining which service
3104 * this packet corresponds to), and (host, port) reflect the host,port of the
3105 * sender. This call returns the packet to the caller if it is finished with
3106 * it, rather than de-allocating it, just as a small performance hack */
3109 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3110 afs_uint32 host, u_short port, int *tnop,
3111 struct rx_call **newcallp)
3113 struct rx_call *call;
3114 struct rx_connection *conn;
3116 afs_uint32 currentCallNumber;
3122 struct rx_packet *tnp;
3125 /* We don't print out the packet until now because (1) the time may not be
3126 * accurate enough until now in the lwp implementation (rx_Listener only gets
3127 * the time after the packet is read) and (2) from a protocol point of view,
3128 * this is the first time the packet has been seen */
3129 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3130 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3131 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3132 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3133 np->header.epoch, np->header.cid, np->header.callNumber,
3134 np->header.seq, np->header.flags, np));
3137 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3138 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3141 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3142 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3145 /* If an input tracer function is defined, call it with the packet and
3146 * network address. Note this function may modify its arguments. */
3147 if (rx_justReceived) {
3148 struct sockaddr_in addr;
3150 addr.sin_family = AF_INET;
3151 addr.sin_port = port;
3152 addr.sin_addr.s_addr = host;
3153 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3154 addr.sin_len = sizeof(addr);
3155 #endif /* AFS_OSF_ENV */
3156 drop = (*rx_justReceived) (np, &addr);
3157 /* drop packet if return value is non-zero */
3160 port = addr.sin_port; /* in case fcn changed addr */
3161 host = addr.sin_addr.s_addr;
3165 /* If packet was not sent by the client, then *we* must be the client */
3166 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3167 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3169 /* Find the connection (or fabricate one, if we're the server & if
3170 * necessary) associated with this packet */
3172 rxi_FindConnection(socket, host, port, np->header.serviceId,
3173 np->header.cid, np->header.epoch, type,
3174 np->header.securityIndex);
3177 /* If no connection found or fabricated, just ignore the packet.
3178 * (An argument could be made for sending an abort packet for
3183 /* If the connection is in an error state, send an abort packet and ignore
3184 * the incoming packet */
3186 /* Don't respond to an abort packet--we don't want loops! */
3187 MUTEX_ENTER(&conn->conn_data_lock);
3188 if (np->header.type != RX_PACKET_TYPE_ABORT)
3189 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3190 MUTEX_ENTER(&rx_refcnt_mutex);
3192 MUTEX_EXIT(&rx_refcnt_mutex);
3193 MUTEX_EXIT(&conn->conn_data_lock);
3197 /* Check for connection-only requests (i.e. not call specific). */
3198 if (np->header.callNumber == 0) {
3199 switch (np->header.type) {
3200 case RX_PACKET_TYPE_ABORT: {
3201 /* What if the supplied error is zero? */
3202 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3203 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3204 rxi_ConnectionError(conn, errcode);
3205 MUTEX_ENTER(&rx_refcnt_mutex);
3207 MUTEX_EXIT(&rx_refcnt_mutex);
3210 case RX_PACKET_TYPE_CHALLENGE:
3211 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3212 MUTEX_ENTER(&rx_refcnt_mutex);
3214 MUTEX_EXIT(&rx_refcnt_mutex);
3216 case RX_PACKET_TYPE_RESPONSE:
3217 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3218 MUTEX_ENTER(&rx_refcnt_mutex);
3220 MUTEX_EXIT(&rx_refcnt_mutex);
3222 case RX_PACKET_TYPE_PARAMS:
3223 case RX_PACKET_TYPE_PARAMS + 1:
3224 case RX_PACKET_TYPE_PARAMS + 2:
3225 /* ignore these packet types for now */
3226 MUTEX_ENTER(&rx_refcnt_mutex);
3228 MUTEX_EXIT(&rx_refcnt_mutex);
3233 /* Should not reach here, unless the peer is broken: send an
3235 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3236 MUTEX_ENTER(&conn->conn_data_lock);
3237 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3238 MUTEX_ENTER(&rx_refcnt_mutex);
3240 MUTEX_EXIT(&rx_refcnt_mutex);
3241 MUTEX_EXIT(&conn->conn_data_lock);
3246 channel = np->header.cid & RX_CHANNELMASK;
3247 call = conn->call[channel];
3250 MUTEX_ENTER(&call->lock);
3251 currentCallNumber = conn->callNumber[channel];
3252 } else if (type == RX_SERVER_CONNECTION) { /* No call allocated */
3253 MUTEX_ENTER(&conn->conn_call_lock);
3254 call = conn->call[channel];
3256 MUTEX_ENTER(&call->lock);
3257 MUTEX_EXIT(&conn->conn_call_lock);
3258 currentCallNumber = conn->callNumber[channel];
3260 call = rxi_NewCall(conn, channel); /* returns locked call */
3261 MUTEX_EXIT(&conn->conn_call_lock);
3262 *call->callNumber = currentCallNumber = np->header.callNumber;
3264 if (np->header.callNumber == 0)
3265 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3266 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3267 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3268 np->header.flags, np, np->length));
3270 call->state = RX_STATE_PRECALL;
3271 clock_GetTime(&call->queueTime);
3272 hzero(call->bytesSent);
3273 hzero(call->bytesRcvd);
3275 * If the number of queued calls exceeds the overload
3276 * threshold then abort this call.
3278 if ((rx_BusyThreshold > 0) &&
3279 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3280 struct rx_packet *tp;
3282 rxi_CallError(call, rx_BusyError);
3283 tp = rxi_SendCallAbort(call, np, 1, 0);
3284 MUTEX_EXIT(&call->lock);
3285 MUTEX_ENTER(&rx_refcnt_mutex);
3287 MUTEX_EXIT(&rx_refcnt_mutex);
3288 if (rx_stats_active)
3289 rx_atomic_inc(&rx_stats.nBusies);
3292 rxi_KeepAliveOn(call);
3294 } else { /* RX_CLIENT_CONNECTION and No call allocated */
3295 /* This packet can't be for this call. If the new call address is
3296 * 0 then no call is running on this channel. If there is a call
3297 * then, since this is a client connection we're getting data for
3298 * it must be for the previous call.
3300 if (rx_stats_active)
3301 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3302 MUTEX_ENTER(&rx_refcnt_mutex);
3304 MUTEX_EXIT(&rx_refcnt_mutex);
3308 /* There is a non-NULL locked call at this point */
3309 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3310 if (np->header.callNumber < currentCallNumber) {
3311 MUTEX_EXIT(&call->lock);
3312 if (rx_stats_active)
3313 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3314 MUTEX_ENTER(&rx_refcnt_mutex);
3316 MUTEX_EXIT(&rx_refcnt_mutex);
3318 } else if (np->header.callNumber != currentCallNumber) {
3319 /* Wait until the transmit queue is idle before deciding
3320 * whether to reset the current call. Chances are that the
3321 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3324 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3325 if (call->state == RX_STATE_ACTIVE) {
3326 rxi_WaitforTQBusy(call);
3328 * If we entered error state while waiting,
3329 * must call rxi_CallError to permit rxi_ResetCall
3330 * to processed when the tqWaiter count hits zero.
3333 rxi_CallError(call, call->error);
3334 MUTEX_EXIT(&call->lock);
3335 MUTEX_ENTER(&rx_refcnt_mutex);
3337 MUTEX_EXIT(&rx_refcnt_mutex);
3341 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3342 /* If the new call cannot be taken right now send a busy and set
3343 * the error condition in this call, so that it terminates as
3344 * quickly as possible */
3345 if (call->state == RX_STATE_ACTIVE) {
3346 struct rx_packet *tp;
3348 rxi_CallError(call, RX_CALL_DEAD);
3349 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3351 MUTEX_EXIT(&call->lock);
3352 MUTEX_ENTER(&rx_refcnt_mutex);
3354 MUTEX_EXIT(&rx_refcnt_mutex);
3357 rxi_ResetCall(call, 0);
3358 *call->callNumber = np->header.callNumber;
3360 if (np->header.callNumber == 0)
3361 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3362 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3363 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3364 np->header.flags, np, np->length));
3366 call->state = RX_STATE_PRECALL;
3367 clock_GetTime(&call->queueTime);
3368 hzero(call->bytesSent);
3369 hzero(call->bytesRcvd);
3371 * If the number of queued calls exceeds the overload
3372 * threshold then abort this call.
3374 if ((rx_BusyThreshold > 0) &&
3375 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3376 struct rx_packet *tp;
3378 rxi_CallError(call, rx_BusyError);
3379 tp = rxi_SendCallAbort(call, np, 1, 0);
3380 MUTEX_EXIT(&call->lock);
3381 MUTEX_ENTER(&rx_refcnt_mutex);
3383 MUTEX_EXIT(&rx_refcnt_mutex);
3384 if (rx_stats_active)
3385 rx_atomic_inc(&rx_stats.nBusies);
3388 rxi_KeepAliveOn(call);
3390 /* Continuing call; do nothing here. */
3392 } else { /* we're the client */
3393 /* Ignore all incoming acknowledgements for calls in DALLY state */
3394 if ((call->state == RX_STATE_DALLY)
3395 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3396 if (rx_stats_active)
3397 rx_atomic_inc(&rx_stats.ignorePacketDally);
3398 MUTEX_EXIT(&call->lock);
3399 MUTEX_ENTER(&rx_refcnt_mutex);
3401 MUTEX_EXIT(&rx_refcnt_mutex);
3405 /* Ignore anything that's not relevant to the current call. If there
3406 * isn't a current call, then no packet is relevant. */
3407 if (np->header.callNumber != currentCallNumber) {
3408 if (rx_stats_active)
3409 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3410 MUTEX_EXIT(&call->lock);
3411 MUTEX_ENTER(&rx_refcnt_mutex);
3413 MUTEX_EXIT(&rx_refcnt_mutex);
3416 /* If the service security object index stamped in the packet does not
3417 * match the connection's security index, ignore the packet */
3418 if (np->header.securityIndex != conn->securityIndex) {
3419 MUTEX_EXIT(&call->lock);
3420 MUTEX_ENTER(&rx_refcnt_mutex);
3422 MUTEX_EXIT(&rx_refcnt_mutex);
3426 /* If we're receiving the response, then all transmit packets are
3427 * implicitly acknowledged. Get rid of them. */
3428 if (np->header.type == RX_PACKET_TYPE_DATA) {
3429 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3430 /* XXX Hack. Because we must release the global rx lock when
3431 * sending packets (osi_NetSend) we drop all acks while we're
3432 * traversing the tq in rxi_Start sending packets out because
3433 * packets may move to the freePacketQueue as result of being here!
3434 * So we drop these packets until we're safely out of the
3435 * traversing. Really ugly!
3436 * For fine grain RX locking, we set the acked field in the
3437 * packets and let rxi_Start remove them from the transmit queue.
3439 if (call->flags & RX_CALL_TQ_BUSY) {
3440 #ifdef RX_ENABLE_LOCKS
3441 rxi_SetAcksInTransmitQueue(call);
3443 MUTEX_ENTER(&rx_refcnt_mutex);
3445 MUTEX_EXIT(&rx_refcnt_mutex);
3446 return np; /* xmitting; drop packet */
3449 rxi_ClearTransmitQueue(call, 0);
3451 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3452 rxi_ClearTransmitQueue(call, 0);
3453 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3455 if (np->header.type == RX_PACKET_TYPE_ACK) {
3456 /* now check to see if this is an ack packet acknowledging that the
3457 * server actually *lost* some hard-acked data. If this happens we
3458 * ignore this packet, as it may indicate that the server restarted in
3459 * the middle of a call. It is also possible that this is an old ack
3460 * packet. We don't abort the connection in this case, because this
3461 * *might* just be an old ack packet. The right way to detect a server
3462 * restart in the midst of a call is to notice that the server epoch
3464 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3465 * XXX unacknowledged. I think that this is off-by-one, but
3466 * XXX I don't dare change it just yet, since it will
3467 * XXX interact badly with the server-restart detection
3468 * XXX code in receiveackpacket. */
3469 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3470 if (rx_stats_active)
3471 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3472 MUTEX_EXIT(&call->lock);
3473 MUTEX_ENTER(&rx_refcnt_mutex);
3475 MUTEX_EXIT(&rx_refcnt_mutex);
3479 } /* else not a data packet */
3482 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3483 /* Set remote user defined status from packet */
3484 call->remoteStatus = np->header.userStatus;
3486 /* Note the gap between the expected next packet and the actual
3487 * packet that arrived, when the new packet has a smaller serial number
3488 * than expected. Rioses frequently reorder packets all by themselves,
3489 * so this will be quite important with very large window sizes.
3490 * Skew is checked against 0 here to avoid any dependence on the type of
3491 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3493 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3494 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3495 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3497 MUTEX_ENTER(&conn->conn_data_lock);
3498 skew = conn->lastSerial - np->header.serial;
3499 conn->lastSerial = np->header.serial;
3500 MUTEX_EXIT(&conn->conn_data_lock);
3502 struct rx_peer *peer;
3504 if (skew > peer->inPacketSkew) {
3505 dpf(("*** In skew changed from %d to %d\n",
3506 peer->inPacketSkew, skew));
3507 peer->inPacketSkew = skew;
3511 /* Now do packet type-specific processing */
3512 switch (np->header.type) {
3513 case RX_PACKET_TYPE_DATA:
3514 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3517 case RX_PACKET_TYPE_ACK:
3518 /* Respond immediately to ack packets requesting acknowledgement
3520 if (np->header.flags & RX_REQUEST_ACK) {
3522 (void)rxi_SendCallAbort(call, 0, 1, 0);
3524 (void)rxi_SendAck(call, 0, np->header.serial,
3525 RX_ACK_PING_RESPONSE, 1);
3527 np = rxi_ReceiveAckPacket(call, np, 1);
3529 case RX_PACKET_TYPE_ABORT: {
3530 /* An abort packet: reset the call, passing the error up to the user. */
3531 /* What if error is zero? */
3532 /* What if the error is -1? the application will treat it as a timeout. */
3533 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3534 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3535 rxi_CallError(call, errdata);
3536 MUTEX_EXIT(&call->lock);
3537 MUTEX_ENTER(&rx_refcnt_mutex);
3539 MUTEX_EXIT(&rx_refcnt_mutex);
3540 return np; /* xmitting; drop packet */
3542 case RX_PACKET_TYPE_BUSY: {
3543 struct clock busyTime;
3545 clock_GetTime(&busyTime);
3547 MUTEX_EXIT(&call->lock);
3549 MUTEX_ENTER(&conn->conn_call_lock);
3550 MUTEX_ENTER(&call->lock);
3551 conn->lastBusy[call->channel] = busyTime.sec;
3552 call->flags |= RX_CALL_PEER_BUSY;
3553 MUTEX_EXIT(&call->lock);
3554 MUTEX_EXIT(&conn->conn_call_lock);
3556 MUTEX_ENTER(&rx_refcnt_mutex);
3558 MUTEX_EXIT(&rx_refcnt_mutex);
3562 case RX_PACKET_TYPE_ACKALL:
3563 /* All packets acknowledged, so we can drop all packets previously
3564 * readied for sending */
3565 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3566 /* XXX Hack. We because we can't release the global rx lock when
3567 * sending packets (osi_NetSend) we drop all ack pkts while we're
3568 * traversing the tq in rxi_Start sending packets out because
3569 * packets may move to the freePacketQueue as result of being
3570 * here! So we drop these packets until we're safely out of the
3571 * traversing. Really ugly!
3572 * For fine grain RX locking, we set the acked field in the packets
3573 * and let rxi_Start remove the packets from the transmit queue.
3575 if (call->flags & RX_CALL_TQ_BUSY) {
3576 #ifdef RX_ENABLE_LOCKS
3577 rxi_SetAcksInTransmitQueue(call);
3579 #else /* RX_ENABLE_LOCKS */
3580 MUTEX_EXIT(&call->lock);
3581 MUTEX_ENTER(&rx_refcnt_mutex);
3583 MUTEX_EXIT(&rx_refcnt_mutex);
3584 return np; /* xmitting; drop packet */
3585 #endif /* RX_ENABLE_LOCKS */
3587 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3588 rxi_ClearTransmitQueue(call, 0);
3591 /* Should not reach here, unless the peer is broken: send an abort
3593 rxi_CallError(call, RX_PROTOCOL_ERROR);
3594 np = rxi_SendCallAbort(call, np, 1, 0);
3597 /* Note when this last legitimate packet was received, for keep-alive
3598 * processing. Note, we delay getting the time until now in the hope that
3599 * the packet will be delivered to the user before any get time is required
3600 * (if not, then the time won't actually be re-evaluated here). */
3601 call->lastReceiveTime = clock_Sec();
3602 /* we've received a legit packet, so the channel is not busy */
3603 call->flags &= ~RX_CALL_PEER_BUSY;
3604 MUTEX_EXIT(&call->lock);
3605 MUTEX_ENTER(&rx_refcnt_mutex);
3607 MUTEX_EXIT(&rx_refcnt_mutex);
3611 /* return true if this is an "interesting" connection from the point of view
3612 of someone trying to debug the system */
3614 rxi_IsConnInteresting(struct rx_connection *aconn)
3617 struct rx_call *tcall;
3619 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3622 for (i = 0; i < RX_MAXCALLS; i++) {
3623 tcall = aconn->call[i];
3625 if ((tcall->state == RX_STATE_PRECALL)
3626 || (tcall->state == RX_STATE_ACTIVE))
3628 if ((tcall->mode == RX_MODE_SENDING)
3629 || (tcall->mode == RX_MODE_RECEIVING))
3637 /* if this is one of the last few packets AND it wouldn't be used by the
3638 receiving call to immediately satisfy a read request, then drop it on
3639 the floor, since accepting it might prevent a lock-holding thread from
3640 making progress in its reading. If a call has been cleared while in
3641 the precall state then ignore all subsequent packets until the call
3642 is assigned to a thread. */
3645 TooLow(struct rx_packet *ap, struct rx_call *acall)
3649 MUTEX_ENTER(&rx_quota_mutex);
3650 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3651 && (acall->state == RX_STATE_PRECALL))
3652 || ((rx_nFreePackets < rxi_dataQuota + 2)
3653 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3654 && (acall->flags & RX_CALL_READER_WAIT)))) {
3657 MUTEX_EXIT(&rx_quota_mutex);
3663 * Clear the attach wait flag on a connection and proceed.
3665 * Any processing waiting for a connection to be attached should be
3666 * unblocked. We clear the flag and do any other needed tasks.
3669 * the conn to unmark waiting for attach
3671 * @pre conn's conn_data_lock must be locked before calling this function
3675 rxi_ConnClearAttachWait(struct rx_connection *conn)
3677 /* Indicate that rxi_CheckReachEvent is no longer running by
3678 * clearing the flag. Must be atomic under conn_data_lock to
3679 * avoid a new call slipping by: rxi_CheckConnReach holds
3680 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3682 conn->flags &= ~RX_CONN_ATTACHWAIT;
3683 if (conn->flags & RX_CONN_NAT_PING) {
3684 conn->flags &= ~RX_CONN_NAT_PING;
3685 rxi_ScheduleNatKeepAliveEvent(conn);
3690 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3692 struct rx_connection *conn = arg1;
3693 struct rx_call *acall = arg2;
3694 struct rx_call *call = acall;
3695 struct clock when, now;
3698 MUTEX_ENTER(&conn->conn_data_lock);
3701 rxevent_Put(conn->checkReachEvent);
3702 conn->checkReachEvent = NULL;
3705 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3707 MUTEX_ENTER(&rx_refcnt_mutex);
3709 MUTEX_EXIT(&rx_refcnt_mutex);
3711 MUTEX_EXIT(&conn->conn_data_lock);
3715 MUTEX_ENTER(&conn->conn_call_lock);
3716 MUTEX_ENTER(&conn->conn_data_lock);
3717 for (i = 0; i < RX_MAXCALLS; i++) {
3718 struct rx_call *tc = conn->call[i];
3719 if (tc && tc->state == RX_STATE_PRECALL) {
3725 rxi_ConnClearAttachWait(conn);
3726 MUTEX_EXIT(&conn->conn_data_lock);
3727 MUTEX_EXIT(&conn->conn_call_lock);
3732 MUTEX_ENTER(&call->lock);
3733 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3735 MUTEX_EXIT(&call->lock);
3737 clock_GetTime(&now);
3739 when.sec += RX_CHECKREACH_TIMEOUT;
3740 MUTEX_ENTER(&conn->conn_data_lock);
3741 if (!conn->checkReachEvent) {
3742 MUTEX_ENTER(&rx_refcnt_mutex);
3744 MUTEX_EXIT(&rx_refcnt_mutex);
3745 conn->checkReachEvent = rxevent_Post(&when, &now,
3746 rxi_CheckReachEvent, conn,
3749 MUTEX_EXIT(&conn->conn_data_lock);
3755 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3757 struct rx_service *service = conn->service;
3758 struct rx_peer *peer = conn->peer;
3759 afs_uint32 now, lastReach;
3761 if (service->checkReach == 0)
3765 MUTEX_ENTER(&peer->peer_lock);
3766 lastReach = peer->lastReachTime;
3767 MUTEX_EXIT(&peer->peer_lock);
3768 if (now - lastReach < RX_CHECKREACH_TTL)
3771 MUTEX_ENTER(&conn->conn_data_lock);
3772 if (conn->flags & RX_CONN_ATTACHWAIT) {
3773 MUTEX_EXIT(&conn->conn_data_lock);
3776 conn->flags |= RX_CONN_ATTACHWAIT;
3777 MUTEX_EXIT(&conn->conn_data_lock);
3778 if (!conn->checkReachEvent)
3779 rxi_CheckReachEvent(NULL, conn, call, 0);
3784 /* try to attach call, if authentication is complete */
3786 TryAttach(struct rx_call *acall, osi_socket socket,
3787 int *tnop, struct rx_call **newcallp,
3790 struct rx_connection *conn = acall->conn;
3792 if (conn->type == RX_SERVER_CONNECTION
3793 && acall->state == RX_STATE_PRECALL) {
3794 /* Don't attach until we have any req'd. authentication. */
3795 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3796 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3797 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3798 /* Note: this does not necessarily succeed; there
3799 * may not any proc available
3802 rxi_ChallengeOn(acall->conn);
3807 /* A data packet has been received off the interface. This packet is
3808 * appropriate to the call (the call is in the right state, etc.). This
3809 * routine can return a packet to the caller, for re-use */
3812 rxi_ReceiveDataPacket(struct rx_call *call,
3813 struct rx_packet *np, int istack,
3814 osi_socket socket, afs_uint32 host, u_short port,
3815 int *tnop, struct rx_call **newcallp)
3817 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3822 afs_uint32 serial=0, flags=0;
3824 struct rx_packet *tnp;
3825 if (rx_stats_active)
3826 rx_atomic_inc(&rx_stats.dataPacketsRead);
3829 /* If there are no packet buffers, drop this new packet, unless we can find
3830 * packet buffers from inactive calls */
3832 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3833 MUTEX_ENTER(&rx_freePktQ_lock);
3834 rxi_NeedMorePackets = TRUE;
3835 MUTEX_EXIT(&rx_freePktQ_lock);
3836 if (rx_stats_active)
3837 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3838 call->rprev = np->header.serial;
3839 rxi_calltrace(RX_TRACE_DROP, call);
3840 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3841 /* We used to clear the receive queue here, in an attempt to free
3842 * packets. However this is unsafe if the queue has received a
3843 * soft ACK for the final packet */
3844 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3846 /* we've damaged this call already, might as well do it in. */
3852 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3853 * packet is one of several packets transmitted as a single
3854 * datagram. Do not send any soft or hard acks until all packets
3855 * in a jumbogram have been processed. Send negative acks right away.
3857 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3858 /* tnp is non-null when there are more packets in the
3859 * current jumbo gram */
3866 seq = np->header.seq;
3867 serial = np->header.serial;
3868 flags = np->header.flags;
3870 /* If the call is in an error state, send an abort message */
3872 return rxi_SendCallAbort(call, np, istack, 0);
3874 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3875 * AFS 3.5 jumbogram. */
3876 if (flags & RX_JUMBO_PACKET) {
3877 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3882 if (np->header.spare != 0) {
3883 MUTEX_ENTER(&call->conn->conn_data_lock);
3884 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3885 MUTEX_EXIT(&call->conn->conn_data_lock);
3888 /* The usual case is that this is the expected next packet */
3889 if (seq == call->rnext) {
3891 /* Check to make sure it is not a duplicate of one already queued */
3892 if (queue_IsNotEmpty(&call->rq)
3893 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3894 if (rx_stats_active)
3895 rx_atomic_inc(&rx_stats.dupPacketsRead);
3896 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3897 rxevent_Cancel(&call->delayedAckEvent, call,
3898 RX_CALL_REFCOUNT_DELAY);
3899 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3905 /* It's the next packet. Stick it on the receive queue
3906 * for this call. Set newPackets to make sure we wake
3907 * the reader once all packets have been processed */
3908 #ifdef RX_TRACK_PACKETS
3909 np->flags |= RX_PKTFLAG_RQ;
3911 queue_Prepend(&call->rq, np);
3912 #ifdef RXDEBUG_PACKET
3914 #endif /* RXDEBUG_PACKET */
3916 np = NULL; /* We can't use this anymore */
3919 /* If an ack is requested then set a flag to make sure we
3920 * send an acknowledgement for this packet */
3921 if (flags & RX_REQUEST_ACK) {
3922 ackNeeded = RX_ACK_REQUESTED;
3925 /* Keep track of whether we have received the last packet */
3926 if (flags & RX_LAST_PACKET) {
3927 call->flags |= RX_CALL_HAVE_LAST;
3931 /* Check whether we have all of the packets for this call */
3932 if (call->flags & RX_CALL_HAVE_LAST) {
3933 afs_uint32 tseq; /* temporary sequence number */
3934 struct rx_packet *tp; /* Temporary packet pointer */
3935 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3937 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3938 if (tseq != tp->header.seq)
3940 if (tp->header.flags & RX_LAST_PACKET) {
3941 call->flags |= RX_CALL_RECEIVE_DONE;
3948 /* Provide asynchronous notification for those who want it
3949 * (e.g. multi rx) */
3950 if (call->arrivalProc) {
3951 (*call->arrivalProc) (call, call->arrivalProcHandle,
3952 call->arrivalProcArg);
3953 call->arrivalProc = (void (*)())0;
3956 /* Update last packet received */
3959 /* If there is no server process serving this call, grab
3960 * one, if available. We only need to do this once. If a
3961 * server thread is available, this thread becomes a server
3962 * thread and the server thread becomes a listener thread. */
3964 TryAttach(call, socket, tnop, newcallp, 0);
3967 /* This is not the expected next packet. */
3969 /* Determine whether this is a new or old packet, and if it's
3970 * a new one, whether it fits into the current receive window.
3971 * Also figure out whether the packet was delivered in sequence.
3972 * We use the prev variable to determine whether the new packet
3973 * is the successor of its immediate predecessor in the
3974 * receive queue, and the missing flag to determine whether
3975 * any of this packets predecessors are missing. */
3977 afs_uint32 prev; /* "Previous packet" sequence number */
3978 struct rx_packet *tp; /* Temporary packet pointer */
3979 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3980 int missing; /* Are any predecessors missing? */
3982 /* If the new packet's sequence number has been sent to the
3983 * application already, then this is a duplicate */
3984 if (seq < call->rnext) {
3985 if (rx_stats_active)
3986 rx_atomic_inc(&rx_stats.dupPacketsRead);
3987 rxevent_Cancel(&call->delayedAckEvent, call,
3988 RX_CALL_REFCOUNT_DELAY);
3989 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3995 /* If the sequence number is greater than what can be
3996 * accomodated by the current window, then send a negative
3997 * acknowledge and drop the packet */
3998 if ((call->rnext + call->rwind) <= seq) {
3999 rxevent_Cancel(&call->delayedAckEvent, call,
4000 RX_CALL_REFCOUNT_DELAY);
4001 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4008 /* Look for the packet in the queue of old received packets */
4009 for (prev = call->rnext - 1, missing =
4010 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4011 /*Check for duplicate packet */
4012 if (seq == tp->header.seq) {
4013 if (rx_stats_active)
4014 rx_atomic_inc(&rx_stats.dupPacketsRead);
4015 rxevent_Cancel(&call->delayedAckEvent, call,
4016 RX_CALL_REFCOUNT_DELAY);
4017 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4023 /* If we find a higher sequence packet, break out and
4024 * insert the new packet here. */
4025 if (seq < tp->header.seq)
4027 /* Check for missing packet */
4028 if (tp->header.seq != prev + 1) {
4032 prev = tp->header.seq;
4035 /* Keep track of whether we have received the last packet. */
4036 if (flags & RX_LAST_PACKET) {
4037 call->flags |= RX_CALL_HAVE_LAST;
4040 /* It's within the window: add it to the the receive queue.
4041 * tp is left by the previous loop either pointing at the
4042 * packet before which to insert the new packet, or at the
4043 * queue head if the queue is empty or the packet should be
4045 #ifdef RX_TRACK_PACKETS
4046 np->flags |= RX_PKTFLAG_RQ;
4048 #ifdef RXDEBUG_PACKET
4050 #endif /* RXDEBUG_PACKET */
4051 queue_InsertBefore(tp, np);
4055 /* Check whether we have all of the packets for this call */
4056 if ((call->flags & RX_CALL_HAVE_LAST)
4057 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4058 afs_uint32 tseq; /* temporary sequence number */
4061 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4062 if (tseq != tp->header.seq)
4064 if (tp->header.flags & RX_LAST_PACKET) {
4065 call->flags |= RX_CALL_RECEIVE_DONE;
4072 /* We need to send an ack of the packet is out of sequence,
4073 * or if an ack was requested by the peer. */
4074 if (seq != prev + 1 || missing) {
4075 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4076 } else if (flags & RX_REQUEST_ACK) {
4077 ackNeeded = RX_ACK_REQUESTED;
4080 /* Acknowledge the last packet for each call */
4081 if (flags & RX_LAST_PACKET) {
4092 * If the receiver is waiting for an iovec, fill the iovec
4093 * using the data from the receive queue */
4094 if (call->flags & RX_CALL_IOVEC_WAIT) {
4095 didHardAck = rxi_FillReadVec(call, serial);
4096 /* the call may have been aborted */
4105 /* Wakeup the reader if any */
4106 if ((call->flags & RX_CALL_READER_WAIT)
4107 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4108 || (call->iovNext >= call->iovMax)
4109 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4110 call->flags &= ~RX_CALL_READER_WAIT;
4111 #ifdef RX_ENABLE_LOCKS
4112 CV_BROADCAST(&call->cv_rq);
4114 osi_rxWakeup(&call->rq);
4120 * Send an ack when requested by the peer, or once every
4121 * rxi_SoftAckRate packets until the last packet has been
4122 * received. Always send a soft ack for the last packet in
4123 * the server's reply. */
4125 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4126 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4127 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4128 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4129 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4130 } else if (call->nSoftAcks) {
4131 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4132 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4134 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4135 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4136 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4143 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4145 struct rx_peer *peer = conn->peer;
4147 MUTEX_ENTER(&peer->peer_lock);
4148 peer->lastReachTime = clock_Sec();
4149 MUTEX_EXIT(&peer->peer_lock);
4151 MUTEX_ENTER(&conn->conn_data_lock);
4152 if (conn->flags & RX_CONN_ATTACHWAIT) {
4155 rxi_ConnClearAttachWait(conn);
4156 MUTEX_EXIT(&conn->conn_data_lock);
4158 for (i = 0; i < RX_MAXCALLS; i++) {
4159 struct rx_call *call = conn->call[i];
4162 MUTEX_ENTER(&call->lock);
4163 /* tnop can be null if newcallp is null */
4164 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4166 MUTEX_EXIT(&call->lock);
4170 MUTEX_EXIT(&conn->conn_data_lock);
4173 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4175 rx_ack_reason(int reason)
4178 case RX_ACK_REQUESTED:
4180 case RX_ACK_DUPLICATE:
4182 case RX_ACK_OUT_OF_SEQUENCE:
4184 case RX_ACK_EXCEEDS_WINDOW:
4186 case RX_ACK_NOSPACE:
4190 case RX_ACK_PING_RESPONSE:
4203 /* The real smarts of the whole thing. */
4205 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4208 struct rx_ackPacket *ap;
4210 struct rx_packet *tp;
4211 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4212 struct rx_connection *conn = call->conn;
4213 struct rx_peer *peer = conn->peer;
4214 struct clock now; /* Current time, for RTT calculations */
4218 /* because there are CM's that are bogus, sending weird values for this. */
4219 afs_uint32 skew = 0;
4224 int newAckCount = 0;
4225 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4226 int pktsize = 0; /* Set if we need to update the peer mtu */
4227 int conn_data_locked = 0;
4229 if (rx_stats_active)
4230 rx_atomic_inc(&rx_stats.ackPacketsRead);
4231 ap = (struct rx_ackPacket *)rx_DataOf(np);
4232 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4234 return np; /* truncated ack packet */
4236 /* depends on ack packet struct */
4237 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4238 first = ntohl(ap->firstPacket);
4239 prev = ntohl(ap->previousPacket);
4240 serial = ntohl(ap->serial);
4241 /* temporarily disabled -- needs to degrade over time
4242 * skew = ntohs(ap->maxSkew); */
4244 /* Ignore ack packets received out of order */
4245 if (first < call->tfirst ||
4246 (first == call->tfirst && prev < call->tprev)) {
4252 if (np->header.flags & RX_SLOW_START_OK) {
4253 call->flags |= RX_CALL_SLOW_START_OK;
4256 if (ap->reason == RX_ACK_PING_RESPONSE)
4257 rxi_UpdatePeerReach(conn, call);
4259 if (conn->lastPacketSizeSeq) {
4260 MUTEX_ENTER(&conn->conn_data_lock);
4261 conn_data_locked = 1;
4262 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4263 pktsize = conn->lastPacketSize;
4264 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4267 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4268 if (!conn_data_locked) {
4269 MUTEX_ENTER(&conn->conn_data_lock);
4270 conn_data_locked = 1;
4272 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4273 /* process mtu ping ack */
4274 pktsize = conn->lastPingSize;
4275 conn->lastPingSizeSer = conn->lastPingSize = 0;
4279 if (conn_data_locked) {
4280 MUTEX_EXIT(&conn->conn_data_lock);
4281 conn_data_locked = 0;
4285 if (rxdebug_active) {
4289 len = _snprintf(msg, sizeof(msg),
4290 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4291 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4292 ntohl(ap->serial), ntohl(ap->previousPacket),
4293 (unsigned int)np->header.seq, (unsigned int)skew,
4294 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4298 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4299 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4303 OutputDebugString(msg);
4305 #else /* AFS_NT40_ENV */
4308 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4309 ap->reason, ntohl(ap->previousPacket),
4310 (unsigned int)np->header.seq, (unsigned int)serial,
4311 (unsigned int)skew, ntohl(ap->firstPacket));
4314 for (offset = 0; offset < nAcks; offset++)
4315 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4320 #endif /* AFS_NT40_ENV */
4323 MUTEX_ENTER(&peer->peer_lock);
4326 * Start somewhere. Can't assume we can send what we can receive,
4327 * but we are clearly receiving.
4329 if (!peer->maxPacketSize)
4330 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4332 if (pktsize > peer->maxPacketSize) {
4333 peer->maxPacketSize = pktsize;
4334 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4335 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4336 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4337 rxi_ScheduleGrowMTUEvent(call, 1);
4342 /* Update the outgoing packet skew value to the latest value of
4343 * the peer's incoming packet skew value. The ack packet, of
4344 * course, could arrive out of order, but that won't affect things
4346 peer->outPacketSkew = skew;
4349 clock_GetTime(&now);
4351 /* The transmit queue splits into 4 sections.
4353 * The first section is packets which have now been acknowledged
4354 * by a window size change in the ack. These have reached the
4355 * application layer, and may be discarded. These are packets
4356 * with sequence numbers < ap->firstPacket.
4358 * The second section is packets which have sequence numbers in
4359 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4360 * contents of the packet's ack array determines whether these
4361 * packets are acknowledged or not.
4363 * The third section is packets which fall above the range
4364 * addressed in the ack packet. These have not yet been received
4367 * The four section is packets which have not yet been transmitted.
4368 * These packets will have a header.serial of 0.
4371 /* First section - implicitly acknowledged packets that can be
4375 tp = queue_First(&call->tq, rx_packet);
4376 while(!queue_IsEnd(&call->tq, tp) && tp->header.seq < first) {
4377 struct rx_packet *next;
4379 next = queue_Next(tp, rx_packet);
4380 call->tfirst = tp->header.seq + 1;
4382 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4384 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4387 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4388 /* XXX Hack. Because we have to release the global rx lock when sending
4389 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4390 * in rxi_Start sending packets out because packets may move to the
4391 * freePacketQueue as result of being here! So we drop these packets until
4392 * we're safely out of the traversing. Really ugly!
4393 * To make it even uglier, if we're using fine grain locking, we can
4394 * set the ack bits in the packets and have rxi_Start remove the packets
4395 * when it's done transmitting.
4397 if (call->flags & RX_CALL_TQ_BUSY) {
4398 #ifdef RX_ENABLE_LOCKS
4399 tp->flags |= RX_PKTFLAG_ACKED;
4400 call->flags |= RX_CALL_TQ_SOME_ACKED;
4401 #else /* RX_ENABLE_LOCKS */
4403 #endif /* RX_ENABLE_LOCKS */
4405 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4408 #ifdef RX_TRACK_PACKETS
4409 tp->flags &= ~RX_PKTFLAG_TQ;
4411 #ifdef RXDEBUG_PACKET
4413 #endif /* RXDEBUG_PACKET */
4414 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4419 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4421 /* Second section of the queue - packets for which we are receiving
4424 * Go through the explicit acks/nacks and record the results in
4425 * the waiting packets. These are packets that can't be released
4426 * yet, even with a positive acknowledge. This positive
4427 * acknowledge only means the packet has been received by the
4428 * peer, not that it will be retained long enough to be sent to
4429 * the peer's upper level. In addition, reset the transmit timers
4430 * of any missing packets (those packets that must be missing
4431 * because this packet was out of sequence) */
4433 call->nSoftAcked = 0;
4435 while (!queue_IsEnd(&call->tq, tp) && tp->header.seq < first + nAcks) {
4436 /* Set the acknowledge flag per packet based on the
4437 * information in the ack packet. An acknowlegded packet can
4438 * be downgraded when the server has discarded a packet it
4439 * soacked previously, or when an ack packet is received
4440 * out of sequence. */
4441 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4442 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4444 tp->flags |= RX_PKTFLAG_ACKED;
4445 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4452 } else /* RX_ACK_TYPE_NACK */ {
4453 tp->flags &= ~RX_PKTFLAG_ACKED;
4457 tp = queue_Next(tp, rx_packet);
4460 /* We don't need to take any action with the 3rd or 4th section in the
4461 * queue - they're not addressed by the contents of this ACK packet.
4464 /* If the window has been extended by this acknowledge packet,
4465 * then wakeup a sender waiting in alloc for window space, or try
4466 * sending packets now, if he's been sitting on packets due to
4467 * lack of window space */
4468 if (call->tnext < (call->tfirst + call->twind)) {
4469 #ifdef RX_ENABLE_LOCKS
4470 CV_SIGNAL(&call->cv_twind);
4472 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4473 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4474 osi_rxWakeup(&call->twind);
4477 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4478 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4482 /* if the ack packet has a receivelen field hanging off it,
4483 * update our state */
4484 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4487 /* If the ack packet has a "recommended" size that is less than
4488 * what I am using now, reduce my size to match */
4489 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4490 (int)sizeof(afs_int32), &tSize);
4491 tSize = (afs_uint32) ntohl(tSize);
4492 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4494 /* Get the maximum packet size to send to this peer */
4495 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4497 tSize = (afs_uint32) ntohl(tSize);
4498 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4499 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4501 /* sanity check - peer might have restarted with different params.
4502 * If peer says "send less", dammit, send less... Peer should never
4503 * be unable to accept packets of the size that prior AFS versions would
4504 * send without asking. */
4505 if (peer->maxMTU != tSize) {
4506 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4508 peer->maxMTU = tSize;
4509 peer->MTU = MIN(tSize, peer->MTU);
4510 call->MTU = MIN(call->MTU, tSize);
4513 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4516 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4517 (int)sizeof(afs_int32), &tSize);
4518 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4519 if (tSize < call->twind) { /* smaller than our send */
4520 call->twind = tSize; /* window, we must send less... */
4521 call->ssthresh = MIN(call->twind, call->ssthresh);
4522 call->conn->twind[call->channel] = call->twind;
4525 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4526 * network MTU confused with the loopback MTU. Calculate the
4527 * maximum MTU here for use in the slow start code below.
4529 /* Did peer restart with older RX version? */
4530 if (peer->maxDgramPackets > 1) {
4531 peer->maxDgramPackets = 1;
4533 } else if (np->length >=
4534 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4537 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4538 sizeof(afs_int32), &tSize);
4539 tSize = (afs_uint32) ntohl(tSize);
4541 * As of AFS 3.5 we set the send window to match the receive window.
4543 if (tSize < call->twind) {
4544 call->twind = tSize;
4545 call->conn->twind[call->channel] = call->twind;
4546 call->ssthresh = MIN(call->twind, call->ssthresh);
4547 } else if (tSize > call->twind) {
4548 call->twind = tSize;
4549 call->conn->twind[call->channel] = call->twind;
4553 * As of AFS 3.5, a jumbogram is more than one fixed size
4554 * packet transmitted in a single UDP datagram. If the remote
4555 * MTU is smaller than our local MTU then never send a datagram
4556 * larger than the natural MTU.
4559 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4560 (int)sizeof(afs_int32), &tSize);
4561 maxDgramPackets = (afs_uint32) ntohl(tSize);
4562 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4564 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4565 if (maxDgramPackets > 1) {
4566 peer->maxDgramPackets = maxDgramPackets;
4567 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4569 peer->maxDgramPackets = 1;
4570 call->MTU = peer->natMTU;
4572 } else if (peer->maxDgramPackets > 1) {
4573 /* Restarted with lower version of RX */
4574 peer->maxDgramPackets = 1;
4576 } else if (peer->maxDgramPackets > 1
4577 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4578 /* Restarted with lower version of RX */
4579 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4580 peer->natMTU = OLD_MAX_PACKET_SIZE;
4581 peer->MTU = OLD_MAX_PACKET_SIZE;
4582 peer->maxDgramPackets = 1;
4583 peer->nDgramPackets = 1;
4585 call->MTU = OLD_MAX_PACKET_SIZE;
4590 * Calculate how many datagrams were successfully received after
4591 * the first missing packet and adjust the negative ack counter
4596 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4597 if (call->nNacks < nNacked) {
4598 call->nNacks = nNacked;
4601 call->nAcks += newAckCount;
4605 /* If the packet contained new acknowledgements, rather than just
4606 * being a duplicate of one we have previously seen, then we can restart
4609 if (newAckCount > 0)
4610 rxi_rto_packet_acked(call, istack);
4612 if (call->flags & RX_CALL_FAST_RECOVER) {
4613 if (newAckCount == 0) {
4614 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4616 call->flags &= ~RX_CALL_FAST_RECOVER;
4617 call->cwind = call->nextCwind;
4618 call->nextCwind = 0;
4621 call->nCwindAcks = 0;
4622 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4623 /* Three negative acks in a row trigger congestion recovery */
4624 call->flags |= RX_CALL_FAST_RECOVER;
4625 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4627 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4628 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4629 call->nextCwind = call->ssthresh;
4632 peer->MTU = call->MTU;
4633 peer->cwind = call->nextCwind;
4634 peer->nDgramPackets = call->nDgramPackets;
4636 call->congestSeq = peer->congestSeq;
4638 /* Reset the resend times on the packets that were nacked
4639 * so we will retransmit as soon as the window permits
4642 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4644 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4645 tp->flags &= ~RX_PKTFLAG_SENT;
4647 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4652 /* If cwind is smaller than ssthresh, then increase
4653 * the window one packet for each ack we receive (exponential
4655 * If cwind is greater than or equal to ssthresh then increase
4656 * the congestion window by one packet for each cwind acks we
4657 * receive (linear growth). */
4658 if (call->cwind < call->ssthresh) {
4660 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4661 call->nCwindAcks = 0;
4663 call->nCwindAcks += newAckCount;
4664 if (call->nCwindAcks >= call->cwind) {
4665 call->nCwindAcks = 0;
4666 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4670 * If we have received several acknowledgements in a row then
4671 * it is time to increase the size of our datagrams
4673 if ((int)call->nAcks > rx_nDgramThreshold) {
4674 if (peer->maxDgramPackets > 1) {
4675 if (call->nDgramPackets < peer->maxDgramPackets) {
4676 call->nDgramPackets++;
4678 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4679 } else if (call->MTU < peer->maxMTU) {
4680 /* don't upgrade if we can't handle it */
4681 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4682 call->MTU = peer->ifMTU;
4684 call->MTU += peer->natMTU;
4685 call->MTU = MIN(call->MTU, peer->maxMTU);
4692 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4694 /* Servers need to hold the call until all response packets have
4695 * been acknowledged. Soft acks are good enough since clients
4696 * are not allowed to clear their receive queues. */
4697 if (call->state == RX_STATE_HOLD
4698 && call->tfirst + call->nSoftAcked >= call->tnext) {
4699 call->state = RX_STATE_DALLY;
4700 rxi_ClearTransmitQueue(call, 0);
4701 rxevent_Cancel(&call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4702 } else if (!queue_IsEmpty(&call->tq)) {
4703 rxi_Start(call, istack);
4708 /* Received a response to a challenge packet */
4710 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4711 struct rx_packet *np, int istack)
4715 /* Ignore the packet if we're the client */
4716 if (conn->type == RX_CLIENT_CONNECTION)
4719 /* If already authenticated, ignore the packet (it's probably a retry) */
4720 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4723 /* Otherwise, have the security object evaluate the response packet */
4724 error = RXS_CheckResponse(conn->securityObject, conn, np);
4726 /* If the response is invalid, reset the connection, sending
4727 * an abort to the peer */
4731 rxi_ConnectionError(conn, error);
4732 MUTEX_ENTER(&conn->conn_data_lock);
4733 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4734 MUTEX_EXIT(&conn->conn_data_lock);
4737 /* If the response is valid, any calls waiting to attach
4738 * servers can now do so */
4741 for (i = 0; i < RX_MAXCALLS; i++) {
4742 struct rx_call *call = conn->call[i];
4744 MUTEX_ENTER(&call->lock);
4745 if (call->state == RX_STATE_PRECALL)
4746 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4747 /* tnop can be null if newcallp is null */
4748 MUTEX_EXIT(&call->lock);
4752 /* Update the peer reachability information, just in case
4753 * some calls went into attach-wait while we were waiting
4754 * for authentication..
4756 rxi_UpdatePeerReach(conn, NULL);
4761 /* A client has received an authentication challenge: the security
4762 * object is asked to cough up a respectable response packet to send
4763 * back to the server. The server is responsible for retrying the
4764 * challenge if it fails to get a response. */
4767 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4768 struct rx_packet *np, int istack)
4772 /* Ignore the challenge if we're the server */
4773 if (conn->type == RX_SERVER_CONNECTION)
4776 /* Ignore the challenge if the connection is otherwise idle; someone's
4777 * trying to use us as an oracle. */
4778 if (!rxi_HasActiveCalls(conn))
4781 /* Send the security object the challenge packet. It is expected to fill
4782 * in the response. */
4783 error = RXS_GetResponse(conn->securityObject, conn, np);
4785 /* If the security object is unable to return a valid response, reset the
4786 * connection and send an abort to the peer. Otherwise send the response
4787 * packet to the peer connection. */
4789 rxi_ConnectionError(conn, error);
4790 MUTEX_ENTER(&conn->conn_data_lock);
4791 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4792 MUTEX_EXIT(&conn->conn_data_lock);
4794 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4795 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4801 /* Find an available server process to service the current request in
4802 * the given call structure. If one isn't available, queue up this
4803 * call so it eventually gets one */
4805 rxi_AttachServerProc(struct rx_call *call,
4806 osi_socket socket, int *tnop,
4807 struct rx_call **newcallp)
4809 struct rx_serverQueueEntry *sq;
4810 struct rx_service *service = call->conn->service;
4813 /* May already be attached */
4814 if (call->state == RX_STATE_ACTIVE)
4817 MUTEX_ENTER(&rx_serverPool_lock);
4819 haveQuota = QuotaOK(service);
4820 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4821 /* If there are no processes available to service this call,
4822 * put the call on the incoming call queue (unless it's
4823 * already on the queue).
4825 #ifdef RX_ENABLE_LOCKS
4827 ReturnToServerPool(service);
4828 #endif /* RX_ENABLE_LOCKS */
4830 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4831 call->flags |= RX_CALL_WAIT_PROC;
4832 rx_atomic_inc(&rx_nWaiting);
4833 rx_atomic_inc(&rx_nWaited);
4834 rxi_calltrace(RX_CALL_ARRIVAL, call);
4835 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4836 queue_Append(&rx_incomingCallQueue, call);
4839 sq = queue_Last(&rx_idleServerQueue, rx_serverQueueEntry);
4841 /* If hot threads are enabled, and both newcallp and sq->socketp
4842 * are non-null, then this thread will process the call, and the
4843 * idle server thread will start listening on this threads socket.
4846 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4849 *sq->socketp = socket;
4850 clock_GetTime(&call->startTime);
4851 MUTEX_ENTER(&rx_refcnt_mutex);
4852 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4853 MUTEX_EXIT(&rx_refcnt_mutex);
4857 if (call->flags & RX_CALL_WAIT_PROC) {
4858 /* Conservative: I don't think this should happen */
4859 call->flags &= ~RX_CALL_WAIT_PROC;
4860 if (queue_IsOnQueue(call)) {
4863 rx_atomic_dec(&rx_nWaiting);
4866 call->state = RX_STATE_ACTIVE;
4867 call->mode = RX_MODE_RECEIVING;
4868 #ifdef RX_KERNEL_TRACE
4870 int glockOwner = ISAFS_GLOCK();
4873 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4874 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4880 if (call->flags & RX_CALL_CLEARED) {
4881 /* send an ack now to start the packet flow up again */
4882 call->flags &= ~RX_CALL_CLEARED;
4883 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4885 #ifdef RX_ENABLE_LOCKS
4888 service->nRequestsRunning++;
4889 MUTEX_ENTER(&rx_quota_mutex);
4890 if (service->nRequestsRunning <= service->minProcs)
4893 MUTEX_EXIT(&rx_quota_mutex);
4897 MUTEX_EXIT(&rx_serverPool_lock);
4900 /* Delay the sending of an acknowledge event for a short while, while
4901 * a new call is being prepared (in the case of a client) or a reply
4902 * is being prepared (in the case of a server). Rather than sending
4903 * an ack packet, an ACKALL packet is sent. */
4905 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4907 #ifdef RX_ENABLE_LOCKS
4909 MUTEX_ENTER(&call->lock);
4910 rxevent_Put(call->delayedAckEvent);
4911 call->delayedAckEvent = NULL;
4912 MUTEX_ENTER(&rx_refcnt_mutex);
4913 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4914 MUTEX_EXIT(&rx_refcnt_mutex);
4916 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4917 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4918 call->flags |= RX_CALL_ACKALL_SENT;
4920 MUTEX_EXIT(&call->lock);
4921 #else /* RX_ENABLE_LOCKS */
4923 rxevent_Put(call->delayedAckEvent);
4924 call->delayedAckEvent = NULL;
4926 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4927 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4928 call->flags |= RX_CALL_ACKALL_SENT;
4929 #endif /* RX_ENABLE_LOCKS */
4933 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4936 struct rx_call *call = arg1;
4937 #ifdef RX_ENABLE_LOCKS
4939 MUTEX_ENTER(&call->lock);
4940 if (event == call->delayedAckEvent) {
4941 rxevent_Put(call->delayedAckEvent);
4942 call->delayedAckEvent = NULL;
4944 MUTEX_ENTER(&rx_refcnt_mutex);
4945 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4946 MUTEX_EXIT(&rx_refcnt_mutex);
4948 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4950 MUTEX_EXIT(&call->lock);
4951 #else /* RX_ENABLE_LOCKS */
4953 rxevent_Put(call->delayedAckEvent);
4954 call->delayedAckEvent = NULL;
4956 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4957 #endif /* RX_ENABLE_LOCKS */
4961 #ifdef RX_ENABLE_LOCKS
4962 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4963 * clearing them out.
4966 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4968 struct rx_packet *p, *tp;
4971 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4972 p->flags |= RX_PKTFLAG_ACKED;
4976 call->flags |= RX_CALL_TQ_CLEARME;
4977 call->flags |= RX_CALL_TQ_SOME_ACKED;
4980 rxi_rto_cancel(call);
4982 call->tfirst = call->tnext;
4983 call->nSoftAcked = 0;
4985 if (call->flags & RX_CALL_FAST_RECOVER) {
4986 call->flags &= ~RX_CALL_FAST_RECOVER;
4987 call->cwind = call->nextCwind;
4988 call->nextCwind = 0;
4991 CV_SIGNAL(&call->cv_twind);
4993 #endif /* RX_ENABLE_LOCKS */
4995 /* Clear out the transmit queue for the current call (all packets have
4996 * been received by peer) */
4998 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5000 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5001 struct rx_packet *p, *tp;
5003 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5005 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
5006 p->flags |= RX_PKTFLAG_ACKED;
5010 call->flags |= RX_CALL_TQ_CLEARME;
5011 call->flags |= RX_CALL_TQ_SOME_ACKED;
5014 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5015 #ifdef RXDEBUG_PACKET
5017 #endif /* RXDEBUG_PACKET */
5018 rxi_FreePackets(0, &call->tq);
5019 rxi_WakeUpTransmitQueue(call);
5020 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5021 call->flags &= ~RX_CALL_TQ_CLEARME;
5023 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5025 rxi_rto_cancel(call);
5026 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5027 call->nSoftAcked = 0;
5029 if (call->flags & RX_CALL_FAST_RECOVER) {
5030 call->flags &= ~RX_CALL_FAST_RECOVER;
5031 call->cwind = call->nextCwind;
5033 #ifdef RX_ENABLE_LOCKS
5034 CV_SIGNAL(&call->cv_twind);
5036 osi_rxWakeup(&call->twind);
5041 rxi_ClearReceiveQueue(struct rx_call *call)
5043 if (queue_IsNotEmpty(&call->rq)) {
5046 count = rxi_FreePackets(0, &call->rq);
5047 rx_packetReclaims += count;
5048 #ifdef RXDEBUG_PACKET
5050 if ( call->rqc != 0 )
5051 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5053 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5055 if (call->state == RX_STATE_PRECALL) {
5056 call->flags |= RX_CALL_CLEARED;
5060 /* Send an abort packet for the specified call */
5062 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5063 int istack, int force)
5066 struct clock when, now;
5071 /* Clients should never delay abort messages */
5072 if (rx_IsClientConn(call->conn))
5075 if (call->abortCode != call->error) {
5076 call->abortCode = call->error;
5077 call->abortCount = 0;
5080 if (force || rxi_callAbortThreshhold == 0
5081 || call->abortCount < rxi_callAbortThreshhold) {
5082 if (call->delayedAbortEvent) {
5083 rxevent_Cancel(&call->delayedAbortEvent, call,
5084 RX_CALL_REFCOUNT_ABORT);
5086 error = htonl(call->error);
5089 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5090 (char *)&error, sizeof(error), istack);
5091 } else if (!call->delayedAbortEvent) {
5092 clock_GetTime(&now);
5094 clock_Addmsec(&when, rxi_callAbortDelay);
5095 MUTEX_ENTER(&rx_refcnt_mutex);
5096 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5097 MUTEX_EXIT(&rx_refcnt_mutex);
5098 call->delayedAbortEvent =
5099 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5104 /* Send an abort packet for the specified connection. Packet is an
5105 * optional pointer to a packet that can be used to send the abort.
5106 * Once the number of abort messages reaches the threshhold, an
5107 * event is scheduled to send the abort. Setting the force flag
5108 * overrides sending delayed abort messages.
5110 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5111 * to send the abort packet.
5114 rxi_SendConnectionAbort(struct rx_connection *conn,
5115 struct rx_packet *packet, int istack, int force)
5118 struct clock when, now;
5123 /* Clients should never delay abort messages */
5124 if (rx_IsClientConn(conn))
5127 if (force || rxi_connAbortThreshhold == 0
5128 || conn->abortCount < rxi_connAbortThreshhold) {
5130 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
5131 error = htonl(conn->error);
5133 MUTEX_EXIT(&conn->conn_data_lock);
5135 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5136 RX_PACKET_TYPE_ABORT, (char *)&error,
5137 sizeof(error), istack);
5138 MUTEX_ENTER(&conn->conn_data_lock);
5139 } else if (!conn->delayedAbortEvent) {
5140 clock_GetTime(&now);
5142 clock_Addmsec(&when, rxi_connAbortDelay);
5143 conn->delayedAbortEvent =
5144 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
5149 /* Associate an error all of the calls owned by a connection. Called
5150 * with error non-zero. This is only for really fatal things, like
5151 * bad authentication responses. The connection itself is set in
5152 * error at this point, so that future packets received will be
5155 rxi_ConnectionError(struct rx_connection *conn,
5161 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5163 MUTEX_ENTER(&conn->conn_data_lock);
5164 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
5165 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
5166 if (conn->checkReachEvent) {
5167 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
5168 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5169 MUTEX_ENTER(&rx_refcnt_mutex);
5171 MUTEX_EXIT(&rx_refcnt_mutex);
5173 MUTEX_EXIT(&conn->conn_data_lock);
5174 for (i = 0; i < RX_MAXCALLS; i++) {
5175 struct rx_call *call = conn->call[i];
5177 MUTEX_ENTER(&call->lock);
5178 rxi_CallError(call, error);
5179 MUTEX_EXIT(&call->lock);
5182 conn->error = error;
5183 if (rx_stats_active)
5184 rx_atomic_inc(&rx_stats.fatalErrors);
5189 * Interrupt an in-progress call with the specified error and wakeup waiters.
5191 * @param[in] call The call to interrupt
5192 * @param[in] error The error code to send to the peer
5195 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5197 MUTEX_ENTER(&call->lock);
5198 rxi_CallError(call, error);
5199 rxi_SendCallAbort(call, NULL, 0, 1);
5200 MUTEX_EXIT(&call->lock);
5204 rxi_CallError(struct rx_call *call, afs_int32 error)
5207 osirx_AssertMine(&call->lock, "rxi_CallError");
5209 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5211 error = call->error;
5213 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5214 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5215 rxi_ResetCall(call, 0);
5218 rxi_ResetCall(call, 0);
5220 call->error = error;
5223 /* Reset various fields in a call structure, and wakeup waiting
5224 * processes. Some fields aren't changed: state & mode are not
5225 * touched (these must be set by the caller), and bufptr, nLeft, and
5226 * nFree are not reset, since these fields are manipulated by
5227 * unprotected macros, and may only be reset by non-interrupting code.
5231 rxi_ResetCall(struct rx_call *call, int newcall)
5234 struct rx_peer *peer;
5235 struct rx_packet *packet;
5237 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5239 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5241 /* Notify anyone who is waiting for asynchronous packet arrival */
5242 if (call->arrivalProc) {
5243 (*call->arrivalProc) (call, call->arrivalProcHandle,
5244 call->arrivalProcArg);
5245 call->arrivalProc = (void (*)())0;
5249 rxevent_Cancel(&call->growMTUEvent, call, RX_CALL_REFCOUNT_ALIVE);
5251 if (call->delayedAbortEvent) {
5252 rxevent_Cancel(&call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5253 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5255 rxi_SendCallAbort(call, packet, 0, 1);
5256 rxi_FreePacket(packet);
5261 * Update the peer with the congestion information in this call
5262 * so other calls on this connection can pick up where this call
5263 * left off. If the congestion sequence numbers don't match then
5264 * another call experienced a retransmission.
5266 peer = call->conn->peer;
5267 MUTEX_ENTER(&peer->peer_lock);
5269 if (call->congestSeq == peer->congestSeq) {
5270 peer->cwind = MAX(peer->cwind, call->cwind);
5271 peer->MTU = MAX(peer->MTU, call->MTU);
5272 peer->nDgramPackets =
5273 MAX(peer->nDgramPackets, call->nDgramPackets);
5276 call->abortCode = 0;
5277 call->abortCount = 0;
5279 if (peer->maxDgramPackets > 1) {
5280 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5282 call->MTU = peer->MTU;
5284 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5285 call->ssthresh = rx_maxSendWindow;
5286 call->nDgramPackets = peer->nDgramPackets;
5287 call->congestSeq = peer->congestSeq;
5288 call->rtt = peer->rtt;
5289 call->rtt_dev = peer->rtt_dev;
5290 clock_Zero(&call->rto);
5291 clock_Addmsec(&call->rto,
5292 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5293 MUTEX_EXIT(&peer->peer_lock);
5295 flags = call->flags;
5296 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5297 rxi_WaitforTQBusy(call);
5298 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5300 rxi_ClearTransmitQueue(call, 1);
5301 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5302 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5306 if ((flags & RX_CALL_PEER_BUSY)) {
5307 /* The call channel is still busy; resetting the call doesn't change
5309 call->flags |= RX_CALL_PEER_BUSY;
5312 rxi_ClearReceiveQueue(call);
5313 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5317 call->twind = call->conn->twind[call->channel];
5318 call->rwind = call->conn->rwind[call->channel];
5319 call->nSoftAcked = 0;
5320 call->nextCwind = 0;
5323 call->nCwindAcks = 0;
5324 call->nSoftAcks = 0;
5325 call->nHardAcks = 0;
5327 call->tfirst = call->rnext = call->tnext = 1;
5330 call->lastAcked = 0;
5331 call->localStatus = call->remoteStatus = 0;
5333 if (flags & RX_CALL_READER_WAIT) {
5334 #ifdef RX_ENABLE_LOCKS
5335 CV_BROADCAST(&call->cv_rq);
5337 osi_rxWakeup(&call->rq);
5340 if (flags & RX_CALL_WAIT_PACKETS) {
5341 MUTEX_ENTER(&rx_freePktQ_lock);
5342 rxi_PacketsUnWait(); /* XXX */
5343 MUTEX_EXIT(&rx_freePktQ_lock);
5345 #ifdef RX_ENABLE_LOCKS
5346 CV_SIGNAL(&call->cv_twind);
5348 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5349 osi_rxWakeup(&call->twind);
5352 #ifdef RX_ENABLE_LOCKS
5353 /* The following ensures that we don't mess with any queue while some
5354 * other thread might also be doing so. The call_queue_lock field is
5355 * is only modified under the call lock. If the call is in the process
5356 * of being removed from a queue, the call is not locked until the
5357 * the queue lock is dropped and only then is the call_queue_lock field
5358 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5359 * Note that any other routine which removes a call from a queue has to
5360 * obtain the queue lock before examing the queue and removing the call.
5362 if (call->call_queue_lock) {
5363 MUTEX_ENTER(call->call_queue_lock);
5364 if (queue_IsOnQueue(call)) {
5366 if (flags & RX_CALL_WAIT_PROC) {
5367 rx_atomic_dec(&rx_nWaiting);
5370 MUTEX_EXIT(call->call_queue_lock);
5371 CLEAR_CALL_QUEUE_LOCK(call);
5373 #else /* RX_ENABLE_LOCKS */
5374 if (queue_IsOnQueue(call)) {
5376 if (flags & RX_CALL_WAIT_PROC)
5377 rx_atomic_dec(&rx_nWaiting);
5379 #endif /* RX_ENABLE_LOCKS */
5381 rxi_KeepAliveOff(call);
5382 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5385 /* Send an acknowledge for the indicated packet (seq,serial) of the
5386 * indicated call, for the indicated reason (reason). This
5387 * acknowledge will specifically acknowledge receiving the packet, and
5388 * will also specify which other packets for this call have been
5389 * received. This routine returns the packet that was used to the
5390 * caller. The caller is responsible for freeing it or re-using it.
5391 * This acknowledgement also returns the highest sequence number
5392 * actually read out by the higher level to the sender; the sender
5393 * promises to keep around packets that have not been read by the
5394 * higher level yet (unless, of course, the sender decides to abort
5395 * the call altogether). Any of p, seq, serial, pflags, or reason may
5396 * be set to zero without ill effect. That is, if they are zero, they
5397 * will not convey any information.
5398 * NOW there is a trailer field, after the ack where it will safely be
5399 * ignored by mundanes, which indicates the maximum size packet this
5400 * host can swallow. */
5402 struct rx_packet *optionalPacket; use to send ack (or null)
5403 int seq; Sequence number of the packet we are acking
5404 int serial; Serial number of the packet
5405 int pflags; Flags field from packet header
5406 int reason; Reason an acknowledge was prompted
5410 rxi_SendAck(struct rx_call *call,
5411 struct rx_packet *optionalPacket, int serial, int reason,
5414 struct rx_ackPacket *ap;
5415 struct rx_packet *rqp;
5416 struct rx_packet *nxp; /* For queue_Scan */
5417 struct rx_packet *p;
5420 afs_uint32 padbytes = 0;
5421 #ifdef RX_ENABLE_TSFPQ
5422 struct rx_ts_info_t * rx_ts_info;
5426 * Open the receive window once a thread starts reading packets
5428 if (call->rnext > 1) {
5429 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5432 /* Don't attempt to grow MTU if this is a critical ping */
5433 if (reason == RX_ACK_MTU) {
5434 /* keep track of per-call attempts, if we're over max, do in small
5435 * otherwise in larger? set a size to increment by, decrease
5438 if (call->conn->peer->maxPacketSize &&
5439 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5441 padbytes = call->conn->peer->maxPacketSize+16;
5443 padbytes = call->conn->peer->maxMTU + 128;
5445 /* do always try a minimum size ping */
5446 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5448 /* subtract the ack payload */
5449 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5450 reason = RX_ACK_PING;
5453 call->nHardAcks = 0;
5454 call->nSoftAcks = 0;
5455 if (call->rnext > call->lastAcked)
5456 call->lastAcked = call->rnext;
5460 rx_computelen(p, p->length); /* reset length, you never know */
5461 } /* where that's been... */
5462 #ifdef RX_ENABLE_TSFPQ
5464 RX_TS_INFO_GET(rx_ts_info);
5465 if ((p = rx_ts_info->local_special_packet)) {
5466 rx_computelen(p, p->length);
5467 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5468 rx_ts_info->local_special_packet = p;
5469 } else { /* We won't send the ack, but don't panic. */
5470 return optionalPacket;
5474 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5475 /* We won't send the ack, but don't panic. */
5476 return optionalPacket;
5481 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5484 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5485 #ifndef RX_ENABLE_TSFPQ
5486 if (!optionalPacket)
5489 return optionalPacket;
5491 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5492 if (rx_Contiguous(p) < templ) {
5493 #ifndef RX_ENABLE_TSFPQ
5494 if (!optionalPacket)
5497 return optionalPacket;
5502 /* MTUXXX failing to send an ack is very serious. We should */
5503 /* try as hard as possible to send even a partial ack; it's */
5504 /* better than nothing. */
5505 ap = (struct rx_ackPacket *)rx_DataOf(p);
5506 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5507 ap->reason = reason;
5509 /* The skew computation used to be bogus, I think it's better now. */
5510 /* We should start paying attention to skew. XXX */
5511 ap->serial = htonl(serial);
5512 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5515 * First packet not yet forwarded to reader. When ACKALL has been
5516 * sent the peer has been told that all received packets will be
5517 * delivered to the reader. The value 'rnext' is used internally
5518 * to refer to the next packet in the receive queue that must be
5519 * delivered to the reader. From the perspective of the peer it
5520 * already has so report the last sequence number plus one if there
5521 * are packets in the receive queue awaiting processing.
5523 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5524 !queue_IsEmpty(&call->rq)) {
5525 ap->firstPacket = htonl(queue_Last(&call->rq, rx_packet)->header.seq + 1);
5527 ap->firstPacket = htonl(call->rnext);
5529 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5531 /* No fear of running out of ack packet here because there can only be at most
5532 * one window full of unacknowledged packets. The window size must be constrained
5533 * to be less than the maximum ack size, of course. Also, an ack should always
5534 * fit into a single packet -- it should not ever be fragmented. */
5535 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5536 if (!rqp || !call->rq.next
5537 || (rqp->header.seq > (call->rnext + call->rwind))) {
5538 #ifndef RX_ENABLE_TSFPQ
5539 if (!optionalPacket)
5542 rxi_CallError(call, RX_CALL_DEAD);
5543 return optionalPacket;
5546 while (rqp->header.seq > call->rnext + offset)
5547 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5548 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5550 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5551 #ifndef RX_ENABLE_TSFPQ
5552 if (!optionalPacket)
5555 rxi_CallError(call, RX_CALL_DEAD);
5556 return optionalPacket;
5562 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5564 /* these are new for AFS 3.3 */
5565 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5566 templ = htonl(templ);
5567 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5568 templ = htonl(call->conn->peer->ifMTU);
5569 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5570 sizeof(afs_int32), &templ);
5572 /* new for AFS 3.4 */
5573 templ = htonl(call->rwind);
5574 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5575 sizeof(afs_int32), &templ);
5577 /* new for AFS 3.5 */
5578 templ = htonl(call->conn->peer->ifDgramPackets);
5579 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5580 sizeof(afs_int32), &templ);
5582 p->header.serviceId = call->conn->serviceId;
5583 p->header.cid = (call->conn->cid | call->channel);
5584 p->header.callNumber = *call->callNumber;
5586 p->header.securityIndex = call->conn->securityIndex;
5587 p->header.epoch = call->conn->epoch;
5588 p->header.type = RX_PACKET_TYPE_ACK;
5589 p->header.flags = RX_SLOW_START_OK;
5590 if (reason == RX_ACK_PING) {
5591 p->header.flags |= RX_REQUEST_ACK;
5593 p->length = padbytes +
5594 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5597 /* not fast but we can potentially use this if truncated
5598 * fragments are delivered to figure out the mtu.
5600 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5601 sizeof(afs_int32), sizeof(afs_int32),
5605 if (call->conn->type == RX_CLIENT_CONNECTION)
5606 p->header.flags |= RX_CLIENT_INITIATED;
5610 if (rxdebug_active) {
5614 len = _snprintf(msg, sizeof(msg),
5615 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5616 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5617 ntohl(ap->serial), ntohl(ap->previousPacket),
5618 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5619 ap->nAcks, ntohs(ap->bufferSpace) );
5623 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5624 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5628 OutputDebugString(msg);
5630 #else /* AFS_NT40_ENV */
5632 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5633 ap->reason, ntohl(ap->previousPacket),
5634 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5636 for (offset = 0; offset < ap->nAcks; offset++)
5637 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5642 #endif /* AFS_NT40_ENV */
5645 int i, nbytes = p->length;
5647 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5648 if (nbytes <= p->wirevec[i].iov_len) {
5651 savelen = p->wirevec[i].iov_len;
5653 p->wirevec[i].iov_len = nbytes;
5655 rxi_Send(call, p, istack);
5656 p->wirevec[i].iov_len = savelen;
5660 nbytes -= p->wirevec[i].iov_len;
5663 if (rx_stats_active)
5664 rx_atomic_inc(&rx_stats.ackPacketsSent);
5665 #ifndef RX_ENABLE_TSFPQ
5666 if (!optionalPacket)
5669 return optionalPacket; /* Return packet for re-use by caller */
5673 struct rx_packet **list;
5678 /* Send all of the packets in the list in single datagram */
5680 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5681 int istack, int moreFlag)
5687 struct rx_connection *conn = call->conn;
5688 struct rx_peer *peer = conn->peer;
5690 MUTEX_ENTER(&peer->peer_lock);
5691 peer->nSent += xmit->len;
5692 if (xmit->resending)
5693 peer->reSends += xmit->len;
5694 MUTEX_EXIT(&peer->peer_lock);
5696 if (rx_stats_active) {
5697 if (xmit->resending)
5698 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5700 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5703 clock_GetTime(&now);
5705 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5709 /* Set the packet flags and schedule the resend events */
5710 /* Only request an ack for the last packet in the list */
5711 for (i = 0; i < xmit->len; i++) {
5712 struct rx_packet *packet = xmit->list[i];
5714 /* Record the time sent */
5715 packet->timeSent = now;
5716 packet->flags |= RX_PKTFLAG_SENT;
5718 /* Ask for an ack on retransmitted packets, on every other packet
5719 * if the peer doesn't support slow start. Ask for an ack on every
5720 * packet until the congestion window reaches the ack rate. */
5721 if (packet->header.serial) {
5724 packet->firstSent = now;
5725 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5726 || (!(call->flags & RX_CALL_SLOW_START_OK)
5727 && (packet->header.seq & 1)))) {
5732 /* Tag this packet as not being the last in this group,
5733 * for the receiver's benefit */
5734 if (i < xmit->len - 1 || moreFlag) {
5735 packet->header.flags |= RX_MORE_PACKETS;
5740 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5743 /* Since we're about to send a data packet to the peer, it's
5744 * safe to nuke any scheduled end-of-packets ack */
5745 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5747 MUTEX_EXIT(&call->lock);
5748 MUTEX_ENTER(&rx_refcnt_mutex);
5749 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5750 MUTEX_EXIT(&rx_refcnt_mutex);
5751 if (xmit->len > 1) {
5752 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5754 rxi_SendPacket(call, conn, xmit->list[0], istack);
5756 MUTEX_ENTER(&call->lock);
5757 MUTEX_ENTER(&rx_refcnt_mutex);
5758 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5759 MUTEX_EXIT(&rx_refcnt_mutex);
5761 /* Tell the RTO calculation engine that we have sent a packet, and
5762 * if it was the last one */
5763 rxi_rto_packet_sent(call, lastPacket, istack);
5765 /* Update last send time for this call (for keep-alive
5766 * processing), and for the connection (so that we can discover
5767 * idle connections) */
5768 conn->lastSendTime = call->lastSendTime = clock_Sec();
5769 /* Let a set of retransmits trigger an idle timeout */
5770 if (!xmit->resending)
5771 call->lastSendData = call->lastSendTime;
5774 /* When sending packets we need to follow these rules:
5775 * 1. Never send more than maxDgramPackets in a jumbogram.
5776 * 2. Never send a packet with more than two iovecs in a jumbogram.
5777 * 3. Never send a retransmitted packet in a jumbogram.
5778 * 4. Never send more than cwind/4 packets in a jumbogram
5779 * We always keep the last list we should have sent so we
5780 * can set the RX_MORE_PACKETS flags correctly.
5784 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5789 struct xmitlist working;
5790 struct xmitlist last;
5792 struct rx_peer *peer = call->conn->peer;
5793 int morePackets = 0;
5795 memset(&last, 0, sizeof(struct xmitlist));
5796 working.list = &list[0];
5798 working.resending = 0;
5800 recovery = call->flags & RX_CALL_FAST_RECOVER;
5802 for (i = 0; i < len; i++) {
5803 /* Does the current packet force us to flush the current list? */
5805 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5806 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5808 /* This sends the 'last' list and then rolls the current working
5809 * set into the 'last' one, and resets the working set */
5812 rxi_SendList(call, &last, istack, 1);
5813 /* If the call enters an error state stop sending, or if
5814 * we entered congestion recovery mode, stop sending */
5816 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5821 working.resending = 0;
5822 working.list = &list[i];
5824 /* Add the current packet to the list if it hasn't been acked.
5825 * Otherwise adjust the list pointer to skip the current packet. */
5826 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5829 if (list[i]->header.serial)
5830 working.resending = 1;
5832 /* Do we need to flush the list? */
5833 if (working.len >= (int)peer->maxDgramPackets
5834 || working.len >= (int)call->nDgramPackets
5835 || working.len >= (int)call->cwind
5836 || list[i]->header.serial
5837 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5839 rxi_SendList(call, &last, istack, 1);
5840 /* If the call enters an error state stop sending, or if
5841 * we entered congestion recovery mode, stop sending */
5843 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5848 working.resending = 0;
5849 working.list = &list[i + 1];
5852 if (working.len != 0) {
5853 osi_Panic("rxi_SendList error");
5855 working.list = &list[i + 1];
5859 /* Send the whole list when the call is in receive mode, when
5860 * the call is in eof mode, when we are in fast recovery mode,
5861 * and when we have the last packet */
5862 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5863 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5864 || (call->flags & RX_CALL_FAST_RECOVER)) {
5865 /* Check for the case where the current list contains
5866 * an acked packet. Since we always send retransmissions
5867 * in a separate packet, we only need to check the first
5868 * packet in the list */
5869 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5873 rxi_SendList(call, &last, istack, morePackets);
5874 /* If the call enters an error state stop sending, or if
5875 * we entered congestion recovery mode, stop sending */
5877 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5881 rxi_SendList(call, &working, istack, 0);
5883 } else if (last.len > 0) {
5884 rxi_SendList(call, &last, istack, 0);
5885 /* Packets which are in 'working' are not sent by this call */
5890 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5892 struct rx_call *call = arg0;
5893 struct rx_peer *peer;
5894 struct rx_packet *p, *nxp;
5895 struct clock maxTimeout = { 60, 0 };
5897 MUTEX_ENTER(&call->lock);
5899 peer = call->conn->peer;
5901 /* Make sure that the event pointer is removed from the call
5902 * structure, since there is no longer a per-call retransmission
5904 if (event == call->resendEvent) {
5905 MUTEX_ENTER(&rx_refcnt_mutex);
5906 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5907 MUTEX_EXIT(&rx_refcnt_mutex);
5908 rxevent_Put(call->resendEvent);
5909 call->resendEvent = NULL;
5912 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5913 rxi_CheckBusy(call);
5916 if (queue_IsEmpty(&call->tq)) {
5917 /* Nothing to do. This means that we've been raced, and that an
5918 * ACK has come in between when we were triggered, and when we
5919 * actually got to run. */
5923 /* We're in loss recovery */
5924 call->flags |= RX_CALL_FAST_RECOVER;
5926 /* Mark all of the pending packets in the queue as being lost */
5927 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5928 if (!(p->flags & RX_PKTFLAG_ACKED))
5929 p->flags &= ~RX_PKTFLAG_SENT;
5932 /* We're resending, so we double the timeout of the call. This will be
5933 * dropped back down by the first successful ACK that we receive.
5935 * We apply a maximum value here of 60 seconds
5937 clock_Add(&call->rto, &call->rto);
5938 if (clock_Gt(&call->rto, &maxTimeout))
5939 call->rto = maxTimeout;
5941 /* Packet loss is most likely due to congestion, so drop our window size
5942 * and start again from the beginning */
5943 if (peer->maxDgramPackets >1) {
5944 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5945 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5947 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5948 call->nDgramPackets = 1;
5950 call->nextCwind = 1;
5953 MUTEX_ENTER(&peer->peer_lock);
5954 peer->MTU = call->MTU;
5955 peer->cwind = call->cwind;
5956 peer->nDgramPackets = 1;
5958 call->congestSeq = peer->congestSeq;
5959 MUTEX_EXIT(&peer->peer_lock);
5961 rxi_Start(call, istack);
5964 MUTEX_EXIT(&call->lock);
5967 /* This routine is called when new packets are readied for
5968 * transmission and when retransmission may be necessary, or when the
5969 * transmission window or burst count are favourable. This should be
5970 * better optimized for new packets, the usual case, now that we've
5971 * got rid of queues of send packets. XXXXXXXXXXX */
5973 rxi_Start(struct rx_call *call, int istack)
5976 struct rx_packet *p;
5977 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5982 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5983 if (rx_stats_active)
5984 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5989 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5991 /* Send (or resend) any packets that need it, subject to
5992 * window restrictions and congestion burst control
5993 * restrictions. Ask for an ack on the last packet sent in
5994 * this burst. For now, we're relying upon the window being
5995 * considerably bigger than the largest number of packets that
5996 * are typically sent at once by one initial call to
5997 * rxi_Start. This is probably bogus (perhaps we should ask
5998 * for an ack when we're half way through the current
5999 * window?). Also, for non file transfer applications, this
6000 * may end up asking for an ack for every packet. Bogus. XXXX
6003 * But check whether we're here recursively, and let the other guy
6006 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6007 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6008 call->flags |= RX_CALL_TQ_BUSY;
6010 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6012 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6013 call->flags &= ~RX_CALL_NEED_START;
6014 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6016 maxXmitPackets = MIN(call->twind, call->cwind);
6017 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
6018 #ifdef RX_TRACK_PACKETS
6019 if ((p->flags & RX_PKTFLAG_FREE)
6020 || (!queue_IsEnd(&call->tq, nxp)
6021 && (nxp->flags & RX_PKTFLAG_FREE))
6022 || (p == (struct rx_packet *)&rx_freePacketQueue)
6023 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
6024 osi_Panic("rxi_Start: xmit queue clobbered");
6027 if (p->flags & RX_PKTFLAG_ACKED) {
6028 /* Since we may block, don't trust this */
6029 if (rx_stats_active)
6030 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6031 continue; /* Ignore this packet if it has been acknowledged */
6034 /* Turn off all flags except these ones, which are the same
6035 * on each transmission */
6036 p->header.flags &= RX_PRESET_FLAGS;
6038 if (p->header.seq >=
6039 call->tfirst + MIN((int)call->twind,
6040 (int)(call->nSoftAcked +
6042 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6043 /* Note: if we're waiting for more window space, we can
6044 * still send retransmits; hence we don't return here, but
6045 * break out to schedule a retransmit event */
6046 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6047 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6052 /* Transmit the packet if it needs to be sent. */
6053 if (!(p->flags & RX_PKTFLAG_SENT)) {
6054 if (nXmitPackets == maxXmitPackets) {
6055 rxi_SendXmitList(call, call->xmitList,
6056 nXmitPackets, istack);
6059 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6060 *(call->callNumber), p));
6061 call->xmitList[nXmitPackets++] = p;
6065 /* xmitList now hold pointers to all of the packets that are
6066 * ready to send. Now we loop to send the packets */
6067 if (nXmitPackets > 0) {
6068 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6072 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6074 /* We went into the error state while sending packets. Now is
6075 * the time to reset the call. This will also inform the using
6076 * process that the call is in an error state.
6078 if (rx_stats_active)
6079 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6080 call->flags &= ~RX_CALL_TQ_BUSY;
6081 rxi_WakeUpTransmitQueue(call);
6082 rxi_CallError(call, call->error);
6085 #ifdef RX_ENABLE_LOCKS
6086 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6088 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6089 /* Some packets have received acks. If they all have, we can clear
6090 * the transmit queue.
6093 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
6094 if (p->header.seq < call->tfirst
6095 && (p->flags & RX_PKTFLAG_ACKED)) {
6097 #ifdef RX_TRACK_PACKETS
6098 p->flags &= ~RX_PKTFLAG_TQ;
6100 #ifdef RXDEBUG_PACKET
6108 call->flags |= RX_CALL_TQ_CLEARME;
6110 #endif /* RX_ENABLE_LOCKS */
6111 if (call->flags & RX_CALL_TQ_CLEARME)
6112 rxi_ClearTransmitQueue(call, 1);
6113 } while (call->flags & RX_CALL_NEED_START);
6115 * TQ references no longer protected by this flag; they must remain
6116 * protected by the global lock.
6118 call->flags &= ~RX_CALL_TQ_BUSY;
6119 rxi_WakeUpTransmitQueue(call);
6121 call->flags |= RX_CALL_NEED_START;
6123 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6125 rxi_rto_cancel(call);
6129 /* Also adjusts the keep alive parameters for the call, to reflect
6130 * that we have just sent a packet (so keep alives aren't sent
6133 rxi_Send(struct rx_call *call, struct rx_packet *p,
6136 struct rx_connection *conn = call->conn;
6138 /* Stamp each packet with the user supplied status */
6139 p->header.userStatus = call->localStatus;
6141 /* Allow the security object controlling this call's security to
6142 * make any last-minute changes to the packet */
6143 RXS_SendPacket(conn->securityObject, call, p);
6145 /* Since we're about to send SOME sort of packet to the peer, it's
6146 * safe to nuke any scheduled end-of-packets ack */
6147 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6149 /* Actually send the packet, filling in more connection-specific fields */
6150 MUTEX_EXIT(&call->lock);
6151 MUTEX_ENTER(&rx_refcnt_mutex);
6152 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6153 MUTEX_EXIT(&rx_refcnt_mutex);
6154 rxi_SendPacket(call, conn, p, istack);
6155 MUTEX_ENTER(&rx_refcnt_mutex);
6156 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6157 MUTEX_EXIT(&rx_refcnt_mutex);
6158 MUTEX_ENTER(&call->lock);
6160 /* Update last send time for this call (for keep-alive
6161 * processing), and for the connection (so that we can discover
6162 * idle connections) */
6163 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6164 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6165 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6167 conn->lastSendTime = call->lastSendTime = clock_Sec();
6168 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6169 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6170 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6171 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6172 RX_ACK_PING_RESPONSE)))
6173 call->lastSendData = call->lastSendTime;
6177 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6178 * that things are fine. Also called periodically to guarantee that nothing
6179 * falls through the cracks (e.g. (error + dally) connections have keepalive
6180 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6182 * haveCTLock Set if calling from rxi_ReapConnections
6184 #ifdef RX_ENABLE_LOCKS
6186 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6187 #else /* RX_ENABLE_LOCKS */
6189 rxi_CheckCall(struct rx_call *call)
6190 #endif /* RX_ENABLE_LOCKS */
6192 struct rx_connection *conn = call->conn;
6194 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6195 afs_uint32 fudgeFactor;
6199 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6200 if (call->flags & RX_CALL_TQ_BUSY) {
6201 /* Call is active and will be reset by rxi_Start if it's
6202 * in an error state.
6207 /* RTT + 8*MDEV, rounded up to the next second. */
6208 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6209 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6211 deadTime = conn->secondsUntilDead + fudgeFactor;
6213 /* These are computed to the second (+- 1 second). But that's
6214 * good enough for these values, which should be a significant
6215 * number of seconds. */
6216 if (now > (call->lastReceiveTime + deadTime)) {
6217 if (call->state == RX_STATE_ACTIVE) {
6219 #if defined(KERNEL) && defined(AFS_SUN5_ENV)
6221 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6222 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6223 ip_stack_t *ipst = ns->netstack_ip;
6225 ire = ire_cache_lookup(conn->peer->host
6226 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6228 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6230 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6237 if (ire && ire->ire_max_frag > 0)
6238 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6240 #if defined(GLOBAL_NETSTACKID)
6244 #endif /* ADAPT_PMTU */
6245 cerror = RX_CALL_DEAD;
6248 #ifdef RX_ENABLE_LOCKS
6249 /* Cancel pending events */
6250 rxevent_Cancel(&call->delayedAckEvent, call,
6251 RX_CALL_REFCOUNT_DELAY);
6252 rxi_rto_cancel(call);
6253 rxevent_Cancel(&call->keepAliveEvent, call,
6254 RX_CALL_REFCOUNT_ALIVE);
6255 rxevent_Cancel(&call->growMTUEvent, call,
6256 RX_CALL_REFCOUNT_ALIVE);
6257 MUTEX_ENTER(&rx_refcnt_mutex);
6258 if (call->refCount == 0) {
6259 rxi_FreeCall(call, haveCTLock);
6260 MUTEX_EXIT(&rx_refcnt_mutex);
6263 MUTEX_EXIT(&rx_refcnt_mutex);
6265 #else /* RX_ENABLE_LOCKS */
6266 rxi_FreeCall(call, 0);
6268 #endif /* RX_ENABLE_LOCKS */
6270 /* Non-active calls are destroyed if they are not responding
6271 * to pings; active calls are simply flagged in error, so the
6272 * attached process can die reasonably gracefully. */
6275 if (conn->idleDeadTime) {
6276 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6279 /* see if we have a non-activity timeout */
6280 if (call->startWait && idleDeadTime
6281 && ((call->startWait + idleDeadTime) < now) &&
6282 (call->flags & RX_CALL_READER_WAIT)) {
6283 if (call->state == RX_STATE_ACTIVE) {
6284 cerror = RX_CALL_TIMEOUT;
6288 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6289 && ((call->lastSendData + idleDeadTime) < now)) {
6290 if (call->state == RX_STATE_ACTIVE) {
6291 cerror = conn->idleDeadErr;
6296 if (conn->hardDeadTime) {
6297 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6300 /* see if we have a hard timeout */
6302 && (now > (hardDeadTime + call->startTime.sec))) {
6303 if (call->state == RX_STATE_ACTIVE)
6304 rxi_CallError(call, RX_CALL_TIMEOUT);
6309 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6310 && call->lastReceiveTime) {
6311 int oldMTU = conn->peer->ifMTU;
6313 /* if we thought we could send more, perhaps things got worse */
6314 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6315 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6316 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6317 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6319 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6321 /* minimum capped in SetPeerMtu */
6322 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6325 conn->lastPacketSize = 0;
6327 /* needed so ResetCall doesn't clobber us. */
6328 call->MTU = conn->peer->ifMTU;
6330 /* if we never succeeded, let the error pass out as-is */
6331 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6332 cerror = conn->msgsizeRetryErr;
6335 rxi_CallError(call, cerror);
6340 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6341 void *dummy, int dummy2)
6343 struct rx_connection *conn = arg1;
6344 struct rx_header theader;
6345 char tbuffer[1 + sizeof(struct rx_header)];
6346 struct sockaddr_in taddr;
6349 struct iovec tmpiov[2];
6352 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6355 tp = &tbuffer[sizeof(struct rx_header)];
6356 taddr.sin_family = AF_INET;
6357 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6358 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6359 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6360 taddr.sin_len = sizeof(struct sockaddr_in);
6362 memset(&theader, 0, sizeof(theader));
6363 theader.epoch = htonl(999);
6365 theader.callNumber = 0;
6368 theader.type = RX_PACKET_TYPE_VERSION;
6369 theader.flags = RX_LAST_PACKET;
6370 theader.serviceId = 0;
6372 memcpy(tbuffer, &theader, sizeof(theader));
6373 memcpy(tp, &a, sizeof(a));
6374 tmpiov[0].iov_base = tbuffer;
6375 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6377 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6379 MUTEX_ENTER(&conn->conn_data_lock);
6380 MUTEX_ENTER(&rx_refcnt_mutex);
6381 /* Only reschedule ourselves if the connection would not be destroyed */
6382 if (conn->refCount <= 1) {
6383 rxevent_Put(conn->natKeepAliveEvent);
6384 conn->natKeepAliveEvent = NULL;
6385 MUTEX_EXIT(&rx_refcnt_mutex);
6386 MUTEX_EXIT(&conn->conn_data_lock);
6387 rx_DestroyConnection(conn); /* drop the reference for this */
6389 conn->refCount--; /* drop the reference for this */
6390 MUTEX_EXIT(&rx_refcnt_mutex);
6391 rxevent_Put(conn->natKeepAliveEvent);
6392 conn->natKeepAliveEvent = NULL;
6393 rxi_ScheduleNatKeepAliveEvent(conn);
6394 MUTEX_EXIT(&conn->conn_data_lock);
6399 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6401 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6402 struct clock when, now;
6403 clock_GetTime(&now);
6405 when.sec += conn->secondsUntilNatPing;
6406 MUTEX_ENTER(&rx_refcnt_mutex);
6407 conn->refCount++; /* hold a reference for this */
6408 MUTEX_EXIT(&rx_refcnt_mutex);
6409 conn->natKeepAliveEvent =
6410 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6415 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6417 MUTEX_ENTER(&conn->conn_data_lock);
6418 conn->secondsUntilNatPing = seconds;
6420 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6421 rxi_ScheduleNatKeepAliveEvent(conn);
6423 conn->flags |= RX_CONN_NAT_PING;
6425 MUTEX_EXIT(&conn->conn_data_lock);
6429 rxi_NatKeepAliveOn(struct rx_connection *conn)
6431 MUTEX_ENTER(&conn->conn_data_lock);
6432 /* if it's already attached */
6433 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6434 rxi_ScheduleNatKeepAliveEvent(conn);
6436 conn->flags |= RX_CONN_NAT_PING;
6437 MUTEX_EXIT(&conn->conn_data_lock);
6440 /* When a call is in progress, this routine is called occasionally to
6441 * make sure that some traffic has arrived (or been sent to) the peer.
6442 * If nothing has arrived in a reasonable amount of time, the call is
6443 * declared dead; if nothing has been sent for a while, we send a
6444 * keep-alive packet (if we're actually trying to keep the call alive)
6447 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6450 struct rx_call *call = arg1;
6451 struct rx_connection *conn;
6454 MUTEX_ENTER(&rx_refcnt_mutex);
6455 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6456 MUTEX_EXIT(&rx_refcnt_mutex);
6457 MUTEX_ENTER(&call->lock);
6459 if (event == call->keepAliveEvent) {
6460 rxevent_Put(call->keepAliveEvent);
6461 call->keepAliveEvent = NULL;
6466 #ifdef RX_ENABLE_LOCKS
6467 if (rxi_CheckCall(call, 0)) {
6468 MUTEX_EXIT(&call->lock);
6471 #else /* RX_ENABLE_LOCKS */
6472 if (rxi_CheckCall(call))
6474 #endif /* RX_ENABLE_LOCKS */
6476 /* Don't try to keep alive dallying calls */
6477 if (call->state == RX_STATE_DALLY) {
6478 MUTEX_EXIT(&call->lock);
6483 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6484 /* Don't try to send keepalives if there is unacknowledged data */
6485 /* the rexmit code should be good enough, this little hack
6486 * doesn't quite work XXX */
6487 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6489 rxi_ScheduleKeepAliveEvent(call);
6490 MUTEX_EXIT(&call->lock);
6493 /* Does what's on the nameplate. */
6495 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6497 struct rx_call *call = arg1;
6498 struct rx_connection *conn;
6500 MUTEX_ENTER(&rx_refcnt_mutex);
6501 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6502 MUTEX_EXIT(&rx_refcnt_mutex);
6503 MUTEX_ENTER(&call->lock);
6505 if (event == call->growMTUEvent) {
6506 rxevent_Put(call->growMTUEvent);
6507 call->growMTUEvent = NULL;
6510 #ifdef RX_ENABLE_LOCKS
6511 if (rxi_CheckCall(call, 0)) {
6512 MUTEX_EXIT(&call->lock);
6515 #else /* RX_ENABLE_LOCKS */
6516 if (rxi_CheckCall(call))
6518 #endif /* RX_ENABLE_LOCKS */
6520 /* Don't bother with dallying calls */
6521 if (call->state == RX_STATE_DALLY) {
6522 MUTEX_EXIT(&call->lock);
6529 * keep being scheduled, just don't do anything if we're at peak,
6530 * or we're not set up to be properly handled (idle timeout required)
6532 if ((conn->peer->maxPacketSize != 0) &&
6533 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6534 (conn->idleDeadErr))
6535 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6536 rxi_ScheduleGrowMTUEvent(call, 0);
6537 MUTEX_EXIT(&call->lock);
6541 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6543 if (!call->keepAliveEvent) {
6544 struct clock when, now;
6545 clock_GetTime(&now);
6547 when.sec += call->conn->secondsUntilPing;
6548 MUTEX_ENTER(&rx_refcnt_mutex);
6549 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6550 MUTEX_EXIT(&rx_refcnt_mutex);
6551 call->keepAliveEvent =
6552 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6557 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6559 if (!call->growMTUEvent) {
6560 struct clock when, now;
6562 clock_GetTime(&now);
6565 if (call->conn->secondsUntilPing)
6566 secs = (6*call->conn->secondsUntilPing)-1;
6568 if (call->conn->secondsUntilDead)
6569 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6573 MUTEX_ENTER(&rx_refcnt_mutex);
6574 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6575 MUTEX_EXIT(&rx_refcnt_mutex);
6576 call->growMTUEvent =
6577 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6581 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6583 rxi_KeepAliveOn(struct rx_call *call)
6585 /* Pretend last packet received was received now--i.e. if another
6586 * packet isn't received within the keep alive time, then the call
6587 * will die; Initialize last send time to the current time--even
6588 * if a packet hasn't been sent yet. This will guarantee that a
6589 * keep-alive is sent within the ping time */
6590 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6591 rxi_ScheduleKeepAliveEvent(call);
6595 rxi_GrowMTUOn(struct rx_call *call)
6597 struct rx_connection *conn = call->conn;
6598 MUTEX_ENTER(&conn->conn_data_lock);
6599 conn->lastPingSizeSer = conn->lastPingSize = 0;
6600 MUTEX_EXIT(&conn->conn_data_lock);
6601 rxi_ScheduleGrowMTUEvent(call, 1);
6604 /* This routine is called to send connection abort messages
6605 * that have been delayed to throttle looping clients. */
6607 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6610 struct rx_connection *conn = arg1;
6613 struct rx_packet *packet;
6615 MUTEX_ENTER(&conn->conn_data_lock);
6616 rxevent_Put(conn->delayedAbortEvent);
6617 conn->delayedAbortEvent = NULL;
6618 error = htonl(conn->error);
6620 MUTEX_EXIT(&conn->conn_data_lock);
6621 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6624 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6625 RX_PACKET_TYPE_ABORT, (char *)&error,
6627 rxi_FreePacket(packet);
6631 /* This routine is called to send call abort messages
6632 * that have been delayed to throttle looping clients. */
6634 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6637 struct rx_call *call = arg1;
6640 struct rx_packet *packet;
6642 MUTEX_ENTER(&call->lock);
6643 rxevent_Put(call->delayedAbortEvent);
6644 call->delayedAbortEvent = NULL;
6645 error = htonl(call->error);
6647 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6650 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6651 (char *)&error, sizeof(error), 0);
6652 rxi_FreePacket(packet);
6654 MUTEX_EXIT(&call->lock);
6655 MUTEX_ENTER(&rx_refcnt_mutex);
6656 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6657 MUTEX_EXIT(&rx_refcnt_mutex);
6660 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6661 * seconds) to ask the client to authenticate itself. The routine
6662 * issues a challenge to the client, which is obtained from the
6663 * security object associated with the connection */
6665 rxi_ChallengeEvent(struct rxevent *event,
6666 void *arg0, void *arg1, int tries)
6668 struct rx_connection *conn = arg0;
6671 rxevent_Put(conn->challengeEvent);
6672 conn->challengeEvent = NULL;
6675 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6676 struct rx_packet *packet;
6677 struct clock when, now;
6680 /* We've failed to authenticate for too long.
6681 * Reset any calls waiting for authentication;
6682 * they are all in RX_STATE_PRECALL.
6686 MUTEX_ENTER(&conn->conn_call_lock);
6687 for (i = 0; i < RX_MAXCALLS; i++) {
6688 struct rx_call *call = conn->call[i];
6690 MUTEX_ENTER(&call->lock);
6691 if (call->state == RX_STATE_PRECALL) {
6692 rxi_CallError(call, RX_CALL_DEAD);
6693 rxi_SendCallAbort(call, NULL, 0, 0);
6695 MUTEX_EXIT(&call->lock);
6698 MUTEX_EXIT(&conn->conn_call_lock);
6702 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6704 /* If there's no packet available, do this later. */
6705 RXS_GetChallenge(conn->securityObject, conn, packet);
6706 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6707 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6708 rxi_FreePacket(packet);
6710 clock_GetTime(&now);
6712 when.sec += RX_CHALLENGE_TIMEOUT;
6713 conn->challengeEvent =
6714 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6719 /* Call this routine to start requesting the client to authenticate
6720 * itself. This will continue until authentication is established,
6721 * the call times out, or an invalid response is returned. The
6722 * security object associated with the connection is asked to create
6723 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6724 * defined earlier. */
6726 rxi_ChallengeOn(struct rx_connection *conn)
6728 if (!conn->challengeEvent) {
6729 RXS_CreateChallenge(conn->securityObject, conn);
6730 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6735 /* rxi_ComputeRoundTripTime is called with peer locked. */
6736 /* peer may be null */
6738 rxi_ComputeRoundTripTime(struct rx_packet *p,
6739 struct rx_ackPacket *ack,
6740 struct rx_call *call,
6741 struct rx_peer *peer,
6744 struct clock thisRtt, *sentp;
6748 /* If the ACK is delayed, then do nothing */
6749 if (ack->reason == RX_ACK_DELAY)
6752 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6753 * their RTT multiple times, so only include the RTT of the last packet
6755 if (p->flags & RX_JUMBO_PACKET)
6758 /* Use the serial number to determine which transmission the ACK is for,
6759 * and set the sent time to match this. If we have no serial number, then
6760 * only use the ACK for RTT calculations if the packet has not been
6764 serial = ntohl(ack->serial);
6766 if (serial == p->header.serial) {
6767 sentp = &p->timeSent;
6768 } else if (serial == p->firstSerial) {
6769 sentp = &p->firstSent;
6770 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6771 sentp = &p->firstSent;
6775 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6776 sentp = &p->firstSent;
6783 if (clock_Lt(&thisRtt, sentp))
6784 return; /* somebody set the clock back, don't count this time. */
6786 clock_Sub(&thisRtt, sentp);
6787 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6788 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6790 if (clock_IsZero(&thisRtt)) {
6792 * The actual round trip time is shorter than the
6793 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6794 * Since we can't tell which at the moment we will assume 1ms.
6796 thisRtt.usec = 1000;
6799 if (rx_stats_active) {
6800 MUTEX_ENTER(&rx_stats_mutex);
6801 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6802 rx_stats.minRtt = thisRtt;
6803 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6804 if (thisRtt.sec > 60) {
6805 MUTEX_EXIT(&rx_stats_mutex);
6806 return; /* somebody set the clock ahead */
6808 rx_stats.maxRtt = thisRtt;
6810 clock_Add(&rx_stats.totalRtt, &thisRtt);
6811 rx_atomic_inc(&rx_stats.nRttSamples);
6812 MUTEX_EXIT(&rx_stats_mutex);
6815 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6817 /* Apply VanJacobson round-trip estimations */
6822 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6823 * srtt is stored as fixed point with 3 bits after the binary
6824 * point (i.e., scaled by 8). The following magic is
6825 * equivalent to the smoothing algorithm in rfc793 with an
6826 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6827 * srtt'*8 = rtt + srtt*7
6828 * srtt'*8 = srtt*8 + rtt - srtt
6829 * srtt' = srtt + rtt/8 - srtt/8
6830 * srtt' = srtt + (rtt - srtt)/8
6833 delta = _8THMSEC(&thisRtt) - call->rtt;
6834 call->rtt += (delta >> 3);
6837 * We accumulate a smoothed rtt variance (actually, a smoothed
6838 * mean difference), then set the retransmit timer to smoothed
6839 * rtt + 4 times the smoothed variance (was 2x in van's original
6840 * paper, but 4x works better for me, and apparently for him as
6842 * rttvar is stored as
6843 * fixed point with 2 bits after the binary point (scaled by
6844 * 4). The following is equivalent to rfc793 smoothing with
6845 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6846 * rttvar'*4 = rttvar*3 + |delta|
6847 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6848 * rttvar' = rttvar + |delta|/4 - rttvar/4
6849 * rttvar' = rttvar + (|delta| - rttvar)/4
6850 * This replaces rfc793's wired-in beta.
6851 * dev*4 = dev*4 + (|actual - expected| - dev)
6857 delta -= (call->rtt_dev << 1);
6858 call->rtt_dev += (delta >> 3);
6860 /* I don't have a stored RTT so I start with this value. Since I'm
6861 * probably just starting a call, and will be pushing more data down
6862 * this, I expect congestion to increase rapidly. So I fudge a
6863 * little, and I set deviance to half the rtt. In practice,
6864 * deviance tends to approach something a little less than
6865 * half the smoothed rtt. */
6866 call->rtt = _8THMSEC(&thisRtt) + 8;
6867 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6869 /* the smoothed RTT time is RTT + 4*MDEV
6871 * We allow a user specified minimum to be set for this, to allow clamping
6872 * at a minimum value in the same way as TCP. In addition, we have to allow
6873 * for the possibility that this packet is answered by a delayed ACK, so we
6874 * add on a fixed 200ms to account for that timer expiring.
6877 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6878 rx_minPeerTimeout) + 200;
6879 clock_Zero(&call->rto);
6880 clock_Addmsec(&call->rto, rtt_timeout);
6882 /* Update the peer, so any new calls start with our values */
6883 peer->rtt_dev = call->rtt_dev;
6884 peer->rtt = call->rtt;
6886 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6887 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6891 /* Find all server connections that have not been active for a long time, and
6894 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6897 struct clock now, when;
6898 clock_GetTime(&now);
6900 /* Find server connection structures that haven't been used for
6901 * greater than rx_idleConnectionTime */
6903 struct rx_connection **conn_ptr, **conn_end;
6904 int i, havecalls = 0;
6905 MUTEX_ENTER(&rx_connHashTable_lock);
6906 for (conn_ptr = &rx_connHashTable[0], conn_end =
6907 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6909 struct rx_connection *conn, *next;
6910 struct rx_call *call;
6914 for (conn = *conn_ptr; conn; conn = next) {
6915 /* XXX -- Shouldn't the connection be locked? */
6918 for (i = 0; i < RX_MAXCALLS; i++) {
6919 call = conn->call[i];
6923 code = MUTEX_TRYENTER(&call->lock);
6926 #ifdef RX_ENABLE_LOCKS
6927 result = rxi_CheckCall(call, 1);
6928 #else /* RX_ENABLE_LOCKS */
6929 result = rxi_CheckCall(call);
6930 #endif /* RX_ENABLE_LOCKS */
6931 MUTEX_EXIT(&call->lock);
6933 /* If CheckCall freed the call, it might
6934 * have destroyed the connection as well,
6935 * which screws up the linked lists.
6941 if (conn->type == RX_SERVER_CONNECTION) {
6942 /* This only actually destroys the connection if
6943 * there are no outstanding calls */
6944 MUTEX_ENTER(&conn->conn_data_lock);
6945 MUTEX_ENTER(&rx_refcnt_mutex);
6946 if (!havecalls && !conn->refCount
6947 && ((conn->lastSendTime + rx_idleConnectionTime) <
6949 conn->refCount++; /* it will be decr in rx_DestroyConn */
6950 MUTEX_EXIT(&rx_refcnt_mutex);
6951 MUTEX_EXIT(&conn->conn_data_lock);
6952 #ifdef RX_ENABLE_LOCKS
6953 rxi_DestroyConnectionNoLock(conn);
6954 #else /* RX_ENABLE_LOCKS */
6955 rxi_DestroyConnection(conn);
6956 #endif /* RX_ENABLE_LOCKS */
6958 #ifdef RX_ENABLE_LOCKS
6960 MUTEX_EXIT(&rx_refcnt_mutex);
6961 MUTEX_EXIT(&conn->conn_data_lock);
6963 #endif /* RX_ENABLE_LOCKS */
6967 #ifdef RX_ENABLE_LOCKS
6968 while (rx_connCleanup_list) {
6969 struct rx_connection *conn;
6970 conn = rx_connCleanup_list;
6971 rx_connCleanup_list = rx_connCleanup_list->next;
6972 MUTEX_EXIT(&rx_connHashTable_lock);
6973 rxi_CleanupConnection(conn);
6974 MUTEX_ENTER(&rx_connHashTable_lock);
6976 MUTEX_EXIT(&rx_connHashTable_lock);
6977 #endif /* RX_ENABLE_LOCKS */
6980 /* Find any peer structures that haven't been used (haven't had an
6981 * associated connection) for greater than rx_idlePeerTime */
6983 struct rx_peer **peer_ptr, **peer_end;
6987 * Why do we need to hold the rx_peerHashTable_lock across
6988 * the incrementing of peer_ptr since the rx_peerHashTable
6989 * array is not changing? We don't.
6991 * By dropping the lock periodically we can permit other
6992 * activities to be performed while a rxi_ReapConnections
6993 * call is in progress. The goal of reap connections
6994 * is to clean up quickly without causing large amounts
6995 * of contention. Therefore, it is important that global
6996 * mutexes not be held for extended periods of time.
6998 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6999 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7001 struct rx_peer *peer, *next, *prev;
7003 MUTEX_ENTER(&rx_peerHashTable_lock);
7004 for (prev = peer = *peer_ptr; peer; peer = next) {
7006 code = MUTEX_TRYENTER(&peer->peer_lock);
7007 if ((code) && (peer->refCount == 0)
7008 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7009 rx_interface_stat_p rpc_stat, nrpc_stat;
7013 * now know that this peer object is one to be
7014 * removed from the hash table. Once it is removed
7015 * it can't be referenced by other threads.
7016 * Lets remove it first and decrement the struct
7017 * nPeerStructs count.
7019 if (peer == *peer_ptr) {
7025 if (rx_stats_active)
7026 rx_atomic_dec(&rx_stats.nPeerStructs);
7029 * Now if we hold references on 'prev' and 'next'
7030 * we can safely drop the rx_peerHashTable_lock
7031 * while we destroy this 'peer' object.
7037 MUTEX_EXIT(&rx_peerHashTable_lock);
7039 MUTEX_EXIT(&peer->peer_lock);
7040 MUTEX_DESTROY(&peer->peer_lock);
7042 (&peer->rpcStats, rpc_stat, nrpc_stat,
7043 rx_interface_stat)) {
7044 unsigned int num_funcs;
7047 queue_Remove(&rpc_stat->queue_header);
7048 queue_Remove(&rpc_stat->all_peers);
7049 num_funcs = rpc_stat->stats[0].func_total;
7051 sizeof(rx_interface_stat_t) +
7052 rpc_stat->stats[0].func_total *
7053 sizeof(rx_function_entry_v1_t);
7055 rxi_Free(rpc_stat, space);
7057 MUTEX_ENTER(&rx_rpc_stats);
7058 rxi_rpc_peer_stat_cnt -= num_funcs;
7059 MUTEX_EXIT(&rx_rpc_stats);
7064 * Regain the rx_peerHashTable_lock and
7065 * decrement the reference count on 'prev'
7068 MUTEX_ENTER(&rx_peerHashTable_lock);
7075 MUTEX_EXIT(&peer->peer_lock);
7080 MUTEX_EXIT(&rx_peerHashTable_lock);
7084 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7085 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7086 * GC, just below. Really, we shouldn't have to keep moving packets from
7087 * one place to another, but instead ought to always know if we can
7088 * afford to hold onto a packet in its particular use. */
7089 MUTEX_ENTER(&rx_freePktQ_lock);
7090 if (rx_waitingForPackets) {
7091 rx_waitingForPackets = 0;
7092 #ifdef RX_ENABLE_LOCKS
7093 CV_BROADCAST(&rx_waitingForPackets_cv);
7095 osi_rxWakeup(&rx_waitingForPackets);
7098 MUTEX_EXIT(&rx_freePktQ_lock);
7101 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7102 rxevent_Put(rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0));
7106 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7107 * rx.h is sort of strange this is better. This is called with a security
7108 * object before it is discarded. Each connection using a security object has
7109 * its own refcount to the object so it won't actually be freed until the last
7110 * connection is destroyed.
7112 * This is the only rxs module call. A hold could also be written but no one
7116 rxs_Release(struct rx_securityClass *aobj)
7118 return RXS_Close(aobj);
7126 #define TRACE_OPTION_RX_DEBUG 16
7134 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7135 0, KEY_QUERY_VALUE, &parmKey);
7136 if (code != ERROR_SUCCESS)
7139 dummyLen = sizeof(TraceOption);
7140 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7141 (BYTE *) &TraceOption, &dummyLen);
7142 if (code == ERROR_SUCCESS) {
7143 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7145 RegCloseKey (parmKey);
7146 #endif /* AFS_NT40_ENV */
7151 rx_DebugOnOff(int on)
7155 rxdebug_active = on;
7161 rx_StatsOnOff(int on)
7163 rx_stats_active = on;
7167 /* Don't call this debugging routine directly; use dpf */
7169 rxi_DebugPrint(char *format, ...)
7178 va_start(ap, format);
7180 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7183 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7185 OutputDebugString(msg);
7191 va_start(ap, format);
7193 clock_GetTime(&now);
7194 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7195 (unsigned int)now.usec);
7196 vfprintf(rx_Log, format, ap);
7204 * This function is used to process the rx_stats structure that is local
7205 * to a process as well as an rx_stats structure received from a remote
7206 * process (via rxdebug). Therefore, it needs to do minimal version
7210 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7211 afs_int32 freePackets, char version)
7215 if (size != sizeof(struct rx_statistics)) {
7217 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7218 size, sizeof(struct rx_statistics));
7221 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7224 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7225 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7226 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7227 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7228 s->specialPktAllocFailures);
7230 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7231 s->receivePktAllocFailures, s->sendPktAllocFailures,
7232 s->specialPktAllocFailures);
7236 " greedy %u, " "bogusReads %u (last from host %x), "
7237 "noPackets %u, " "noBuffers %u, " "selects %u, "
7238 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7239 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7240 s->selects, s->sendSelects);
7242 fprintf(file, " packets read: ");
7243 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7244 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7246 fprintf(file, "\n");
7249 " other read counters: data %u, " "ack %u, " "dup %u "
7250 "spurious %u " "dally %u\n", s->dataPacketsRead,
7251 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7252 s->ignorePacketDally);
7254 fprintf(file, " packets sent: ");
7255 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7256 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7258 fprintf(file, "\n");
7261 " other send counters: ack %u, " "data %u (not resends), "
7262 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7263 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7264 s->dataPacketsPushed, s->ignoreAckedPacket);
7267 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7268 s->netSendFailures, (int)s->fatalErrors);
7270 if (s->nRttSamples) {
7271 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7272 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7274 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7275 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7279 " %d server connections, " "%d client connections, "
7280 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7281 s->nServerConns, s->nClientConns, s->nPeerStructs,
7282 s->nCallStructs, s->nFreeCallStructs);
7284 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7285 fprintf(file, " %d clock updates\n", clock_nUpdates);
7289 /* for backward compatibility */
7291 rx_PrintStats(FILE * file)
7293 MUTEX_ENTER(&rx_stats_mutex);
7294 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7295 sizeof(rx_stats), rx_nFreePackets,
7297 MUTEX_EXIT(&rx_stats_mutex);
7301 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7303 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7304 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7305 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7308 " Rtt %d, " "total sent %d, " "resent %d\n",
7309 peer->rtt, peer->nSent, peer->reSends);
7312 " Packet size %d, " "max in packet skew %d, "
7313 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7314 (int)peer->outPacketSkew);
7318 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7320 * This mutex protects the following static variables:
7324 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7325 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7327 #define LOCK_RX_DEBUG
7328 #define UNLOCK_RX_DEBUG
7329 #endif /* AFS_PTHREAD_ENV */
7331 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7333 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7334 u_char type, void *inputData, size_t inputLength,
7335 void *outputData, size_t outputLength)
7337 static afs_int32 counter = 100;
7338 time_t waitTime, waitCount;
7339 struct rx_header theader;
7342 struct timeval tv_now, tv_wake, tv_delta;
7343 struct sockaddr_in taddr, faddr;
7357 tp = &tbuffer[sizeof(struct rx_header)];
7358 taddr.sin_family = AF_INET;
7359 taddr.sin_port = remotePort;
7360 taddr.sin_addr.s_addr = remoteAddr;
7361 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7362 taddr.sin_len = sizeof(struct sockaddr_in);
7365 memset(&theader, 0, sizeof(theader));
7366 theader.epoch = htonl(999);
7368 theader.callNumber = htonl(counter);
7371 theader.type = type;
7372 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7373 theader.serviceId = 0;
7375 memcpy(tbuffer, &theader, sizeof(theader));
7376 memcpy(tp, inputData, inputLength);
7378 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7379 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7381 /* see if there's a packet available */
7382 gettimeofday(&tv_wake, NULL);
7383 tv_wake.tv_sec += waitTime;
7386 FD_SET(socket, &imask);
7387 tv_delta.tv_sec = tv_wake.tv_sec;
7388 tv_delta.tv_usec = tv_wake.tv_usec;
7389 gettimeofday(&tv_now, NULL);
7391 if (tv_delta.tv_usec < tv_now.tv_usec) {
7393 tv_delta.tv_usec += 1000000;
7396 tv_delta.tv_usec -= tv_now.tv_usec;
7398 if (tv_delta.tv_sec < tv_now.tv_sec) {
7402 tv_delta.tv_sec -= tv_now.tv_sec;
7405 code = select(0, &imask, 0, 0, &tv_delta);
7406 #else /* AFS_NT40_ENV */
7407 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7408 #endif /* AFS_NT40_ENV */
7409 if (code == 1 && FD_ISSET(socket, &imask)) {
7410 /* now receive a packet */
7411 faddrLen = sizeof(struct sockaddr_in);
7413 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7414 (struct sockaddr *)&faddr, &faddrLen);
7417 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7418 if (counter == ntohl(theader.callNumber))
7426 /* see if we've timed out */
7434 code -= sizeof(struct rx_header);
7435 if (code > outputLength)
7436 code = outputLength;
7437 memcpy(outputData, tp, code);
7440 #endif /* RXDEBUG */
7443 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7444 afs_uint16 remotePort, struct rx_debugStats * stat,
7445 afs_uint32 * supportedValues)
7447 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7449 struct rx_debugIn in;
7451 *supportedValues = 0;
7452 in.type = htonl(RX_DEBUGI_GETSTATS);
7455 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7456 &in, sizeof(in), stat, sizeof(*stat));
7459 * If the call was successful, fixup the version and indicate
7460 * what contents of the stat structure are valid.
7461 * Also do net to host conversion of fields here.
7465 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7466 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7468 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7469 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7471 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7472 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7474 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7475 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7477 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7478 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7480 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7481 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7483 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7484 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7486 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7487 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7489 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7490 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7492 stat->nFreePackets = ntohl(stat->nFreePackets);
7493 stat->packetReclaims = ntohl(stat->packetReclaims);
7494 stat->callsExecuted = ntohl(stat->callsExecuted);
7495 stat->nWaiting = ntohl(stat->nWaiting);
7496 stat->idleThreads = ntohl(stat->idleThreads);
7497 stat->nWaited = ntohl(stat->nWaited);
7498 stat->nPackets = ntohl(stat->nPackets);
7507 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7508 afs_uint16 remotePort, struct rx_statistics * stat,
7509 afs_uint32 * supportedValues)
7511 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7513 struct rx_debugIn in;
7514 afs_int32 *lp = (afs_int32 *) stat;
7518 * supportedValues is currently unused, but added to allow future
7519 * versioning of this function.
7522 *supportedValues = 0;
7523 in.type = htonl(RX_DEBUGI_RXSTATS);
7525 memset(stat, 0, sizeof(*stat));
7527 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7528 &in, sizeof(in), stat, sizeof(*stat));
7533 * Do net to host conversion here
7536 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7547 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7548 afs_uint16 remotePort, size_t version_length,
7551 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7553 return MakeDebugCall(socket, remoteAddr, remotePort,
7554 RX_PACKET_TYPE_VERSION, a, 1, version,
7562 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7563 afs_uint16 remotePort, afs_int32 * nextConnection,
7564 int allConnections, afs_uint32 debugSupportedValues,
7565 struct rx_debugConn * conn,
7566 afs_uint32 * supportedValues)
7568 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7570 struct rx_debugIn in;
7574 * supportedValues is currently unused, but added to allow future
7575 * versioning of this function.
7578 *supportedValues = 0;
7579 if (allConnections) {
7580 in.type = htonl(RX_DEBUGI_GETALLCONN);
7582 in.type = htonl(RX_DEBUGI_GETCONN);
7584 in.index = htonl(*nextConnection);
7585 memset(conn, 0, sizeof(*conn));
7587 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7588 &in, sizeof(in), conn, sizeof(*conn));
7591 *nextConnection += 1;
7594 * Convert old connection format to new structure.
7597 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7598 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7599 #define MOVEvL(a) (conn->a = vL->a)
7601 /* any old or unrecognized version... */
7602 for (i = 0; i < RX_MAXCALLS; i++) {
7603 MOVEvL(callState[i]);
7604 MOVEvL(callMode[i]);
7605 MOVEvL(callFlags[i]);
7606 MOVEvL(callOther[i]);
7608 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7609 MOVEvL(secStats.type);
7610 MOVEvL(secStats.level);
7611 MOVEvL(secStats.flags);
7612 MOVEvL(secStats.expires);
7613 MOVEvL(secStats.packetsReceived);
7614 MOVEvL(secStats.packetsSent);
7615 MOVEvL(secStats.bytesReceived);
7616 MOVEvL(secStats.bytesSent);
7621 * Do net to host conversion here
7623 * I don't convert host or port since we are most likely
7624 * going to want these in NBO.
7626 conn->cid = ntohl(conn->cid);
7627 conn->serial = ntohl(conn->serial);
7628 for (i = 0; i < RX_MAXCALLS; i++) {
7629 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7631 conn->error = ntohl(conn->error);
7632 conn->secStats.flags = ntohl(conn->secStats.flags);
7633 conn->secStats.expires = ntohl(conn->secStats.expires);
7634 conn->secStats.packetsReceived =
7635 ntohl(conn->secStats.packetsReceived);
7636 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7637 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7638 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7639 conn->epoch = ntohl(conn->epoch);
7640 conn->natMTU = ntohl(conn->natMTU);
7649 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7650 afs_uint16 remotePort, afs_int32 * nextPeer,
7651 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7652 afs_uint32 * supportedValues)
7654 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7656 struct rx_debugIn in;
7659 * supportedValues is currently unused, but added to allow future
7660 * versioning of this function.
7663 *supportedValues = 0;
7664 in.type = htonl(RX_DEBUGI_GETPEER);
7665 in.index = htonl(*nextPeer);
7666 memset(peer, 0, sizeof(*peer));
7668 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7669 &in, sizeof(in), peer, sizeof(*peer));
7675 * Do net to host conversion here
7677 * I don't convert host or port since we are most likely
7678 * going to want these in NBO.
7680 peer->ifMTU = ntohs(peer->ifMTU);
7681 peer->idleWhen = ntohl(peer->idleWhen);
7682 peer->refCount = ntohs(peer->refCount);
7683 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7684 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7685 peer->rtt = ntohl(peer->rtt);
7686 peer->rtt_dev = ntohl(peer->rtt_dev);
7687 peer->timeout.sec = 0;
7688 peer->timeout.usec = 0;
7689 peer->nSent = ntohl(peer->nSent);
7690 peer->reSends = ntohl(peer->reSends);
7691 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7692 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7693 peer->natMTU = ntohs(peer->natMTU);
7694 peer->maxMTU = ntohs(peer->maxMTU);
7695 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7696 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7697 peer->MTU = ntohs(peer->MTU);
7698 peer->cwind = ntohs(peer->cwind);
7699 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7700 peer->congestSeq = ntohs(peer->congestSeq);
7701 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7702 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7703 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7704 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7713 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7714 struct rx_debugPeer * peerStats)
7717 afs_int32 error = 1; /* default to "did not succeed" */
7718 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7720 MUTEX_ENTER(&rx_peerHashTable_lock);
7721 for(tp = rx_peerHashTable[hashValue];
7722 tp != NULL; tp = tp->next) {
7723 if (tp->host == peerHost)
7729 MUTEX_EXIT(&rx_peerHashTable_lock);
7733 MUTEX_ENTER(&tp->peer_lock);
7734 peerStats->host = tp->host;
7735 peerStats->port = tp->port;
7736 peerStats->ifMTU = tp->ifMTU;
7737 peerStats->idleWhen = tp->idleWhen;
7738 peerStats->refCount = tp->refCount;
7739 peerStats->burstSize = tp->burstSize;
7740 peerStats->burst = tp->burst;
7741 peerStats->burstWait.sec = tp->burstWait.sec;
7742 peerStats->burstWait.usec = tp->burstWait.usec;
7743 peerStats->rtt = tp->rtt;
7744 peerStats->rtt_dev = tp->rtt_dev;
7745 peerStats->timeout.sec = 0;
7746 peerStats->timeout.usec = 0;
7747 peerStats->nSent = tp->nSent;
7748 peerStats->reSends = tp->reSends;
7749 peerStats->inPacketSkew = tp->inPacketSkew;
7750 peerStats->outPacketSkew = tp->outPacketSkew;
7751 peerStats->natMTU = tp->natMTU;
7752 peerStats->maxMTU = tp->maxMTU;
7753 peerStats->maxDgramPackets = tp->maxDgramPackets;
7754 peerStats->ifDgramPackets = tp->ifDgramPackets;
7755 peerStats->MTU = tp->MTU;
7756 peerStats->cwind = tp->cwind;
7757 peerStats->nDgramPackets = tp->nDgramPackets;
7758 peerStats->congestSeq = tp->congestSeq;
7759 peerStats->bytesSent.high = tp->bytesSent.high;
7760 peerStats->bytesSent.low = tp->bytesSent.low;
7761 peerStats->bytesReceived.high = tp->bytesReceived.high;
7762 peerStats->bytesReceived.low = tp->bytesReceived.low;
7763 MUTEX_EXIT(&tp->peer_lock);
7765 MUTEX_ENTER(&rx_peerHashTable_lock);
7768 MUTEX_EXIT(&rx_peerHashTable_lock);
7776 struct rx_serverQueueEntry *np;
7779 struct rx_call *call;
7780 struct rx_serverQueueEntry *sq;
7784 if (rxinit_status == 1) {
7786 return; /* Already shutdown. */
7790 #ifndef AFS_PTHREAD_ENV
7791 FD_ZERO(&rx_selectMask);
7792 #endif /* AFS_PTHREAD_ENV */
7793 rxi_dataQuota = RX_MAX_QUOTA;
7794 #ifndef AFS_PTHREAD_ENV
7796 #endif /* AFS_PTHREAD_ENV */
7799 #ifndef AFS_PTHREAD_ENV
7800 #ifndef AFS_USE_GETTIMEOFDAY
7802 #endif /* AFS_USE_GETTIMEOFDAY */
7803 #endif /* AFS_PTHREAD_ENV */
7805 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7806 call = queue_First(&rx_freeCallQueue, rx_call);
7808 rxi_Free(call, sizeof(struct rx_call));
7811 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7812 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7818 struct rx_peer **peer_ptr, **peer_end;
7819 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7820 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7822 struct rx_peer *peer, *next;
7824 MUTEX_ENTER(&rx_peerHashTable_lock);
7825 for (peer = *peer_ptr; peer; peer = next) {
7826 rx_interface_stat_p rpc_stat, nrpc_stat;
7829 MUTEX_ENTER(&rx_rpc_stats);
7830 MUTEX_ENTER(&peer->peer_lock);
7832 (&peer->rpcStats, rpc_stat, nrpc_stat,
7833 rx_interface_stat)) {
7834 unsigned int num_funcs;
7837 queue_Remove(&rpc_stat->queue_header);
7838 queue_Remove(&rpc_stat->all_peers);
7839 num_funcs = rpc_stat->stats[0].func_total;
7841 sizeof(rx_interface_stat_t) +
7842 rpc_stat->stats[0].func_total *
7843 sizeof(rx_function_entry_v1_t);
7845 rxi_Free(rpc_stat, space);
7847 /* rx_rpc_stats must be held */
7848 rxi_rpc_peer_stat_cnt -= num_funcs;
7850 MUTEX_EXIT(&peer->peer_lock);
7851 MUTEX_EXIT(&rx_rpc_stats);
7855 if (rx_stats_active)
7856 rx_atomic_dec(&rx_stats.nPeerStructs);
7858 MUTEX_EXIT(&rx_peerHashTable_lock);
7861 for (i = 0; i < RX_MAX_SERVICES; i++) {
7863 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7865 for (i = 0; i < rx_hashTableSize; i++) {
7866 struct rx_connection *tc, *ntc;
7867 MUTEX_ENTER(&rx_connHashTable_lock);
7868 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7870 for (j = 0; j < RX_MAXCALLS; j++) {
7872 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7875 rxi_Free(tc, sizeof(*tc));
7877 MUTEX_EXIT(&rx_connHashTable_lock);
7880 MUTEX_ENTER(&freeSQEList_lock);
7882 while ((np = rx_FreeSQEList)) {
7883 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7884 MUTEX_DESTROY(&np->lock);
7885 rxi_Free(np, sizeof(*np));
7888 MUTEX_EXIT(&freeSQEList_lock);
7889 MUTEX_DESTROY(&freeSQEList_lock);
7890 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7891 MUTEX_DESTROY(&rx_connHashTable_lock);
7892 MUTEX_DESTROY(&rx_peerHashTable_lock);
7893 MUTEX_DESTROY(&rx_serverPool_lock);
7895 osi_Free(rx_connHashTable,
7896 rx_hashTableSize * sizeof(struct rx_connection *));
7897 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7899 UNPIN(rx_connHashTable,
7900 rx_hashTableSize * sizeof(struct rx_connection *));
7901 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7903 rxi_FreeAllPackets();
7905 MUTEX_ENTER(&rx_quota_mutex);
7906 rxi_dataQuota = RX_MAX_QUOTA;
7907 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7908 MUTEX_EXIT(&rx_quota_mutex);
7913 #ifdef RX_ENABLE_LOCKS
7915 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7917 if (!MUTEX_ISMINE(lockaddr))
7918 osi_Panic("Lock not held: %s", msg);
7920 #endif /* RX_ENABLE_LOCKS */
7925 * Routines to implement connection specific data.
7929 rx_KeyCreate(rx_destructor_t rtn)
7932 MUTEX_ENTER(&rxi_keyCreate_lock);
7933 key = rxi_keyCreate_counter++;
7934 rxi_keyCreate_destructor = (rx_destructor_t *)
7935 realloc((void *)rxi_keyCreate_destructor,
7936 (key + 1) * sizeof(rx_destructor_t));
7937 rxi_keyCreate_destructor[key] = rtn;
7938 MUTEX_EXIT(&rxi_keyCreate_lock);
7943 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7946 MUTEX_ENTER(&conn->conn_data_lock);
7947 if (!conn->specific) {
7948 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7949 for (i = 0; i < key; i++)
7950 conn->specific[i] = NULL;
7951 conn->nSpecific = key + 1;
7952 conn->specific[key] = ptr;
7953 } else if (key >= conn->nSpecific) {
7954 conn->specific = (void **)
7955 realloc(conn->specific, (key + 1) * sizeof(void *));
7956 for (i = conn->nSpecific; i < key; i++)
7957 conn->specific[i] = NULL;
7958 conn->nSpecific = key + 1;
7959 conn->specific[key] = ptr;
7961 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7962 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7963 conn->specific[key] = ptr;
7965 MUTEX_EXIT(&conn->conn_data_lock);
7969 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7972 MUTEX_ENTER(&svc->svc_data_lock);
7973 if (!svc->specific) {
7974 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7975 for (i = 0; i < key; i++)
7976 svc->specific[i] = NULL;
7977 svc->nSpecific = key + 1;
7978 svc->specific[key] = ptr;
7979 } else if (key >= svc->nSpecific) {
7980 svc->specific = (void **)
7981 realloc(svc->specific, (key + 1) * sizeof(void *));
7982 for (i = svc->nSpecific; i < key; i++)
7983 svc->specific[i] = NULL;
7984 svc->nSpecific = key + 1;
7985 svc->specific[key] = ptr;
7987 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7988 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7989 svc->specific[key] = ptr;
7991 MUTEX_EXIT(&svc->svc_data_lock);
7995 rx_GetSpecific(struct rx_connection *conn, int key)
7998 MUTEX_ENTER(&conn->conn_data_lock);
7999 if (key >= conn->nSpecific)
8002 ptr = conn->specific[key];
8003 MUTEX_EXIT(&conn->conn_data_lock);
8008 rx_GetServiceSpecific(struct rx_service *svc, int key)
8011 MUTEX_ENTER(&svc->svc_data_lock);
8012 if (key >= svc->nSpecific)
8015 ptr = svc->specific[key];
8016 MUTEX_EXIT(&svc->svc_data_lock);
8021 #endif /* !KERNEL */
8024 * processStats is a queue used to store the statistics for the local
8025 * process. Its contents are similar to the contents of the rpcStats
8026 * queue on a rx_peer structure, but the actual data stored within
8027 * this queue contains totals across the lifetime of the process (assuming
8028 * the stats have not been reset) - unlike the per peer structures
8029 * which can come and go based upon the peer lifetime.
8032 static struct rx_queue processStats = { &processStats, &processStats };
8035 * peerStats is a queue used to store the statistics for all peer structs.
8036 * Its contents are the union of all the peer rpcStats queues.
8039 static struct rx_queue peerStats = { &peerStats, &peerStats };
8042 * rxi_monitor_processStats is used to turn process wide stat collection
8046 static int rxi_monitor_processStats = 0;
8049 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8052 static int rxi_monitor_peerStats = 0;
8055 * rxi_AddRpcStat - given all of the information for a particular rpc
8056 * call, create (if needed) and update the stat totals for the rpc.
8060 * IN stats - the queue of stats that will be updated with the new value
8062 * IN rxInterface - a unique number that identifies the rpc interface
8064 * IN currentFunc - the index of the function being invoked
8066 * IN totalFunc - the total number of functions in this interface
8068 * IN queueTime - the amount of time this function waited for a thread
8070 * IN execTime - the amount of time this function invocation took to execute
8072 * IN bytesSent - the number bytes sent by this invocation
8074 * IN bytesRcvd - the number bytes received by this invocation
8076 * IN isServer - if true, this invocation was made to a server
8078 * IN remoteHost - the ip address of the remote host
8080 * IN remotePort - the port of the remote host
8082 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8084 * INOUT counter - if a new stats structure is allocated, the counter will
8085 * be updated with the new number of allocated stat structures
8093 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8094 afs_uint32 currentFunc, afs_uint32 totalFunc,
8095 struct clock *queueTime, struct clock *execTime,
8096 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8097 afs_uint32 remoteHost, afs_uint32 remotePort,
8098 int addToPeerList, unsigned int *counter)
8101 rx_interface_stat_p rpc_stat, nrpc_stat;
8104 * See if there's already a structure for this interface
8107 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8108 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8109 && (rpc_stat->stats[0].remote_is_server == isServer))
8114 * Didn't find a match so allocate a new structure and add it to the
8118 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8119 || (rpc_stat->stats[0].interfaceId != rxInterface)
8120 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8125 sizeof(rx_interface_stat_t) +
8126 totalFunc * sizeof(rx_function_entry_v1_t);
8128 rpc_stat = rxi_Alloc(space);
8129 if (rpc_stat == NULL) {
8133 *counter += totalFunc;
8134 for (i = 0; i < totalFunc; i++) {
8135 rpc_stat->stats[i].remote_peer = remoteHost;
8136 rpc_stat->stats[i].remote_port = remotePort;
8137 rpc_stat->stats[i].remote_is_server = isServer;
8138 rpc_stat->stats[i].interfaceId = rxInterface;
8139 rpc_stat->stats[i].func_total = totalFunc;
8140 rpc_stat->stats[i].func_index = i;
8141 hzero(rpc_stat->stats[i].invocations);
8142 hzero(rpc_stat->stats[i].bytes_sent);
8143 hzero(rpc_stat->stats[i].bytes_rcvd);
8144 rpc_stat->stats[i].queue_time_sum.sec = 0;
8145 rpc_stat->stats[i].queue_time_sum.usec = 0;
8146 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8147 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8148 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8149 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8150 rpc_stat->stats[i].queue_time_max.sec = 0;
8151 rpc_stat->stats[i].queue_time_max.usec = 0;
8152 rpc_stat->stats[i].execution_time_sum.sec = 0;
8153 rpc_stat->stats[i].execution_time_sum.usec = 0;
8154 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8155 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8156 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8157 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8158 rpc_stat->stats[i].execution_time_max.sec = 0;
8159 rpc_stat->stats[i].execution_time_max.usec = 0;
8161 queue_Prepend(stats, rpc_stat);
8162 if (addToPeerList) {
8163 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8168 * Increment the stats for this function
8171 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8172 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8173 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8174 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8175 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8176 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8177 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8179 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8180 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8182 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8183 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8185 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8186 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8188 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8189 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8197 * rx_IncrementTimeAndCount - increment the times and count for a particular
8202 * IN peer - the peer who invoked the rpc
8204 * IN rxInterface - a unique number that identifies the rpc interface
8206 * IN currentFunc - the index of the function being invoked
8208 * IN totalFunc - the total number of functions in this interface
8210 * IN queueTime - the amount of time this function waited for a thread
8212 * IN execTime - the amount of time this function invocation took to execute
8214 * IN bytesSent - the number bytes sent by this invocation
8216 * IN bytesRcvd - the number bytes received by this invocation
8218 * IN isServer - if true, this invocation was made to a server
8226 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8227 afs_uint32 currentFunc, afs_uint32 totalFunc,
8228 struct clock *queueTime, struct clock *execTime,
8229 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8233 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8236 MUTEX_ENTER(&rx_rpc_stats);
8238 if (rxi_monitor_peerStats) {
8239 MUTEX_ENTER(&peer->peer_lock);
8240 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8241 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8242 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8243 MUTEX_EXIT(&peer->peer_lock);
8246 if (rxi_monitor_processStats) {
8247 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8248 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8249 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8252 MUTEX_EXIT(&rx_rpc_stats);
8257 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8261 * IN callerVersion - the rpc stat version of the caller.
8263 * IN count - the number of entries to marshall.
8265 * IN stats - pointer to stats to be marshalled.
8267 * OUT ptr - Where to store the marshalled data.
8274 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8275 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8281 * We only support the first version
8283 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8284 *(ptr++) = stats->remote_peer;
8285 *(ptr++) = stats->remote_port;
8286 *(ptr++) = stats->remote_is_server;
8287 *(ptr++) = stats->interfaceId;
8288 *(ptr++) = stats->func_total;
8289 *(ptr++) = stats->func_index;
8290 *(ptr++) = hgethi(stats->invocations);
8291 *(ptr++) = hgetlo(stats->invocations);
8292 *(ptr++) = hgethi(stats->bytes_sent);
8293 *(ptr++) = hgetlo(stats->bytes_sent);
8294 *(ptr++) = hgethi(stats->bytes_rcvd);
8295 *(ptr++) = hgetlo(stats->bytes_rcvd);
8296 *(ptr++) = stats->queue_time_sum.sec;
8297 *(ptr++) = stats->queue_time_sum.usec;
8298 *(ptr++) = stats->queue_time_sum_sqr.sec;
8299 *(ptr++) = stats->queue_time_sum_sqr.usec;
8300 *(ptr++) = stats->queue_time_min.sec;
8301 *(ptr++) = stats->queue_time_min.usec;
8302 *(ptr++) = stats->queue_time_max.sec;
8303 *(ptr++) = stats->queue_time_max.usec;
8304 *(ptr++) = stats->execution_time_sum.sec;
8305 *(ptr++) = stats->execution_time_sum.usec;
8306 *(ptr++) = stats->execution_time_sum_sqr.sec;
8307 *(ptr++) = stats->execution_time_sum_sqr.usec;
8308 *(ptr++) = stats->execution_time_min.sec;
8309 *(ptr++) = stats->execution_time_min.usec;
8310 *(ptr++) = stats->execution_time_max.sec;
8311 *(ptr++) = stats->execution_time_max.usec;
8317 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8322 * IN callerVersion - the rpc stat version of the caller
8324 * OUT myVersion - the rpc stat version of this function
8326 * OUT clock_sec - local time seconds
8328 * OUT clock_usec - local time microseconds
8330 * OUT allocSize - the number of bytes allocated to contain stats
8332 * OUT statCount - the number stats retrieved from this process.
8334 * OUT stats - the actual stats retrieved from this process.
8338 * Returns void. If successful, stats will != NULL.
8342 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8343 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8344 size_t * allocSize, afs_uint32 * statCount,
8345 afs_uint32 ** stats)
8355 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8358 * Check to see if stats are enabled
8361 MUTEX_ENTER(&rx_rpc_stats);
8362 if (!rxi_monitor_processStats) {
8363 MUTEX_EXIT(&rx_rpc_stats);
8367 clock_GetTime(&now);
8368 *clock_sec = now.sec;
8369 *clock_usec = now.usec;
8372 * Allocate the space based upon the caller version
8374 * If the client is at an older version than we are,
8375 * we return the statistic data in the older data format, but
8376 * we still return our version number so the client knows we
8377 * are maintaining more data than it can retrieve.
8380 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8381 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8382 *statCount = rxi_rpc_process_stat_cnt;
8385 * This can't happen yet, but in the future version changes
8386 * can be handled by adding additional code here
8390 if (space > (size_t) 0) {
8392 ptr = *stats = rxi_Alloc(space);
8395 rx_interface_stat_p rpc_stat, nrpc_stat;
8399 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8401 * Copy the data based upon the caller version
8403 rx_MarshallProcessRPCStats(callerVersion,
8404 rpc_stat->stats[0].func_total,
8405 rpc_stat->stats, &ptr);
8411 MUTEX_EXIT(&rx_rpc_stats);
8416 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8420 * IN callerVersion - the rpc stat version of the caller
8422 * OUT myVersion - the rpc stat version of this function
8424 * OUT clock_sec - local time seconds
8426 * OUT clock_usec - local time microseconds
8428 * OUT allocSize - the number of bytes allocated to contain stats
8430 * OUT statCount - the number of stats retrieved from the individual
8433 * OUT stats - the actual stats retrieved from the individual peer structures.
8437 * Returns void. If successful, stats will != NULL.
8441 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8442 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8443 size_t * allocSize, afs_uint32 * statCount,
8444 afs_uint32 ** stats)
8454 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8457 * Check to see if stats are enabled
8460 MUTEX_ENTER(&rx_rpc_stats);
8461 if (!rxi_monitor_peerStats) {
8462 MUTEX_EXIT(&rx_rpc_stats);
8466 clock_GetTime(&now);
8467 *clock_sec = now.sec;
8468 *clock_usec = now.usec;
8471 * Allocate the space based upon the caller version
8473 * If the client is at an older version than we are,
8474 * we return the statistic data in the older data format, but
8475 * we still return our version number so the client knows we
8476 * are maintaining more data than it can retrieve.
8479 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8480 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8481 *statCount = rxi_rpc_peer_stat_cnt;
8484 * This can't happen yet, but in the future version changes
8485 * can be handled by adding additional code here
8489 if (space > (size_t) 0) {
8491 ptr = *stats = rxi_Alloc(space);
8494 rx_interface_stat_p rpc_stat, nrpc_stat;
8498 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8500 * We have to fix the offset of rpc_stat since we are
8501 * keeping this structure on two rx_queues. The rx_queue
8502 * package assumes that the rx_queue member is the first
8503 * member of the structure. That is, rx_queue assumes that
8504 * any one item is only on one queue at a time. We are
8505 * breaking that assumption and so we have to do a little
8506 * math to fix our pointers.
8509 fix_offset = (char *)rpc_stat;
8510 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8511 rpc_stat = (rx_interface_stat_p) fix_offset;
8514 * Copy the data based upon the caller version
8516 rx_MarshallProcessRPCStats(callerVersion,
8517 rpc_stat->stats[0].func_total,
8518 rpc_stat->stats, &ptr);
8524 MUTEX_EXIT(&rx_rpc_stats);
8529 * rx_FreeRPCStats - free memory allocated by
8530 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8534 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8535 * rx_RetrievePeerRPCStats
8537 * IN allocSize - the number of bytes in stats.
8545 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8547 rxi_Free(stats, allocSize);
8551 * rx_queryProcessRPCStats - see if process rpc stat collection is
8552 * currently enabled.
8558 * Returns 0 if stats are not enabled != 0 otherwise
8562 rx_queryProcessRPCStats(void)
8565 MUTEX_ENTER(&rx_rpc_stats);
8566 rc = rxi_monitor_processStats;
8567 MUTEX_EXIT(&rx_rpc_stats);
8572 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8578 * Returns 0 if stats are not enabled != 0 otherwise
8582 rx_queryPeerRPCStats(void)
8585 MUTEX_ENTER(&rx_rpc_stats);
8586 rc = rxi_monitor_peerStats;
8587 MUTEX_EXIT(&rx_rpc_stats);
8592 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8602 rx_enableProcessRPCStats(void)
8604 MUTEX_ENTER(&rx_rpc_stats);
8605 rx_enable_stats = 1;
8606 rxi_monitor_processStats = 1;
8607 MUTEX_EXIT(&rx_rpc_stats);
8611 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8621 rx_enablePeerRPCStats(void)
8623 MUTEX_ENTER(&rx_rpc_stats);
8624 rx_enable_stats = 1;
8625 rxi_monitor_peerStats = 1;
8626 MUTEX_EXIT(&rx_rpc_stats);
8630 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8640 rx_disableProcessRPCStats(void)
8642 rx_interface_stat_p rpc_stat, nrpc_stat;
8645 MUTEX_ENTER(&rx_rpc_stats);
8648 * Turn off process statistics and if peer stats is also off, turn
8652 rxi_monitor_processStats = 0;
8653 if (rxi_monitor_peerStats == 0) {
8654 rx_enable_stats = 0;
8657 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8658 unsigned int num_funcs = 0;
8661 queue_Remove(rpc_stat);
8662 num_funcs = rpc_stat->stats[0].func_total;
8664 sizeof(rx_interface_stat_t) +
8665 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8667 rxi_Free(rpc_stat, space);
8668 rxi_rpc_process_stat_cnt -= num_funcs;
8670 MUTEX_EXIT(&rx_rpc_stats);
8674 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8684 rx_disablePeerRPCStats(void)
8686 struct rx_peer **peer_ptr, **peer_end;
8690 * Turn off peer statistics and if process stats is also off, turn
8694 rxi_monitor_peerStats = 0;
8695 if (rxi_monitor_processStats == 0) {
8696 rx_enable_stats = 0;
8699 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8700 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8702 struct rx_peer *peer, *next, *prev;
8704 MUTEX_ENTER(&rx_peerHashTable_lock);
8705 MUTEX_ENTER(&rx_rpc_stats);
8706 for (prev = peer = *peer_ptr; peer; peer = next) {
8708 code = MUTEX_TRYENTER(&peer->peer_lock);
8710 rx_interface_stat_p rpc_stat, nrpc_stat;
8713 if (prev == *peer_ptr) {
8724 MUTEX_EXIT(&rx_peerHashTable_lock);
8727 (&peer->rpcStats, rpc_stat, nrpc_stat,
8728 rx_interface_stat)) {
8729 unsigned int num_funcs = 0;
8732 queue_Remove(&rpc_stat->queue_header);
8733 queue_Remove(&rpc_stat->all_peers);
8734 num_funcs = rpc_stat->stats[0].func_total;
8736 sizeof(rx_interface_stat_t) +
8737 rpc_stat->stats[0].func_total *
8738 sizeof(rx_function_entry_v1_t);
8740 rxi_Free(rpc_stat, space);
8741 rxi_rpc_peer_stat_cnt -= num_funcs;
8743 MUTEX_EXIT(&peer->peer_lock);
8745 MUTEX_ENTER(&rx_peerHashTable_lock);
8755 MUTEX_EXIT(&rx_rpc_stats);
8756 MUTEX_EXIT(&rx_peerHashTable_lock);
8761 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8766 * IN clearFlag - flag indicating which stats to clear
8774 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8776 rx_interface_stat_p rpc_stat, nrpc_stat;
8778 MUTEX_ENTER(&rx_rpc_stats);
8780 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8781 unsigned int num_funcs = 0, i;
8782 num_funcs = rpc_stat->stats[0].func_total;
8783 for (i = 0; i < num_funcs; i++) {
8784 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8785 hzero(rpc_stat->stats[i].invocations);
8787 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8788 hzero(rpc_stat->stats[i].bytes_sent);
8790 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8791 hzero(rpc_stat->stats[i].bytes_rcvd);
8793 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8794 rpc_stat->stats[i].queue_time_sum.sec = 0;
8795 rpc_stat->stats[i].queue_time_sum.usec = 0;
8797 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8798 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8799 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8801 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8802 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8803 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8805 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8806 rpc_stat->stats[i].queue_time_max.sec = 0;
8807 rpc_stat->stats[i].queue_time_max.usec = 0;
8809 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8810 rpc_stat->stats[i].execution_time_sum.sec = 0;
8811 rpc_stat->stats[i].execution_time_sum.usec = 0;
8813 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8814 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8815 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8817 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8818 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8819 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8821 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8822 rpc_stat->stats[i].execution_time_max.sec = 0;
8823 rpc_stat->stats[i].execution_time_max.usec = 0;
8828 MUTEX_EXIT(&rx_rpc_stats);
8832 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8837 * IN clearFlag - flag indicating which stats to clear
8845 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8847 rx_interface_stat_p rpc_stat, nrpc_stat;
8849 MUTEX_ENTER(&rx_rpc_stats);
8851 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8852 unsigned int num_funcs = 0, i;
8855 * We have to fix the offset of rpc_stat since we are
8856 * keeping this structure on two rx_queues. The rx_queue
8857 * package assumes that the rx_queue member is the first
8858 * member of the structure. That is, rx_queue assumes that
8859 * any one item is only on one queue at a time. We are
8860 * breaking that assumption and so we have to do a little
8861 * math to fix our pointers.
8864 fix_offset = (char *)rpc_stat;
8865 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8866 rpc_stat = (rx_interface_stat_p) fix_offset;
8868 num_funcs = rpc_stat->stats[0].func_total;
8869 for (i = 0; i < num_funcs; i++) {
8870 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8871 hzero(rpc_stat->stats[i].invocations);
8873 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8874 hzero(rpc_stat->stats[i].bytes_sent);
8876 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8877 hzero(rpc_stat->stats[i].bytes_rcvd);
8879 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8880 rpc_stat->stats[i].queue_time_sum.sec = 0;
8881 rpc_stat->stats[i].queue_time_sum.usec = 0;
8883 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8884 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8885 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8887 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8888 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8889 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8891 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8892 rpc_stat->stats[i].queue_time_max.sec = 0;
8893 rpc_stat->stats[i].queue_time_max.usec = 0;
8895 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8896 rpc_stat->stats[i].execution_time_sum.sec = 0;
8897 rpc_stat->stats[i].execution_time_sum.usec = 0;
8899 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8900 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8901 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8903 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8904 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8905 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8907 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8908 rpc_stat->stats[i].execution_time_max.sec = 0;
8909 rpc_stat->stats[i].execution_time_max.usec = 0;
8914 MUTEX_EXIT(&rx_rpc_stats);
8918 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8919 * is authorized to enable/disable/clear RX statistics.
8921 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8924 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8926 rxi_rxstat_userok = proc;
8930 rx_RxStatUserOk(struct rx_call *call)
8932 if (!rxi_rxstat_userok)
8934 return rxi_rxstat_userok(call);
8939 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8940 * function in the MSVC runtime DLL (msvcrt.dll).
8942 * Note: the system serializes calls to this function.
8945 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8946 DWORD reason, /* reason function is being called */
8947 LPVOID reserved) /* reserved for future use */
8950 case DLL_PROCESS_ATTACH:
8951 /* library is being attached to a process */
8955 case DLL_PROCESS_DETACH:
8962 #endif /* AFS_NT40_ENV */
8965 int rx_DumpCalls(FILE *outputFile, char *cookie)
8967 #ifdef RXDEBUG_PACKET
8968 #ifdef KDUMP_RX_LOCK
8969 struct rx_call_rx_lock *c;
8976 #define RXDPRINTF sprintf
8977 #define RXDPRINTOUT output
8979 #define RXDPRINTF fprintf
8980 #define RXDPRINTOUT outputFile
8983 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8985 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8988 for (c = rx_allCallsp; c; c = c->allNextp) {
8989 u_short rqc, tqc, iovqc;
8990 struct rx_packet *p, *np;
8992 MUTEX_ENTER(&c->lock);
8993 queue_Count(&c->rq, p, np, rx_packet, rqc);
8994 queue_Count(&c->tq, p, np, rx_packet, tqc);
8995 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8997 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, "
8998 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8999 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9000 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9001 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9002 #ifdef RX_ENABLE_LOCKS
9005 #ifdef RX_REFCOUNT_CHECK
9006 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9007 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9010 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,
9011 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9012 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9013 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9014 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9015 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9016 #ifdef RX_ENABLE_LOCKS
9017 , (afs_uint32)c->refCount
9019 #ifdef RX_REFCOUNT_CHECK
9020 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9023 MUTEX_EXIT(&c->lock);
9026 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9029 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9031 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9033 #endif /* RXDEBUG_PACKET */