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"
30 # include "inet/common.h"
32 # include "inet/ip_ire.h"
34 # include "afs/afs_args.h"
35 # include "afs/afs_osi.h"
36 # ifdef RX_KERNEL_TRACE
37 # include "rx_kcommon.h"
39 # if defined(AFS_AIX_ENV)
43 # undef RXDEBUG /* turn off debugging */
45 # if defined(AFS_SGI_ENV)
46 # include "sys/debug.h"
49 # include "afs/sysincludes.h"
50 # include "afsincludes.h"
51 # endif /* !UKERNEL */
52 # include "afs/lock.h"
53 # include "rx_kmutex.h"
54 # include "rx_kernel.h"
55 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
56 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
57 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
58 extern afs_int32 afs_termState;
60 # include "sys/lockl.h"
61 # include "sys/lock_def.h"
62 # endif /* AFS_AIX41_ENV */
63 # include "afs/rxgen_consts.h"
68 # include <afs/afsutil.h>
69 # include <WINNT\afsreg.h>
78 #include "rx_atomic.h"
79 #include "rx_globals.h"
81 #include "rx_internal.h"
84 #include <afs/rxgen_consts.h>
87 #ifdef AFS_PTHREAD_ENV
89 int (*registerProgram) (pid_t, char *) = 0;
90 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
93 int (*registerProgram) (PROCESS, char *) = 0;
94 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
98 /* Local static routines */
99 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
100 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
101 struct rx_peer *, struct clock *);
103 #ifdef RX_ENABLE_LOCKS
104 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
107 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
109 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
110 rx_atomic_t rxi_start_in_error;
112 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
115 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
116 * currently allocated within rx. This number is used to allocate the
117 * memory required to return the statistics when queried.
118 * Protected by the rx_rpc_stats mutex.
121 static unsigned int rxi_rpc_peer_stat_cnt;
124 * rxi_rpc_process_stat_cnt counts the total number of local process stat
125 * structures currently allocated within rx. The number is used to allocate
126 * the memory required to return the statistics when queried.
127 * Protected by the rx_rpc_stats mutex.
130 static unsigned int rxi_rpc_process_stat_cnt;
133 * rxi_busyChannelError is the error to return to the application when a call
134 * channel appears busy (inferred from the receipt of RX_PACKET_TYPE_BUSY
135 * packets on the channel), and there are other call channels in the
136 * connection that are not busy. If 0, we do not return errors upon receiving
137 * busy packets; we just keep trying on the same call channel until we hit a
140 static afs_int32 rxi_busyChannelError = 0;
142 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
143 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
145 #if !defined(offsetof)
146 #include <stddef.h> /* for definition of offsetof() */
149 #ifdef RX_ENABLE_LOCKS
150 afs_kmutex_t rx_atomic_mutex;
153 #ifdef AFS_PTHREAD_ENV
156 * Use procedural initialization of mutexes/condition variables
160 extern afs_kmutex_t rx_quota_mutex;
161 extern afs_kmutex_t rx_pthread_mutex;
162 extern afs_kmutex_t rx_packets_mutex;
163 extern afs_kmutex_t rx_refcnt_mutex;
164 extern afs_kmutex_t des_init_mutex;
165 extern afs_kmutex_t des_random_mutex;
166 extern afs_kmutex_t rx_clock_mutex;
167 extern afs_kmutex_t rxi_connCacheMutex;
168 extern afs_kmutex_t rx_event_mutex;
169 extern afs_kmutex_t event_handler_mutex;
170 extern afs_kmutex_t listener_mutex;
171 extern afs_kmutex_t rx_if_init_mutex;
172 extern afs_kmutex_t rx_if_mutex;
173 extern afs_kmutex_t rxkad_client_uid_mutex;
174 extern afs_kmutex_t rxkad_random_mutex;
176 extern afs_kcondvar_t rx_event_handler_cond;
177 extern afs_kcondvar_t rx_listener_cond;
179 static afs_kmutex_t epoch_mutex;
180 static afs_kmutex_t rx_init_mutex;
181 static afs_kmutex_t rx_debug_mutex;
182 static afs_kmutex_t rx_rpc_stats;
185 rxi_InitPthread(void)
187 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
188 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
189 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
190 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
191 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
192 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
193 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
194 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
206 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
207 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
209 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
210 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
212 rxkad_global_stats_init();
214 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
216 #ifdef RX_ENABLE_LOCKS
219 #endif /* RX_LOCKS_DB */
220 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
223 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
225 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
227 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
229 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
230 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
231 #endif /* RX_ENABLE_LOCKS */
234 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
235 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
237 * The rx_stats_mutex mutex protects the following global variables:
238 * rxi_lowConnRefCount
239 * rxi_lowPeerRefCount
248 * The rx_quota_mutex mutex protects the following global variables:
256 * The rx_freePktQ_lock protects the following global variables:
261 * The rx_packets_mutex mutex protects the following global variables:
269 * The rx_pthread_mutex mutex protects the following global variables:
270 * rxi_fcfs_thread_num
273 #define INIT_PTHREAD_LOCKS
277 /* Variables for handling the minProcs implementation. availProcs gives the
278 * number of threads available in the pool at this moment (not counting dudes
279 * executing right now). totalMin gives the total number of procs required
280 * for handling all minProcs requests. minDeficit is a dynamic variable
281 * tracking the # of procs required to satisfy all of the remaining minProcs
283 * For fine grain locking to work, the quota check and the reservation of
284 * a server thread has to come while rxi_availProcs and rxi_minDeficit
285 * are locked. To this end, the code has been modified under #ifdef
286 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
287 * same time. A new function, ReturnToServerPool() returns the allocation.
289 * A call can be on several queue's (but only one at a time). When
290 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
291 * that no one else is touching the queue. To this end, we store the address
292 * of the queue lock in the call structure (under the call lock) when we
293 * put the call on a queue, and we clear the call_queue_lock when the
294 * call is removed from a queue (once the call lock has been obtained).
295 * This allows rxi_ResetCall to safely synchronize with others wishing
296 * to manipulate the queue.
299 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
300 static afs_kmutex_t rx_rpc_stats;
301 void rxi_StartUnlocked(struct rxevent *event, void *call,
302 void *arg1, int istack);
305 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
306 ** pretty good that the next packet coming in is from the same connection
307 ** as the last packet, since we're send multiple packets in a transmit window.
309 struct rx_connection *rxLastConn = 0;
311 #ifdef RX_ENABLE_LOCKS
312 /* The locking hierarchy for rx fine grain locking is composed of these
315 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
316 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
317 * call->lock - locks call data fields.
318 * These are independent of each other:
319 * rx_freeCallQueue_lock
324 * serverQueueEntry->lock
325 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
327 * peer->lock - locks peer data fields.
328 * conn_data_lock - that more than one thread is not updating a conn data
329 * field at the same time.
340 * Do we need a lock to protect the peer field in the conn structure?
341 * conn->peer was previously a constant for all intents and so has no
342 * lock protecting this field. The multihomed client delta introduced
343 * a RX code change : change the peer field in the connection structure
344 * to that remote interface from which the last packet for this
345 * connection was sent out. This may become an issue if further changes
348 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
349 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
351 /* rxdb_fileID is used to identify the lock location, along with line#. */
352 static int rxdb_fileID = RXDB_FILE_RX;
353 #endif /* RX_LOCKS_DB */
354 #else /* RX_ENABLE_LOCKS */
355 #define SET_CALL_QUEUE_LOCK(C, L)
356 #define CLEAR_CALL_QUEUE_LOCK(C)
357 #endif /* RX_ENABLE_LOCKS */
358 struct rx_serverQueueEntry *rx_waitForPacket = 0;
359 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
361 /* ------------Exported Interfaces------------- */
363 /* This function allows rxkad to set the epoch to a suitably random number
364 * which rx_NewConnection will use in the future. The principle purpose is to
365 * get rxnull connections to use the same epoch as the rxkad connections do, at
366 * least once the first rxkad connection is established. This is important now
367 * that the host/port addresses aren't used in FindConnection: the uniqueness
368 * of epoch/cid matters and the start time won't do. */
370 #ifdef AFS_PTHREAD_ENV
372 * This mutex protects the following global variables:
376 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
377 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
381 #endif /* AFS_PTHREAD_ENV */
384 rx_SetEpoch(afs_uint32 epoch)
391 /* Initialize rx. A port number may be mentioned, in which case this
392 * becomes the default port number for any service installed later.
393 * If 0 is provided for the port number, a random port will be chosen
394 * by the kernel. Whether this will ever overlap anything in
395 * /etc/services is anybody's guess... Returns 0 on success, -1 on
400 int rxinit_status = 1;
401 #ifdef AFS_PTHREAD_ENV
403 * This mutex protects the following global variables:
407 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
408 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
411 #define UNLOCK_RX_INIT
415 rx_InitHost(u_int host, u_int port)
422 char *htable, *ptable;
429 if (rxinit_status == 0) {
430 tmp_status = rxinit_status;
432 return tmp_status; /* Already started; return previous error code. */
438 if (afs_winsockInit() < 0)
444 * Initialize anything necessary to provide a non-premptive threading
447 rxi_InitializeThreadSupport();
450 /* Allocate and initialize a socket for client and perhaps server
453 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
454 if (rx_socket == OSI_NULLSOCKET) {
458 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
461 #endif /* RX_LOCKS_DB */
462 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
463 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
464 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
465 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
466 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
467 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
468 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
469 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
470 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
472 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
474 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
476 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
478 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
479 #if defined(AFS_HPUX110_ENV)
481 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
482 #endif /* AFS_HPUX110_ENV */
483 #endif /* RX_ENABLE_LOCKS && KERNEL */
486 rx_connDeadTime = 12;
487 rx_tranquil = 0; /* reset flag */
488 rxi_ResetStatistics();
490 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
491 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
492 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
493 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
494 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
495 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
497 /* Malloc up a bunch of packets & buffers */
499 queue_Init(&rx_freePacketQueue);
500 rxi_NeedMorePackets = FALSE;
501 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
503 /* enforce a minimum number of allocated packets */
504 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
505 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
507 /* allocate the initial free packet pool */
508 #ifdef RX_ENABLE_TSFPQ
509 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
510 #else /* RX_ENABLE_TSFPQ */
511 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
512 #endif /* RX_ENABLE_TSFPQ */
519 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
520 tv.tv_sec = clock_now.sec;
521 tv.tv_usec = clock_now.usec;
522 srand((unsigned int)tv.tv_usec);
529 #if defined(KERNEL) && !defined(UKERNEL)
530 /* Really, this should never happen in a real kernel */
533 struct sockaddr_in addr;
535 int addrlen = sizeof(addr);
537 socklen_t addrlen = sizeof(addr);
539 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
543 rx_port = addr.sin_port;
546 rx_stats.minRtt.sec = 9999999;
548 rx_SetEpoch(tv.tv_sec | 0x80000000);
550 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
551 * will provide a randomer value. */
553 MUTEX_ENTER(&rx_quota_mutex);
554 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
555 MUTEX_EXIT(&rx_quota_mutex);
556 /* *Slightly* random start time for the cid. This is just to help
557 * out with the hashing function at the peer */
558 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
559 rx_connHashTable = (struct rx_connection **)htable;
560 rx_peerHashTable = (struct rx_peer **)ptable;
562 rx_lastAckDelay.sec = 0;
563 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
564 rx_hardAckDelay.sec = 0;
565 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
566 rx_softAckDelay.sec = 0;
567 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
569 rxevent_Init(20, rxi_ReScheduleEvents);
571 /* Initialize various global queues */
572 queue_Init(&rx_idleServerQueue);
573 queue_Init(&rx_incomingCallQueue);
574 queue_Init(&rx_freeCallQueue);
576 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
577 /* Initialize our list of usable IP addresses. */
581 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
582 /* Start listener process (exact function is dependent on the
583 * implementation environment--kernel or user space) */
588 tmp_status = rxinit_status = 0;
596 return rx_InitHost(htonl(INADDR_ANY), port);
600 * Sets the error generated when a busy call channel is detected.
602 * @param[in] error The error to return for a call on a busy channel.
604 * @pre Neither rx_Init nor rx_InitHost have been called yet
607 rx_SetBusyChannelError(afs_int32 error)
609 osi_Assert(rxinit_status != 0);
610 rxi_busyChannelError = error;
613 /* called with unincremented nRequestsRunning to see if it is OK to start
614 * a new thread in this service. Could be "no" for two reasons: over the
615 * max quota, or would prevent others from reaching their min quota.
617 #ifdef RX_ENABLE_LOCKS
618 /* This verion of QuotaOK reserves quota if it's ok while the
619 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
622 QuotaOK(struct rx_service *aservice)
624 /* check if over max quota */
625 if (aservice->nRequestsRunning >= aservice->maxProcs) {
629 /* under min quota, we're OK */
630 /* otherwise, can use only if there are enough to allow everyone
631 * to go to their min quota after this guy starts.
634 MUTEX_ENTER(&rx_quota_mutex);
635 if ((aservice->nRequestsRunning < aservice->minProcs)
636 || (rxi_availProcs > rxi_minDeficit)) {
637 aservice->nRequestsRunning++;
638 /* just started call in minProcs pool, need fewer to maintain
640 if (aservice->nRequestsRunning <= aservice->minProcs)
643 MUTEX_EXIT(&rx_quota_mutex);
646 MUTEX_EXIT(&rx_quota_mutex);
652 ReturnToServerPool(struct rx_service *aservice)
654 aservice->nRequestsRunning--;
655 MUTEX_ENTER(&rx_quota_mutex);
656 if (aservice->nRequestsRunning < aservice->minProcs)
659 MUTEX_EXIT(&rx_quota_mutex);
662 #else /* RX_ENABLE_LOCKS */
664 QuotaOK(struct rx_service *aservice)
667 /* under min quota, we're OK */
668 if (aservice->nRequestsRunning < aservice->minProcs)
671 /* check if over max quota */
672 if (aservice->nRequestsRunning >= aservice->maxProcs)
675 /* otherwise, can use only if there are enough to allow everyone
676 * to go to their min quota after this guy starts.
678 MUTEX_ENTER(&rx_quota_mutex);
679 if (rxi_availProcs > rxi_minDeficit)
681 MUTEX_EXIT(&rx_quota_mutex);
684 #endif /* RX_ENABLE_LOCKS */
687 /* Called by rx_StartServer to start up lwp's to service calls.
688 NExistingProcs gives the number of procs already existing, and which
689 therefore needn't be created. */
691 rxi_StartServerProcs(int nExistingProcs)
693 struct rx_service *service;
698 /* For each service, reserve N processes, where N is the "minimum"
699 * number of processes that MUST be able to execute a request in parallel,
700 * at any time, for that process. Also compute the maximum difference
701 * between any service's maximum number of processes that can run
702 * (i.e. the maximum number that ever will be run, and a guarantee
703 * that this number will run if other services aren't running), and its
704 * minimum number. The result is the extra number of processes that
705 * we need in order to provide the latter guarantee */
706 for (i = 0; i < RX_MAX_SERVICES; i++) {
708 service = rx_services[i];
709 if (service == (struct rx_service *)0)
711 nProcs += service->minProcs;
712 diff = service->maxProcs - service->minProcs;
716 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
717 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
718 for (i = 0; i < nProcs; i++) {
719 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
725 /* This routine is only required on Windows */
727 rx_StartClientThread(void)
729 #ifdef AFS_PTHREAD_ENV
731 pid = pthread_self();
732 #endif /* AFS_PTHREAD_ENV */
734 #endif /* AFS_NT40_ENV */
736 /* This routine must be called if any services are exported. If the
737 * donateMe flag is set, the calling process is donated to the server
740 rx_StartServer(int donateMe)
742 struct rx_service *service;
748 /* Start server processes, if necessary (exact function is dependent
749 * on the implementation environment--kernel or user space). DonateMe
750 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
751 * case, one less new proc will be created rx_StartServerProcs.
753 rxi_StartServerProcs(donateMe);
755 /* count up the # of threads in minProcs, and add set the min deficit to
756 * be that value, too.
758 for (i = 0; i < RX_MAX_SERVICES; i++) {
759 service = rx_services[i];
760 if (service == (struct rx_service *)0)
762 MUTEX_ENTER(&rx_quota_mutex);
763 rxi_totalMin += service->minProcs;
764 /* below works even if a thread is running, since minDeficit would
765 * still have been decremented and later re-incremented.
767 rxi_minDeficit += service->minProcs;
768 MUTEX_EXIT(&rx_quota_mutex);
771 /* Turn on reaping of idle server connections */
772 rxi_ReapConnections(NULL, NULL, NULL);
781 #ifdef AFS_PTHREAD_ENV
783 pid = afs_pointer_to_int(pthread_self());
784 #else /* AFS_PTHREAD_ENV */
786 LWP_CurrentProcess(&pid);
787 #endif /* AFS_PTHREAD_ENV */
789 sprintf(name, "srv_%d", ++nProcs);
791 (*registerProgram) (pid, name);
793 #endif /* AFS_NT40_ENV */
794 rx_ServerProc(NULL); /* Never returns */
796 #ifdef RX_ENABLE_TSFPQ
797 /* no use leaving packets around in this thread's local queue if
798 * it isn't getting donated to the server thread pool.
800 rxi_FlushLocalPacketsTSFPQ();
801 #endif /* RX_ENABLE_TSFPQ */
805 /* Create a new client connection to the specified service, using the
806 * specified security object to implement the security model for this
808 struct rx_connection *
809 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
810 struct rx_securityClass *securityObject,
811 int serviceSecurityIndex)
815 struct rx_connection *conn;
820 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
821 "serviceSecurityIndex %d)\n",
822 ntohl(shost), ntohs(sport), sservice, securityObject,
823 serviceSecurityIndex));
825 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
826 * the case of kmem_alloc? */
827 conn = rxi_AllocConnection();
828 #ifdef RX_ENABLE_LOCKS
829 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
830 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
831 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
834 MUTEX_ENTER(&rx_connHashTable_lock);
835 cid = (rx_nextCid += RX_MAXCALLS);
836 conn->type = RX_CLIENT_CONNECTION;
838 conn->epoch = rx_epoch;
839 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
840 conn->serviceId = sservice;
841 conn->securityObject = securityObject;
842 conn->securityData = (void *) 0;
843 conn->securityIndex = serviceSecurityIndex;
844 rx_SetConnDeadTime(conn, rx_connDeadTime);
845 rx_SetConnSecondsUntilNatPing(conn, 0);
846 conn->ackRate = RX_FAST_ACK_RATE;
848 conn->specific = NULL;
849 conn->challengeEvent = NULL;
850 conn->delayedAbortEvent = NULL;
851 conn->abortCount = 0;
853 for (i = 0; i < RX_MAXCALLS; i++) {
854 conn->twind[i] = rx_initSendWindow;
855 conn->rwind[i] = rx_initReceiveWindow;
856 conn->lastBusy[i] = 0;
859 RXS_NewConnection(securityObject, conn);
861 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
863 conn->refCount++; /* no lock required since only this thread knows... */
864 conn->next = rx_connHashTable[hashindex];
865 rx_connHashTable[hashindex] = conn;
867 rx_atomic_inc(&rx_stats.nClientConns);
868 MUTEX_EXIT(&rx_connHashTable_lock);
874 * Ensure a connection's timeout values are valid.
876 * @param[in] conn The connection to check
878 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
879 * unless idleDeadTime and/or hardDeadTime are not set
883 rxi_CheckConnTimeouts(struct rx_connection *conn)
885 /* a connection's timeouts must have the relationship
886 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
887 * total loss of network to a peer may cause an idle timeout instead of a
888 * dead timeout, simply because the idle timeout gets hit first. Also set
889 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
890 /* this logic is slightly complicated by the fact that
891 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
893 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
894 if (conn->idleDeadTime) {
895 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
897 if (conn->hardDeadTime) {
898 if (conn->idleDeadTime) {
899 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
901 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
907 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
909 /* The idea is to set the dead time to a value that allows several
910 * keepalives to be dropped without timing out the connection. */
911 conn->secondsUntilDead = seconds;
912 rxi_CheckConnTimeouts(conn);
913 conn->secondsUntilPing = conn->secondsUntilDead / 6;
917 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
919 conn->hardDeadTime = seconds;
920 rxi_CheckConnTimeouts(conn);
924 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
926 conn->idleDeadTime = seconds;
927 rxi_CheckConnTimeouts(conn);
930 int rxi_lowPeerRefCount = 0;
931 int rxi_lowConnRefCount = 0;
934 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
935 * NOTE: must not be called with rx_connHashTable_lock held.
938 rxi_CleanupConnection(struct rx_connection *conn)
940 /* Notify the service exporter, if requested, that this connection
941 * is being destroyed */
942 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
943 (*conn->service->destroyConnProc) (conn);
945 /* Notify the security module that this connection is being destroyed */
946 RXS_DestroyConnection(conn->securityObject, conn);
948 /* If this is the last connection using the rx_peer struct, set its
949 * idle time to now. rxi_ReapConnections will reap it if it's still
950 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
952 MUTEX_ENTER(&rx_peerHashTable_lock);
953 if (conn->peer->refCount < 2) {
954 conn->peer->idleWhen = clock_Sec();
955 if (conn->peer->refCount < 1) {
956 conn->peer->refCount = 1;
957 if (rx_stats_active) {
958 MUTEX_ENTER(&rx_stats_mutex);
959 rxi_lowPeerRefCount++;
960 MUTEX_EXIT(&rx_stats_mutex);
964 conn->peer->refCount--;
965 MUTEX_EXIT(&rx_peerHashTable_lock);
969 if (conn->type == RX_SERVER_CONNECTION)
970 rx_atomic_dec(&rx_stats.nServerConns);
972 rx_atomic_dec(&rx_stats.nClientConns);
975 if (conn->specific) {
977 for (i = 0; i < conn->nSpecific; i++) {
978 if (conn->specific[i] && rxi_keyCreate_destructor[i])
979 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
980 conn->specific[i] = NULL;
982 free(conn->specific);
984 conn->specific = NULL;
988 MUTEX_DESTROY(&conn->conn_call_lock);
989 MUTEX_DESTROY(&conn->conn_data_lock);
990 CV_DESTROY(&conn->conn_call_cv);
992 rxi_FreeConnection(conn);
995 /* Destroy the specified connection */
997 rxi_DestroyConnection(struct rx_connection *conn)
999 MUTEX_ENTER(&rx_connHashTable_lock);
1000 rxi_DestroyConnectionNoLock(conn);
1001 /* conn should be at the head of the cleanup list */
1002 if (conn == rx_connCleanup_list) {
1003 rx_connCleanup_list = rx_connCleanup_list->next;
1004 MUTEX_EXIT(&rx_connHashTable_lock);
1005 rxi_CleanupConnection(conn);
1007 #ifdef RX_ENABLE_LOCKS
1009 MUTEX_EXIT(&rx_connHashTable_lock);
1011 #endif /* RX_ENABLE_LOCKS */
1015 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1017 struct rx_connection **conn_ptr;
1019 struct rx_packet *packet;
1026 MUTEX_ENTER(&conn->conn_data_lock);
1027 MUTEX_ENTER(&rx_refcnt_mutex);
1028 if (conn->refCount > 0)
1031 if (rx_stats_active) {
1032 MUTEX_ENTER(&rx_stats_mutex);
1033 rxi_lowConnRefCount++;
1034 MUTEX_EXIT(&rx_stats_mutex);
1038 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1039 /* Busy; wait till the last guy before proceeding */
1040 MUTEX_EXIT(&rx_refcnt_mutex);
1041 MUTEX_EXIT(&conn->conn_data_lock);
1046 /* If the client previously called rx_NewCall, but it is still
1047 * waiting, treat this as a running call, and wait to destroy the
1048 * connection later when the call completes. */
1049 if ((conn->type == RX_CLIENT_CONNECTION)
1050 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1051 conn->flags |= RX_CONN_DESTROY_ME;
1052 MUTEX_EXIT(&conn->conn_data_lock);
1056 MUTEX_EXIT(&rx_refcnt_mutex);
1057 MUTEX_EXIT(&conn->conn_data_lock);
1059 /* Check for extant references to this connection */
1060 for (i = 0; i < RX_MAXCALLS; i++) {
1061 struct rx_call *call = conn->call[i];
1064 if (conn->type == RX_CLIENT_CONNECTION) {
1065 MUTEX_ENTER(&call->lock);
1066 if (call->delayedAckEvent) {
1067 /* Push the final acknowledgment out now--there
1068 * won't be a subsequent call to acknowledge the
1069 * last reply packets */
1070 rxevent_Cancel(call->delayedAckEvent, call,
1071 RX_CALL_REFCOUNT_DELAY);
1072 if (call->state == RX_STATE_PRECALL
1073 || call->state == RX_STATE_ACTIVE) {
1074 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1076 rxi_AckAll(NULL, call, 0);
1079 MUTEX_EXIT(&call->lock);
1083 #ifdef RX_ENABLE_LOCKS
1085 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1086 MUTEX_EXIT(&conn->conn_data_lock);
1088 /* Someone is accessing a packet right now. */
1092 #endif /* RX_ENABLE_LOCKS */
1095 /* Don't destroy the connection if there are any call
1096 * structures still in use */
1097 MUTEX_ENTER(&conn->conn_data_lock);
1098 conn->flags |= RX_CONN_DESTROY_ME;
1099 MUTEX_EXIT(&conn->conn_data_lock);
1104 if (conn->natKeepAliveEvent) {
1105 rxi_NatKeepAliveOff(conn);
1108 if (conn->delayedAbortEvent) {
1109 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1110 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1112 MUTEX_ENTER(&conn->conn_data_lock);
1113 rxi_SendConnectionAbort(conn, packet, 0, 1);
1114 MUTEX_EXIT(&conn->conn_data_lock);
1115 rxi_FreePacket(packet);
1119 /* Remove from connection hash table before proceeding */
1121 &rx_connHashTable[CONN_HASH
1122 (peer->host, peer->port, conn->cid, conn->epoch,
1124 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1125 if (*conn_ptr == conn) {
1126 *conn_ptr = conn->next;
1130 /* if the conn that we are destroying was the last connection, then we
1131 * clear rxLastConn as well */
1132 if (rxLastConn == conn)
1135 /* Make sure the connection is completely reset before deleting it. */
1136 /* get rid of pending events that could zap us later */
1137 if (conn->challengeEvent)
1138 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1139 if (conn->checkReachEvent)
1140 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1141 if (conn->natKeepAliveEvent)
1142 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1144 /* Add the connection to the list of destroyed connections that
1145 * need to be cleaned up. This is necessary to avoid deadlocks
1146 * in the routines we call to inform others that this connection is
1147 * being destroyed. */
1148 conn->next = rx_connCleanup_list;
1149 rx_connCleanup_list = conn;
1152 /* Externally available version */
1154 rx_DestroyConnection(struct rx_connection *conn)
1159 rxi_DestroyConnection(conn);
1164 rx_GetConnection(struct rx_connection *conn)
1169 MUTEX_ENTER(&rx_refcnt_mutex);
1171 MUTEX_EXIT(&rx_refcnt_mutex);
1175 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1176 /* Wait for the transmit queue to no longer be busy.
1177 * requires the call->lock to be held */
1179 rxi_WaitforTQBusy(struct rx_call *call) {
1180 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1181 call->flags |= RX_CALL_TQ_WAIT;
1183 #ifdef RX_ENABLE_LOCKS
1184 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1185 CV_WAIT(&call->cv_tq, &call->lock);
1186 #else /* RX_ENABLE_LOCKS */
1187 osi_rxSleep(&call->tq);
1188 #endif /* RX_ENABLE_LOCKS */
1190 if (call->tqWaiters == 0) {
1191 call->flags &= ~RX_CALL_TQ_WAIT;
1198 rxi_WakeUpTransmitQueue(struct rx_call *call)
1200 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1201 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1202 call, call->tqWaiters, call->flags));
1203 #ifdef RX_ENABLE_LOCKS
1204 osirx_AssertMine(&call->lock, "rxi_Start start");
1205 CV_BROADCAST(&call->cv_tq);
1206 #else /* RX_ENABLE_LOCKS */
1207 osi_rxWakeup(&call->tq);
1208 #endif /* RX_ENABLE_LOCKS */
1212 /* Start a new rx remote procedure call, on the specified connection.
1213 * If wait is set to 1, wait for a free call channel; otherwise return
1214 * 0. Maxtime gives the maximum number of seconds this call may take,
1215 * after rx_NewCall returns. After this time interval, a call to any
1216 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1217 * For fine grain locking, we hold the conn_call_lock in order to
1218 * to ensure that we don't get signalle after we found a call in an active
1219 * state and before we go to sleep.
1222 rx_NewCall(struct rx_connection *conn)
1224 int i, wait, ignoreBusy = 1;
1225 struct rx_call *call;
1226 struct clock queueTime;
1227 afs_uint32 leastBusy = 0;
1231 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1234 clock_GetTime(&queueTime);
1236 * Check if there are others waiting for a new call.
1237 * If so, let them go first to avoid starving them.
1238 * This is a fairly simple scheme, and might not be
1239 * a complete solution for large numbers of waiters.
1241 * makeCallWaiters keeps track of the number of
1242 * threads waiting to make calls and the
1243 * RX_CONN_MAKECALL_WAITING flag bit is used to
1244 * indicate that there are indeed calls waiting.
1245 * The flag is set when the waiter is incremented.
1246 * It is only cleared when makeCallWaiters is 0.
1247 * This prevents us from accidently destroying the
1248 * connection while it is potentially about to be used.
1250 MUTEX_ENTER(&conn->conn_call_lock);
1251 MUTEX_ENTER(&conn->conn_data_lock);
1252 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1253 conn->flags |= RX_CONN_MAKECALL_WAITING;
1254 conn->makeCallWaiters++;
1255 MUTEX_EXIT(&conn->conn_data_lock);
1257 #ifdef RX_ENABLE_LOCKS
1258 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1262 MUTEX_ENTER(&conn->conn_data_lock);
1263 conn->makeCallWaiters--;
1264 if (conn->makeCallWaiters == 0)
1265 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1268 /* We are now the active thread in rx_NewCall */
1269 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1270 MUTEX_EXIT(&conn->conn_data_lock);
1275 for (i = 0; i < RX_MAXCALLS; i++) {
1276 call = conn->call[i];
1278 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1279 /* we're not ignoring busy call slots; only look at the
1280 * call slot that is the "least" busy */
1284 if (call->state == RX_STATE_DALLY) {
1285 MUTEX_ENTER(&call->lock);
1286 if (call->state == RX_STATE_DALLY) {
1287 if (ignoreBusy && conn->lastBusy[i]) {
1288 /* if we're ignoring busy call slots, skip any ones that
1289 * have lastBusy set */
1290 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1291 leastBusy = conn->lastBusy[i];
1293 MUTEX_EXIT(&call->lock);
1298 * We are setting the state to RX_STATE_RESET to
1299 * ensure that no one else will attempt to use this
1300 * call once we drop the conn->conn_call_lock and
1301 * call->lock. We must drop the conn->conn_call_lock
1302 * before calling rxi_ResetCall because the process
1303 * of clearing the transmit queue can block for an
1304 * extended period of time. If we block while holding
1305 * the conn->conn_call_lock, then all rx_EndCall
1306 * processing will block as well. This has a detrimental
1307 * effect on overall system performance.
1309 call->state = RX_STATE_RESET;
1310 MUTEX_EXIT(&conn->conn_call_lock);
1311 MUTEX_ENTER(&rx_refcnt_mutex);
1312 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1313 MUTEX_EXIT(&rx_refcnt_mutex);
1314 rxi_ResetCall(call, 0);
1315 (*call->callNumber)++;
1316 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1320 * If we failed to be able to safely obtain the
1321 * conn->conn_call_lock we will have to drop the
1322 * call->lock to avoid a deadlock. When the call->lock
1323 * is released the state of the call can change. If it
1324 * is no longer RX_STATE_RESET then some other thread is
1327 MUTEX_EXIT(&call->lock);
1328 MUTEX_ENTER(&conn->conn_call_lock);
1329 MUTEX_ENTER(&call->lock);
1331 if (call->state == RX_STATE_RESET)
1335 * If we get here it means that after dropping
1336 * the conn->conn_call_lock and call->lock that
1337 * the call is no longer ours. If we can't find
1338 * a free call in the remaining slots we should
1339 * not go immediately to RX_CONN_MAKECALL_WAITING
1340 * because by dropping the conn->conn_call_lock
1341 * we have given up synchronization with rx_EndCall.
1342 * Instead, cycle through one more time to see if
1343 * we can find a call that can call our own.
1345 MUTEX_ENTER(&rx_refcnt_mutex);
1346 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1347 MUTEX_EXIT(&rx_refcnt_mutex);
1350 MUTEX_EXIT(&call->lock);
1353 if (ignoreBusy && conn->lastBusy[i]) {
1354 /* if we're ignoring busy call slots, skip any ones that
1355 * have lastBusy set */
1356 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1357 leastBusy = conn->lastBusy[i];
1362 /* rxi_NewCall returns with mutex locked */
1363 call = rxi_NewCall(conn, i);
1364 MUTEX_ENTER(&rx_refcnt_mutex);
1365 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1366 MUTEX_EXIT(&rx_refcnt_mutex);
1370 if (i < RX_MAXCALLS) {
1371 conn->lastBusy[i] = 0;
1376 if (leastBusy && ignoreBusy) {
1377 /* we didn't find a useable call slot, but we did see at least one
1378 * 'busy' slot; look again and only use a slot with the 'least
1384 MUTEX_ENTER(&conn->conn_data_lock);
1385 conn->flags |= RX_CONN_MAKECALL_WAITING;
1386 conn->makeCallWaiters++;
1387 MUTEX_EXIT(&conn->conn_data_lock);
1389 #ifdef RX_ENABLE_LOCKS
1390 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1394 MUTEX_ENTER(&conn->conn_data_lock);
1395 conn->makeCallWaiters--;
1396 if (conn->makeCallWaiters == 0)
1397 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1398 MUTEX_EXIT(&conn->conn_data_lock);
1400 /* Client is initially in send mode */
1401 call->state = RX_STATE_ACTIVE;
1402 call->error = conn->error;
1404 call->mode = RX_MODE_ERROR;
1406 call->mode = RX_MODE_SENDING;
1408 /* remember start time for call in case we have hard dead time limit */
1409 call->queueTime = queueTime;
1410 clock_GetTime(&call->startTime);
1411 hzero(call->bytesSent);
1412 hzero(call->bytesRcvd);
1414 /* Turn on busy protocol. */
1415 rxi_KeepAliveOn(call);
1417 /* Attempt MTU discovery */
1418 rxi_GrowMTUOn(call);
1421 * We are no longer the active thread in rx_NewCall
1423 MUTEX_ENTER(&conn->conn_data_lock);
1424 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1425 MUTEX_EXIT(&conn->conn_data_lock);
1428 * Wake up anyone else who might be giving us a chance to
1429 * run (see code above that avoids resource starvation).
1431 #ifdef RX_ENABLE_LOCKS
1432 CV_BROADCAST(&conn->conn_call_cv);
1436 MUTEX_EXIT(&conn->conn_call_lock);
1438 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1439 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1440 osi_Panic("rx_NewCall call about to be used without an empty tq");
1442 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1444 MUTEX_EXIT(&call->lock);
1447 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1452 rxi_HasActiveCalls(struct rx_connection *aconn)
1455 struct rx_call *tcall;
1459 for (i = 0; i < RX_MAXCALLS; i++) {
1460 if ((tcall = aconn->call[i])) {
1461 if ((tcall->state == RX_STATE_ACTIVE)
1462 || (tcall->state == RX_STATE_PRECALL)) {
1473 rxi_GetCallNumberVector(struct rx_connection *aconn,
1474 afs_int32 * aint32s)
1477 struct rx_call *tcall;
1481 for (i = 0; i < RX_MAXCALLS; i++) {
1482 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1483 aint32s[i] = aconn->callNumber[i] + 1;
1485 aint32s[i] = aconn->callNumber[i];
1492 rxi_SetCallNumberVector(struct rx_connection *aconn,
1493 afs_int32 * aint32s)
1496 struct rx_call *tcall;
1500 for (i = 0; i < RX_MAXCALLS; i++) {
1501 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1502 aconn->callNumber[i] = aint32s[i] - 1;
1504 aconn->callNumber[i] = aint32s[i];
1510 /* Advertise a new service. A service is named locally by a UDP port
1511 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1514 char *serviceName; Name for identification purposes (e.g. the
1515 service name might be used for probing for
1518 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1519 char *serviceName, struct rx_securityClass **securityObjects,
1520 int nSecurityObjects,
1521 afs_int32(*serviceProc) (struct rx_call * acall))
1523 osi_socket socket = OSI_NULLSOCKET;
1524 struct rx_service *tservice;
1530 if (serviceId == 0) {
1532 "rx_NewService: service id for service %s is not non-zero.\n",
1539 "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",
1547 tservice = rxi_AllocService();
1550 #ifdef RX_ENABLE_LOCKS
1551 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1554 for (i = 0; i < RX_MAX_SERVICES; i++) {
1555 struct rx_service *service = rx_services[i];
1557 if (port == service->servicePort && host == service->serviceHost) {
1558 if (service->serviceId == serviceId) {
1559 /* The identical service has already been
1560 * installed; if the caller was intending to
1561 * change the security classes used by this
1562 * service, he/she loses. */
1564 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1565 serviceName, serviceId, service->serviceName);
1567 rxi_FreeService(tservice);
1570 /* Different service, same port: re-use the socket
1571 * which is bound to the same port */
1572 socket = service->socket;
1575 if (socket == OSI_NULLSOCKET) {
1576 /* If we don't already have a socket (from another
1577 * service on same port) get a new one */
1578 socket = rxi_GetHostUDPSocket(host, port);
1579 if (socket == OSI_NULLSOCKET) {
1581 rxi_FreeService(tservice);
1586 service->socket = socket;
1587 service->serviceHost = host;
1588 service->servicePort = port;
1589 service->serviceId = serviceId;
1590 service->serviceName = serviceName;
1591 service->nSecurityObjects = nSecurityObjects;
1592 service->securityObjects = securityObjects;
1593 service->minProcs = 0;
1594 service->maxProcs = 1;
1595 service->idleDeadTime = 60;
1596 service->idleDeadErr = 0;
1597 service->connDeadTime = rx_connDeadTime;
1598 service->executeRequestProc = serviceProc;
1599 service->checkReach = 0;
1600 service->nSpecific = 0;
1601 service->specific = NULL;
1602 rx_services[i] = service; /* not visible until now */
1608 rxi_FreeService(tservice);
1609 (osi_Msg "rx_NewService: cannot support > %d services\n",
1614 /* Set configuration options for all of a service's security objects */
1617 rx_SetSecurityConfiguration(struct rx_service *service,
1618 rx_securityConfigVariables type,
1622 for (i = 0; i<service->nSecurityObjects; i++) {
1623 if (service->securityObjects[i]) {
1624 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1632 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1633 struct rx_securityClass **securityObjects, int nSecurityObjects,
1634 afs_int32(*serviceProc) (struct rx_call * acall))
1636 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1639 /* Generic request processing loop. This routine should be called
1640 * by the implementation dependent rx_ServerProc. If socketp is
1641 * non-null, it will be set to the file descriptor that this thread
1642 * is now listening on. If socketp is null, this routine will never
1645 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1647 struct rx_call *call;
1649 struct rx_service *tservice = NULL;
1656 call = rx_GetCall(threadID, tservice, socketp);
1657 if (socketp && *socketp != OSI_NULLSOCKET) {
1658 /* We are now a listener thread */
1663 /* if server is restarting( typically smooth shutdown) then do not
1664 * allow any new calls.
1667 if (rx_tranquil && (call != NULL)) {
1671 MUTEX_ENTER(&call->lock);
1673 rxi_CallError(call, RX_RESTARTING);
1674 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1676 MUTEX_EXIT(&call->lock);
1680 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1681 #ifdef RX_ENABLE_LOCKS
1683 #endif /* RX_ENABLE_LOCKS */
1684 afs_termState = AFSOP_STOP_AFS;
1685 afs_osi_Wakeup(&afs_termState);
1686 #ifdef RX_ENABLE_LOCKS
1688 #endif /* RX_ENABLE_LOCKS */
1693 tservice = call->conn->service;
1695 if (tservice->beforeProc)
1696 (*tservice->beforeProc) (call);
1698 code = tservice->executeRequestProc(call);
1700 if (tservice->afterProc)
1701 (*tservice->afterProc) (call, code);
1703 rx_EndCall(call, code);
1704 if (rx_stats_active) {
1705 MUTEX_ENTER(&rx_stats_mutex);
1707 MUTEX_EXIT(&rx_stats_mutex);
1714 rx_WakeupServerProcs(void)
1716 struct rx_serverQueueEntry *np, *tqp;
1720 MUTEX_ENTER(&rx_serverPool_lock);
1722 #ifdef RX_ENABLE_LOCKS
1723 if (rx_waitForPacket)
1724 CV_BROADCAST(&rx_waitForPacket->cv);
1725 #else /* RX_ENABLE_LOCKS */
1726 if (rx_waitForPacket)
1727 osi_rxWakeup(rx_waitForPacket);
1728 #endif /* RX_ENABLE_LOCKS */
1729 MUTEX_ENTER(&freeSQEList_lock);
1730 for (np = rx_FreeSQEList; np; np = tqp) {
1731 tqp = *(struct rx_serverQueueEntry **)np;
1732 #ifdef RX_ENABLE_LOCKS
1733 CV_BROADCAST(&np->cv);
1734 #else /* RX_ENABLE_LOCKS */
1736 #endif /* RX_ENABLE_LOCKS */
1738 MUTEX_EXIT(&freeSQEList_lock);
1739 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1740 #ifdef RX_ENABLE_LOCKS
1741 CV_BROADCAST(&np->cv);
1742 #else /* RX_ENABLE_LOCKS */
1744 #endif /* RX_ENABLE_LOCKS */
1746 MUTEX_EXIT(&rx_serverPool_lock);
1751 * One thing that seems to happen is that all the server threads get
1752 * tied up on some empty or slow call, and then a whole bunch of calls
1753 * arrive at once, using up the packet pool, so now there are more
1754 * empty calls. The most critical resources here are server threads
1755 * and the free packet pool. The "doreclaim" code seems to help in
1756 * general. I think that eventually we arrive in this state: there
1757 * are lots of pending calls which do have all their packets present,
1758 * so they won't be reclaimed, are multi-packet calls, so they won't
1759 * be scheduled until later, and thus are tying up most of the free
1760 * packet pool for a very long time.
1762 * 1. schedule multi-packet calls if all the packets are present.
1763 * Probably CPU-bound operation, useful to return packets to pool.
1764 * Do what if there is a full window, but the last packet isn't here?
1765 * 3. preserve one thread which *only* runs "best" calls, otherwise
1766 * it sleeps and waits for that type of call.
1767 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1768 * the current dataquota business is badly broken. The quota isn't adjusted
1769 * to reflect how many packets are presently queued for a running call.
1770 * So, when we schedule a queued call with a full window of packets queued
1771 * up for it, that *should* free up a window full of packets for other 2d-class
1772 * calls to be able to use from the packet pool. But it doesn't.
1774 * NB. Most of the time, this code doesn't run -- since idle server threads
1775 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1776 * as a new call arrives.
1778 /* Sleep until a call arrives. Returns a pointer to the call, ready
1779 * for an rx_Read. */
1780 #ifdef RX_ENABLE_LOCKS
1782 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1784 struct rx_serverQueueEntry *sq;
1785 struct rx_call *call = (struct rx_call *)0;
1786 struct rx_service *service = NULL;
1788 MUTEX_ENTER(&freeSQEList_lock);
1790 if ((sq = rx_FreeSQEList)) {
1791 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1792 MUTEX_EXIT(&freeSQEList_lock);
1793 } else { /* otherwise allocate a new one and return that */
1794 MUTEX_EXIT(&freeSQEList_lock);
1795 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1796 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1797 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1800 MUTEX_ENTER(&rx_serverPool_lock);
1801 if (cur_service != NULL) {
1802 ReturnToServerPool(cur_service);
1805 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1806 struct rx_call *tcall, *ncall, *choice2 = NULL;
1808 /* Scan for eligible incoming calls. A call is not eligible
1809 * if the maximum number of calls for its service type are
1810 * already executing */
1811 /* One thread will process calls FCFS (to prevent starvation),
1812 * while the other threads may run ahead looking for calls which
1813 * have all their input data available immediately. This helps
1814 * keep threads from blocking, waiting for data from the client. */
1815 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1816 service = tcall->conn->service;
1817 if (!QuotaOK(service)) {
1820 MUTEX_ENTER(&rx_pthread_mutex);
1821 if (tno == rxi_fcfs_thread_num
1822 || !tcall->queue_item_header.next) {
1823 MUTEX_EXIT(&rx_pthread_mutex);
1824 /* If we're the fcfs thread , then we'll just use
1825 * this call. If we haven't been able to find an optimal
1826 * choice, and we're at the end of the list, then use a
1827 * 2d choice if one has been identified. Otherwise... */
1828 call = (choice2 ? choice2 : tcall);
1829 service = call->conn->service;
1831 MUTEX_EXIT(&rx_pthread_mutex);
1832 if (!queue_IsEmpty(&tcall->rq)) {
1833 struct rx_packet *rp;
1834 rp = queue_First(&tcall->rq, rx_packet);
1835 if (rp->header.seq == 1) {
1837 || (rp->header.flags & RX_LAST_PACKET)) {
1839 } else if (rxi_2dchoice && !choice2
1840 && !(tcall->flags & RX_CALL_CLEARED)
1841 && (tcall->rprev > rxi_HardAckRate)) {
1851 ReturnToServerPool(service);
1858 MUTEX_EXIT(&rx_serverPool_lock);
1859 MUTEX_ENTER(&call->lock);
1861 if (call->flags & RX_CALL_WAIT_PROC) {
1862 call->flags &= ~RX_CALL_WAIT_PROC;
1863 rx_atomic_dec(&rx_nWaiting);
1866 if (call->state != RX_STATE_PRECALL || call->error) {
1867 MUTEX_EXIT(&call->lock);
1868 MUTEX_ENTER(&rx_serverPool_lock);
1869 ReturnToServerPool(service);
1874 if (queue_IsEmpty(&call->rq)
1875 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1876 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1878 CLEAR_CALL_QUEUE_LOCK(call);
1881 /* If there are no eligible incoming calls, add this process
1882 * to the idle server queue, to wait for one */
1886 *socketp = OSI_NULLSOCKET;
1888 sq->socketp = socketp;
1889 queue_Append(&rx_idleServerQueue, sq);
1890 #ifndef AFS_AIX41_ENV
1891 rx_waitForPacket = sq;
1893 rx_waitingForPacket = sq;
1894 #endif /* AFS_AIX41_ENV */
1896 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1898 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1899 MUTEX_EXIT(&rx_serverPool_lock);
1900 return (struct rx_call *)0;
1903 } while (!(call = sq->newcall)
1904 && !(socketp && *socketp != OSI_NULLSOCKET));
1905 MUTEX_EXIT(&rx_serverPool_lock);
1907 MUTEX_ENTER(&call->lock);
1913 MUTEX_ENTER(&freeSQEList_lock);
1914 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1915 rx_FreeSQEList = sq;
1916 MUTEX_EXIT(&freeSQEList_lock);
1919 clock_GetTime(&call->startTime);
1920 call->state = RX_STATE_ACTIVE;
1921 call->mode = RX_MODE_RECEIVING;
1922 #ifdef RX_KERNEL_TRACE
1923 if (ICL_SETACTIVE(afs_iclSetp)) {
1924 int glockOwner = ISAFS_GLOCK();
1927 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1928 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1935 rxi_calltrace(RX_CALL_START, call);
1936 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1937 call->conn->service->servicePort, call->conn->service->serviceId,
1940 MUTEX_EXIT(&call->lock);
1941 MUTEX_ENTER(&rx_refcnt_mutex);
1942 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1943 MUTEX_EXIT(&rx_refcnt_mutex);
1945 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1950 #else /* RX_ENABLE_LOCKS */
1952 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1954 struct rx_serverQueueEntry *sq;
1955 struct rx_call *call = (struct rx_call *)0, *choice2;
1956 struct rx_service *service = NULL;
1960 MUTEX_ENTER(&freeSQEList_lock);
1962 if ((sq = rx_FreeSQEList)) {
1963 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1964 MUTEX_EXIT(&freeSQEList_lock);
1965 } else { /* otherwise allocate a new one and return that */
1966 MUTEX_EXIT(&freeSQEList_lock);
1967 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1968 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1969 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1971 MUTEX_ENTER(&sq->lock);
1973 if (cur_service != NULL) {
1974 cur_service->nRequestsRunning--;
1975 MUTEX_ENTER(&rx_quota_mutex);
1976 if (cur_service->nRequestsRunning < cur_service->minProcs)
1979 MUTEX_EXIT(&rx_quota_mutex);
1981 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1982 struct rx_call *tcall, *ncall;
1983 /* Scan for eligible incoming calls. A call is not eligible
1984 * if the maximum number of calls for its service type are
1985 * already executing */
1986 /* One thread will process calls FCFS (to prevent starvation),
1987 * while the other threads may run ahead looking for calls which
1988 * have all their input data available immediately. This helps
1989 * keep threads from blocking, waiting for data from the client. */
1990 choice2 = (struct rx_call *)0;
1991 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1992 service = tcall->conn->service;
1993 if (QuotaOK(service)) {
1994 MUTEX_ENTER(&rx_pthread_mutex);
1995 if (tno == rxi_fcfs_thread_num
1996 || !tcall->queue_item_header.next) {
1997 MUTEX_EXIT(&rx_pthread_mutex);
1998 /* If we're the fcfs thread, then we'll just use
1999 * this call. If we haven't been able to find an optimal
2000 * choice, and we're at the end of the list, then use a
2001 * 2d choice if one has been identified. Otherwise... */
2002 call = (choice2 ? choice2 : tcall);
2003 service = call->conn->service;
2005 MUTEX_EXIT(&rx_pthread_mutex);
2006 if (!queue_IsEmpty(&tcall->rq)) {
2007 struct rx_packet *rp;
2008 rp = queue_First(&tcall->rq, rx_packet);
2009 if (rp->header.seq == 1
2011 || (rp->header.flags & RX_LAST_PACKET))) {
2013 } else if (rxi_2dchoice && !choice2
2014 && !(tcall->flags & RX_CALL_CLEARED)
2015 && (tcall->rprev > rxi_HardAckRate)) {
2029 /* we can't schedule a call if there's no data!!! */
2030 /* send an ack if there's no data, if we're missing the
2031 * first packet, or we're missing something between first
2032 * and last -- there's a "hole" in the incoming data. */
2033 if (queue_IsEmpty(&call->rq)
2034 || queue_First(&call->rq, rx_packet)->header.seq != 1
2035 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2036 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2038 call->flags &= (~RX_CALL_WAIT_PROC);
2039 service->nRequestsRunning++;
2040 /* just started call in minProcs pool, need fewer to maintain
2042 MUTEX_ENTER(&rx_quota_mutex);
2043 if (service->nRequestsRunning <= service->minProcs)
2046 MUTEX_EXIT(&rx_quota_mutex);
2047 rx_atomic_dec(&rx_nWaiting);
2048 /* MUTEX_EXIT(&call->lock); */
2050 /* If there are no eligible incoming calls, add this process
2051 * to the idle server queue, to wait for one */
2054 *socketp = OSI_NULLSOCKET;
2056 sq->socketp = socketp;
2057 queue_Append(&rx_idleServerQueue, sq);
2061 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2063 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2064 return (struct rx_call *)0;
2067 } while (!(call = sq->newcall)
2068 && !(socketp && *socketp != OSI_NULLSOCKET));
2070 MUTEX_EXIT(&sq->lock);
2072 MUTEX_ENTER(&freeSQEList_lock);
2073 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2074 rx_FreeSQEList = sq;
2075 MUTEX_EXIT(&freeSQEList_lock);
2078 clock_GetTime(&call->startTime);
2079 call->state = RX_STATE_ACTIVE;
2080 call->mode = RX_MODE_RECEIVING;
2081 #ifdef RX_KERNEL_TRACE
2082 if (ICL_SETACTIVE(afs_iclSetp)) {
2083 int glockOwner = ISAFS_GLOCK();
2086 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2087 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2094 rxi_calltrace(RX_CALL_START, call);
2095 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2096 call->conn->service->servicePort, call->conn->service->serviceId,
2099 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2106 #endif /* RX_ENABLE_LOCKS */
2110 /* Establish a procedure to be called when a packet arrives for a
2111 * call. This routine will be called at most once after each call,
2112 * and will also be called if there is an error condition on the or
2113 * the call is complete. Used by multi rx to build a selection
2114 * function which determines which of several calls is likely to be a
2115 * good one to read from.
2116 * NOTE: the way this is currently implemented it is probably only a
2117 * good idea to (1) use it immediately after a newcall (clients only)
2118 * and (2) only use it once. Other uses currently void your warranty
2121 rx_SetArrivalProc(struct rx_call *call,
2122 void (*proc) (struct rx_call * call,
2125 void * handle, int arg)
2127 call->arrivalProc = proc;
2128 call->arrivalProcHandle = handle;
2129 call->arrivalProcArg = arg;
2132 /* Call is finished (possibly prematurely). Return rc to the peer, if
2133 * appropriate, and return the final error code from the conversation
2137 rx_EndCall(struct rx_call *call, afs_int32 rc)
2139 struct rx_connection *conn = call->conn;
2143 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2144 call, rc, call->error, call->abortCode));
2147 MUTEX_ENTER(&call->lock);
2149 if (rc == 0 && call->error == 0) {
2150 call->abortCode = 0;
2151 call->abortCount = 0;
2154 call->arrivalProc = (void (*)())0;
2155 if (rc && call->error == 0) {
2156 rxi_CallError(call, rc);
2157 call->mode = RX_MODE_ERROR;
2158 /* Send an abort message to the peer if this error code has
2159 * only just been set. If it was set previously, assume the
2160 * peer has already been sent the error code or will request it
2162 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2164 if (conn->type == RX_SERVER_CONNECTION) {
2165 /* Make sure reply or at least dummy reply is sent */
2166 if (call->mode == RX_MODE_RECEIVING) {
2167 MUTEX_EXIT(&call->lock);
2168 rxi_WriteProc(call, 0, 0);
2169 MUTEX_ENTER(&call->lock);
2171 if (call->mode == RX_MODE_SENDING) {
2172 MUTEX_EXIT(&call->lock);
2173 rxi_FlushWrite(call);
2174 MUTEX_ENTER(&call->lock);
2176 rxi_calltrace(RX_CALL_END, call);
2177 /* Call goes to hold state until reply packets are acknowledged */
2178 if (call->tfirst + call->nSoftAcked < call->tnext) {
2179 call->state = RX_STATE_HOLD;
2181 call->state = RX_STATE_DALLY;
2182 rxi_ClearTransmitQueue(call, 0);
2183 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2184 rxevent_Cancel(call->keepAliveEvent, call,
2185 RX_CALL_REFCOUNT_ALIVE);
2187 } else { /* Client connection */
2189 /* Make sure server receives input packets, in the case where
2190 * no reply arguments are expected */
2191 if ((call->mode == RX_MODE_SENDING)
2192 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2193 MUTEX_EXIT(&call->lock);
2194 (void)rxi_ReadProc(call, &dummy, 1);
2195 MUTEX_ENTER(&call->lock);
2198 /* If we had an outstanding delayed ack, be nice to the server
2199 * and force-send it now.
2201 if (call->delayedAckEvent) {
2202 rxevent_Cancel(call->delayedAckEvent, call,
2203 RX_CALL_REFCOUNT_DELAY);
2204 call->delayedAckEvent = NULL;
2205 rxi_SendDelayedAck(NULL, call, NULL);
2208 /* We need to release the call lock since it's lower than the
2209 * conn_call_lock and we don't want to hold the conn_call_lock
2210 * over the rx_ReadProc call. The conn_call_lock needs to be held
2211 * here for the case where rx_NewCall is perusing the calls on
2212 * the connection structure. We don't want to signal until
2213 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2214 * have checked this call, found it active and by the time it
2215 * goes to sleep, will have missed the signal.
2217 MUTEX_EXIT(&call->lock);
2218 MUTEX_ENTER(&conn->conn_call_lock);
2219 MUTEX_ENTER(&call->lock);
2221 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2222 conn->lastBusy[call->channel] = 0;
2225 MUTEX_ENTER(&conn->conn_data_lock);
2226 conn->flags |= RX_CONN_BUSY;
2227 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2228 MUTEX_EXIT(&conn->conn_data_lock);
2229 #ifdef RX_ENABLE_LOCKS
2230 CV_BROADCAST(&conn->conn_call_cv);
2235 #ifdef RX_ENABLE_LOCKS
2237 MUTEX_EXIT(&conn->conn_data_lock);
2239 #endif /* RX_ENABLE_LOCKS */
2240 call->state = RX_STATE_DALLY;
2242 error = call->error;
2244 /* currentPacket, nLeft, and NFree must be zeroed here, because
2245 * ResetCall cannot: ResetCall may be called at splnet(), in the
2246 * kernel version, and may interrupt the macros rx_Read or
2247 * rx_Write, which run at normal priority for efficiency. */
2248 if (call->currentPacket) {
2249 #ifdef RX_TRACK_PACKETS
2250 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2252 rxi_FreePacket(call->currentPacket);
2253 call->currentPacket = (struct rx_packet *)0;
2256 call->nLeft = call->nFree = call->curlen = 0;
2258 /* Free any packets from the last call to ReadvProc/WritevProc */
2259 #ifdef RXDEBUG_PACKET
2261 #endif /* RXDEBUG_PACKET */
2262 rxi_FreePackets(0, &call->iovq);
2263 MUTEX_EXIT(&call->lock);
2265 MUTEX_ENTER(&rx_refcnt_mutex);
2266 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2267 MUTEX_EXIT(&rx_refcnt_mutex);
2268 if (conn->type == RX_CLIENT_CONNECTION) {
2269 MUTEX_ENTER(&conn->conn_data_lock);
2270 conn->flags &= ~RX_CONN_BUSY;
2271 MUTEX_EXIT(&conn->conn_data_lock);
2272 MUTEX_EXIT(&conn->conn_call_lock);
2276 * Map errors to the local host's errno.h format.
2278 error = ntoh_syserr_conv(error);
2282 #if !defined(KERNEL)
2284 /* Call this routine when shutting down a server or client (especially
2285 * clients). This will allow Rx to gracefully garbage collect server
2286 * connections, and reduce the number of retries that a server might
2287 * make to a dead client.
2288 * This is not quite right, since some calls may still be ongoing and
2289 * we can't lock them to destroy them. */
2293 struct rx_connection **conn_ptr, **conn_end;
2297 if (rxinit_status == 1) {
2299 return; /* Already shutdown. */
2301 rxi_DeleteCachedConnections();
2302 if (rx_connHashTable) {
2303 MUTEX_ENTER(&rx_connHashTable_lock);
2304 for (conn_ptr = &rx_connHashTable[0], conn_end =
2305 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2307 struct rx_connection *conn, *next;
2308 for (conn = *conn_ptr; conn; conn = next) {
2310 if (conn->type == RX_CLIENT_CONNECTION) {
2311 MUTEX_ENTER(&rx_refcnt_mutex);
2313 MUTEX_EXIT(&rx_refcnt_mutex);
2314 #ifdef RX_ENABLE_LOCKS
2315 rxi_DestroyConnectionNoLock(conn);
2316 #else /* RX_ENABLE_LOCKS */
2317 rxi_DestroyConnection(conn);
2318 #endif /* RX_ENABLE_LOCKS */
2322 #ifdef RX_ENABLE_LOCKS
2323 while (rx_connCleanup_list) {
2324 struct rx_connection *conn;
2325 conn = rx_connCleanup_list;
2326 rx_connCleanup_list = rx_connCleanup_list->next;
2327 MUTEX_EXIT(&rx_connHashTable_lock);
2328 rxi_CleanupConnection(conn);
2329 MUTEX_ENTER(&rx_connHashTable_lock);
2331 MUTEX_EXIT(&rx_connHashTable_lock);
2332 #endif /* RX_ENABLE_LOCKS */
2337 afs_winsockCleanup();
2345 /* if we wakeup packet waiter too often, can get in loop with two
2346 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2348 rxi_PacketsUnWait(void)
2350 if (!rx_waitingForPackets) {
2354 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2355 return; /* still over quota */
2358 rx_waitingForPackets = 0;
2359 #ifdef RX_ENABLE_LOCKS
2360 CV_BROADCAST(&rx_waitingForPackets_cv);
2362 osi_rxWakeup(&rx_waitingForPackets);
2368 /* ------------------Internal interfaces------------------------- */
2370 /* Return this process's service structure for the
2371 * specified socket and service */
2373 rxi_FindService(osi_socket socket, u_short serviceId)
2375 struct rx_service **sp;
2376 for (sp = &rx_services[0]; *sp; sp++) {
2377 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2383 #ifdef RXDEBUG_PACKET
2384 #ifdef KDUMP_RX_LOCK
2385 static struct rx_call_rx_lock *rx_allCallsp = 0;
2387 static struct rx_call *rx_allCallsp = 0;
2389 #endif /* RXDEBUG_PACKET */
2391 /* Allocate a call structure, for the indicated channel of the
2392 * supplied connection. The mode and state of the call must be set by
2393 * the caller. Returns the call with mutex locked. */
2395 rxi_NewCall(struct rx_connection *conn, int channel)
2397 struct rx_call *call;
2398 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2399 struct rx_call *cp; /* Call pointer temp */
2400 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2401 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2403 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2405 /* Grab an existing call structure, or allocate a new one.
2406 * Existing call structures are assumed to have been left reset by
2408 MUTEX_ENTER(&rx_freeCallQueue_lock);
2410 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2412 * EXCEPT that the TQ might not yet be cleared out.
2413 * Skip over those with in-use TQs.
2416 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2417 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2423 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2424 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2425 call = queue_First(&rx_freeCallQueue, rx_call);
2426 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2428 if (rx_stats_active)
2429 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2430 MUTEX_EXIT(&rx_freeCallQueue_lock);
2431 MUTEX_ENTER(&call->lock);
2432 CLEAR_CALL_QUEUE_LOCK(call);
2433 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2434 /* Now, if TQ wasn't cleared earlier, do it now. */
2435 rxi_WaitforTQBusy(call);
2436 if (call->flags & RX_CALL_TQ_CLEARME) {
2437 rxi_ClearTransmitQueue(call, 1);
2438 /*queue_Init(&call->tq);*/
2440 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2441 /* Bind the call to its connection structure */
2443 rxi_ResetCall(call, 1);
2446 call = rxi_Alloc(sizeof(struct rx_call));
2447 #ifdef RXDEBUG_PACKET
2448 call->allNextp = rx_allCallsp;
2449 rx_allCallsp = call;
2451 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2452 #else /* RXDEBUG_PACKET */
2453 rx_atomic_inc(&rx_stats.nCallStructs);
2454 #endif /* RXDEBUG_PACKET */
2456 MUTEX_EXIT(&rx_freeCallQueue_lock);
2457 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2458 MUTEX_ENTER(&call->lock);
2459 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2460 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2461 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2463 /* Initialize once-only items */
2464 queue_Init(&call->tq);
2465 queue_Init(&call->rq);
2466 queue_Init(&call->iovq);
2467 #ifdef RXDEBUG_PACKET
2468 call->rqc = call->tqc = call->iovqc = 0;
2469 #endif /* RXDEBUG_PACKET */
2470 /* Bind the call to its connection structure (prereq for reset) */
2472 rxi_ResetCall(call, 1);
2474 call->channel = channel;
2475 call->callNumber = &conn->callNumber[channel];
2476 call->rwind = conn->rwind[channel];
2477 call->twind = conn->twind[channel];
2478 /* Note that the next expected call number is retained (in
2479 * conn->callNumber[i]), even if we reallocate the call structure
2481 conn->call[channel] = call;
2482 /* if the channel's never been used (== 0), we should start at 1, otherwise
2483 * the call number is valid from the last time this channel was used */
2484 if (*call->callNumber == 0)
2485 *call->callNumber = 1;
2490 /* A call has been inactive long enough that so we can throw away
2491 * state, including the call structure, which is placed on the call
2494 * call->lock amd rx_refcnt_mutex are held upon entry.
2495 * haveCTLock is set when called from rxi_ReapConnections.
2498 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2500 int channel = call->channel;
2501 struct rx_connection *conn = call->conn;
2504 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2505 (*call->callNumber)++;
2507 * We are setting the state to RX_STATE_RESET to
2508 * ensure that no one else will attempt to use this
2509 * call once we drop the refcnt lock. We must drop
2510 * the refcnt lock before calling rxi_ResetCall
2511 * because it cannot be held across acquiring the
2512 * freepktQ lock. NewCall does the same.
2514 call->state = RX_STATE_RESET;
2515 MUTEX_EXIT(&rx_refcnt_mutex);
2516 rxi_ResetCall(call, 0);
2517 call->conn->call[channel] = (struct rx_call *)0;
2519 MUTEX_ENTER(&rx_freeCallQueue_lock);
2520 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2521 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2522 /* A call may be free even though its transmit queue is still in use.
2523 * Since we search the call list from head to tail, put busy calls at
2524 * the head of the list, and idle calls at the tail.
2526 if (call->flags & RX_CALL_TQ_BUSY)
2527 queue_Prepend(&rx_freeCallQueue, call);
2529 queue_Append(&rx_freeCallQueue, call);
2530 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2531 queue_Append(&rx_freeCallQueue, call);
2532 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2533 if (rx_stats_active)
2534 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2535 MUTEX_EXIT(&rx_freeCallQueue_lock);
2537 /* Destroy the connection if it was previously slated for
2538 * destruction, i.e. the Rx client code previously called
2539 * rx_DestroyConnection (client connections), or
2540 * rxi_ReapConnections called the same routine (server
2541 * connections). Only do this, however, if there are no
2542 * outstanding calls. Note that for fine grain locking, there appears
2543 * to be a deadlock in that rxi_FreeCall has a call locked and
2544 * DestroyConnectionNoLock locks each call in the conn. But note a
2545 * few lines up where we have removed this call from the conn.
2546 * If someone else destroys a connection, they either have no
2547 * call lock held or are going through this section of code.
2549 MUTEX_ENTER(&conn->conn_data_lock);
2550 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2551 MUTEX_ENTER(&rx_refcnt_mutex);
2553 MUTEX_EXIT(&rx_refcnt_mutex);
2554 MUTEX_EXIT(&conn->conn_data_lock);
2555 #ifdef RX_ENABLE_LOCKS
2557 rxi_DestroyConnectionNoLock(conn);
2559 rxi_DestroyConnection(conn);
2560 #else /* RX_ENABLE_LOCKS */
2561 rxi_DestroyConnection(conn);
2562 #endif /* RX_ENABLE_LOCKS */
2564 MUTEX_EXIT(&conn->conn_data_lock);
2566 MUTEX_ENTER(&rx_refcnt_mutex);
2569 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2570 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2573 rxi_Alloc(size_t size)
2577 if (rx_stats_active) {
2578 rx_atomic_add(&rxi_Allocsize, (int) size);
2579 rx_atomic_inc(&rxi_Alloccnt);
2583 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2584 afs_osi_Alloc_NoSleep(size);
2589 osi_Panic("rxi_Alloc error");
2595 rxi_Free(void *addr, size_t size)
2597 if (rx_stats_active) {
2598 rx_atomic_sub(&rxi_Allocsize, (int) size);
2599 rx_atomic_dec(&rxi_Alloccnt);
2601 osi_Free(addr, size);
2605 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2607 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2608 struct rx_peer *next = NULL;
2612 MUTEX_ENTER(&rx_peerHashTable_lock);
2614 peer_ptr = &rx_peerHashTable[0];
2615 peer_end = &rx_peerHashTable[rx_hashTableSize];
2618 for ( ; peer_ptr < peer_end; peer_ptr++) {
2621 for ( ; peer; peer = next) {
2623 if (host == peer->host)
2628 hashIndex = PEER_HASH(host, port);
2629 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2630 if ((peer->host == host) && (peer->port == port))
2635 MUTEX_ENTER(&rx_peerHashTable_lock);
2640 MUTEX_EXIT(&rx_peerHashTable_lock);
2642 MUTEX_ENTER(&peer->peer_lock);
2643 /* We don't handle dropping below min, so don't */
2644 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2645 peer->ifMTU=MIN(mtu, peer->ifMTU);
2646 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2647 /* if we tweaked this down, need to tune our peer MTU too */
2648 peer->MTU = MIN(peer->MTU, peer->natMTU);
2649 /* if we discovered a sub-1500 mtu, degrade */
2650 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2651 peer->maxDgramPackets = 1;
2652 /* We no longer have valid peer packet information */
2653 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2654 peer->maxPacketSize = 0;
2655 MUTEX_EXIT(&peer->peer_lock);
2657 MUTEX_ENTER(&rx_peerHashTable_lock);
2659 if (host && !port) {
2661 /* pick up where we left off */
2665 MUTEX_EXIT(&rx_peerHashTable_lock);
2668 /* Find the peer process represented by the supplied (host,port)
2669 * combination. If there is no appropriate active peer structure, a
2670 * new one will be allocated and initialized
2671 * The origPeer, if set, is a pointer to a peer structure on which the
2672 * refcount will be be decremented. This is used to replace the peer
2673 * structure hanging off a connection structure */
2675 rxi_FindPeer(afs_uint32 host, u_short port,
2676 struct rx_peer *origPeer, int create)
2680 hashIndex = PEER_HASH(host, port);
2681 MUTEX_ENTER(&rx_peerHashTable_lock);
2682 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2683 if ((pp->host == host) && (pp->port == port))
2688 pp = rxi_AllocPeer(); /* This bzero's *pp */
2689 pp->host = host; /* set here or in InitPeerParams is zero */
2691 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2692 queue_Init(&pp->congestionQueue);
2693 queue_Init(&pp->rpcStats);
2694 pp->next = rx_peerHashTable[hashIndex];
2695 rx_peerHashTable[hashIndex] = pp;
2696 rxi_InitPeerParams(pp);
2697 if (rx_stats_active)
2698 rx_atomic_inc(&rx_stats.nPeerStructs);
2705 origPeer->refCount--;
2706 MUTEX_EXIT(&rx_peerHashTable_lock);
2711 /* Find the connection at (host, port) started at epoch, and with the
2712 * given connection id. Creates the server connection if necessary.
2713 * The type specifies whether a client connection or a server
2714 * connection is desired. In both cases, (host, port) specify the
2715 * peer's (host, pair) pair. Client connections are not made
2716 * automatically by this routine. The parameter socket gives the
2717 * socket descriptor on which the packet was received. This is used,
2718 * in the case of server connections, to check that *new* connections
2719 * come via a valid (port, serviceId). Finally, the securityIndex
2720 * parameter must match the existing index for the connection. If a
2721 * server connection is created, it will be created using the supplied
2722 * index, if the index is valid for this service */
2723 struct rx_connection *
2724 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2725 u_short port, u_short serviceId, afs_uint32 cid,
2726 afs_uint32 epoch, int type, u_int securityIndex)
2728 int hashindex, flag, i;
2729 struct rx_connection *conn;
2730 hashindex = CONN_HASH(host, port, cid, epoch, type);
2731 MUTEX_ENTER(&rx_connHashTable_lock);
2732 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2733 rx_connHashTable[hashindex],
2736 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2737 && (epoch == conn->epoch)) {
2738 struct rx_peer *pp = conn->peer;
2739 if (securityIndex != conn->securityIndex) {
2740 /* this isn't supposed to happen, but someone could forge a packet
2741 * like this, and there seems to be some CM bug that makes this
2742 * happen from time to time -- in which case, the fileserver
2744 MUTEX_EXIT(&rx_connHashTable_lock);
2745 return (struct rx_connection *)0;
2747 if (pp->host == host && pp->port == port)
2749 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2751 /* So what happens when it's a callback connection? */
2752 if ( /*type == RX_CLIENT_CONNECTION && */
2753 (conn->epoch & 0x80000000))
2757 /* the connection rxLastConn that was used the last time is not the
2758 ** one we are looking for now. Hence, start searching in the hash */
2760 conn = rx_connHashTable[hashindex];
2765 struct rx_service *service;
2766 if (type == RX_CLIENT_CONNECTION) {
2767 MUTEX_EXIT(&rx_connHashTable_lock);
2768 return (struct rx_connection *)0;
2770 service = rxi_FindService(socket, serviceId);
2771 if (!service || (securityIndex >= service->nSecurityObjects)
2772 || (service->securityObjects[securityIndex] == 0)) {
2773 MUTEX_EXIT(&rx_connHashTable_lock);
2774 return (struct rx_connection *)0;
2776 conn = rxi_AllocConnection(); /* This bzero's the connection */
2777 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2778 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2779 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2780 conn->next = rx_connHashTable[hashindex];
2781 rx_connHashTable[hashindex] = conn;
2782 conn->peer = rxi_FindPeer(host, port, 0, 1);
2783 conn->type = RX_SERVER_CONNECTION;
2784 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2785 conn->epoch = epoch;
2786 conn->cid = cid & RX_CIDMASK;
2787 /* conn->serial = conn->lastSerial = 0; */
2788 /* conn->timeout = 0; */
2789 conn->ackRate = RX_FAST_ACK_RATE;
2790 conn->service = service;
2791 conn->serviceId = serviceId;
2792 conn->securityIndex = securityIndex;
2793 conn->securityObject = service->securityObjects[securityIndex];
2794 conn->nSpecific = 0;
2795 conn->specific = NULL;
2796 rx_SetConnDeadTime(conn, service->connDeadTime);
2797 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2798 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2799 for (i = 0; i < RX_MAXCALLS; i++) {
2800 conn->twind[i] = rx_initSendWindow;
2801 conn->rwind[i] = rx_initReceiveWindow;
2803 /* Notify security object of the new connection */
2804 RXS_NewConnection(conn->securityObject, conn);
2805 /* XXXX Connection timeout? */
2806 if (service->newConnProc)
2807 (*service->newConnProc) (conn);
2808 if (rx_stats_active)
2809 rx_atomic_inc(&rx_stats.nServerConns);
2812 MUTEX_ENTER(&rx_refcnt_mutex);
2814 MUTEX_EXIT(&rx_refcnt_mutex);
2816 rxLastConn = conn; /* store this connection as the last conn used */
2817 MUTEX_EXIT(&rx_connHashTable_lock);
2822 * Timeout a call on a busy call channel if appropriate.
2824 * @param[in] call The busy call.
2826 * @pre 'call' is marked as busy (namely,
2827 * call->conn->lastBusy[call->channel] != 0)
2829 * @pre call->lock is held
2830 * @pre rxi_busyChannelError is nonzero
2832 * @note call->lock is dropped and reacquired
2835 rxi_CheckBusy(struct rx_call *call)
2837 struct rx_connection *conn = call->conn;
2838 int channel = call->channel;
2839 int freechannel = 0;
2841 afs_uint32 callNumber = *call->callNumber;
2843 MUTEX_EXIT(&call->lock);
2845 MUTEX_ENTER(&conn->conn_call_lock);
2847 /* Are there any other call slots on this conn that we should try? Look for
2848 * slots that are empty and are either non-busy, or were marked as busy
2849 * longer than conn->secondsUntilDead seconds before this call started. */
2851 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
2853 /* only look at channels that aren't us */
2857 if (conn->lastBusy[i]) {
2858 /* if this channel looked busy too recently, don't look at it */
2859 if (conn->lastBusy[i] >= call->startTime.sec) {
2862 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
2867 if (conn->call[i]) {
2868 struct rx_call *tcall = conn->call[i];
2869 MUTEX_ENTER(&tcall->lock);
2870 if (tcall->state == RX_STATE_DALLY) {
2873 MUTEX_EXIT(&tcall->lock);
2879 MUTEX_EXIT(&conn->conn_call_lock);
2881 MUTEX_ENTER(&call->lock);
2883 /* Since the call->lock and conn->conn_call_lock have been released it is
2884 * possible that (1) the call may no longer be busy and/or (2) the call may
2885 * have been reused by another waiting thread. Therefore, we must confirm
2886 * that the call state has not changed when deciding whether or not to
2887 * force this application thread to retry by forcing a Timeout error. */
2889 if (freechannel && *call->callNumber == callNumber &&
2890 (call->flags & RX_CALL_PEER_BUSY)) {
2891 /* Since 'freechannel' is set, there exists another channel in this
2892 * rx_conn that the application thread might be able to use. We know
2893 * that we have the correct call since callNumber is unchanged, and we
2894 * know that the call is still busy. So, set the call error state to
2895 * rxi_busyChannelError so the application can retry the request,
2896 * presumably on a less-busy call channel. */
2898 rxi_CallError(call, rxi_busyChannelError);
2902 /* There are two packet tracing routines available for testing and monitoring
2903 * Rx. One is called just after every packet is received and the other is
2904 * called just before every packet is sent. Received packets, have had their
2905 * headers decoded, and packets to be sent have not yet had their headers
2906 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2907 * containing the network address. Both can be modified. The return value, if
2908 * non-zero, indicates that the packet should be dropped. */
2910 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2911 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2913 /* A packet has been received off the interface. Np is the packet, socket is
2914 * the socket number it was received from (useful in determining which service
2915 * this packet corresponds to), and (host, port) reflect the host,port of the
2916 * sender. This call returns the packet to the caller if it is finished with
2917 * it, rather than de-allocating it, just as a small performance hack */
2920 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2921 afs_uint32 host, u_short port, int *tnop,
2922 struct rx_call **newcallp)
2924 struct rx_call *call;
2925 struct rx_connection *conn;
2927 afs_uint32 currentCallNumber;
2933 struct rx_packet *tnp;
2936 /* We don't print out the packet until now because (1) the time may not be
2937 * accurate enough until now in the lwp implementation (rx_Listener only gets
2938 * the time after the packet is read) and (2) from a protocol point of view,
2939 * this is the first time the packet has been seen */
2940 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2941 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2942 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2943 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2944 np->header.epoch, np->header.cid, np->header.callNumber,
2945 np->header.seq, np->header.flags, np));
2948 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2949 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2952 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2953 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2956 /* If an input tracer function is defined, call it with the packet and
2957 * network address. Note this function may modify its arguments. */
2958 if (rx_justReceived) {
2959 struct sockaddr_in addr;
2961 addr.sin_family = AF_INET;
2962 addr.sin_port = port;
2963 addr.sin_addr.s_addr = host;
2964 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2965 addr.sin_len = sizeof(addr);
2966 #endif /* AFS_OSF_ENV */
2967 drop = (*rx_justReceived) (np, &addr);
2968 /* drop packet if return value is non-zero */
2971 port = addr.sin_port; /* in case fcn changed addr */
2972 host = addr.sin_addr.s_addr;
2976 /* If packet was not sent by the client, then *we* must be the client */
2977 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2978 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2980 /* Find the connection (or fabricate one, if we're the server & if
2981 * necessary) associated with this packet */
2983 rxi_FindConnection(socket, host, port, np->header.serviceId,
2984 np->header.cid, np->header.epoch, type,
2985 np->header.securityIndex);
2988 /* If no connection found or fabricated, just ignore the packet.
2989 * (An argument could be made for sending an abort packet for
2994 MUTEX_ENTER(&conn->conn_data_lock);
2995 if (conn->maxSerial < np->header.serial)
2996 conn->maxSerial = np->header.serial;
2997 MUTEX_EXIT(&conn->conn_data_lock);
2999 /* If the connection is in an error state, send an abort packet and ignore
3000 * the incoming packet */
3002 /* Don't respond to an abort packet--we don't want loops! */
3003 MUTEX_ENTER(&conn->conn_data_lock);
3004 if (np->header.type != RX_PACKET_TYPE_ABORT)
3005 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3006 MUTEX_ENTER(&rx_refcnt_mutex);
3008 MUTEX_EXIT(&rx_refcnt_mutex);
3009 MUTEX_EXIT(&conn->conn_data_lock);
3013 /* Check for connection-only requests (i.e. not call specific). */
3014 if (np->header.callNumber == 0) {
3015 switch (np->header.type) {
3016 case RX_PACKET_TYPE_ABORT: {
3017 /* What if the supplied error is zero? */
3018 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3019 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3020 rxi_ConnectionError(conn, errcode);
3021 MUTEX_ENTER(&rx_refcnt_mutex);
3023 MUTEX_EXIT(&rx_refcnt_mutex);
3026 case RX_PACKET_TYPE_CHALLENGE:
3027 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3028 MUTEX_ENTER(&rx_refcnt_mutex);
3030 MUTEX_EXIT(&rx_refcnt_mutex);
3032 case RX_PACKET_TYPE_RESPONSE:
3033 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3034 MUTEX_ENTER(&rx_refcnt_mutex);
3036 MUTEX_EXIT(&rx_refcnt_mutex);
3038 case RX_PACKET_TYPE_PARAMS:
3039 case RX_PACKET_TYPE_PARAMS + 1:
3040 case RX_PACKET_TYPE_PARAMS + 2:
3041 /* ignore these packet types for now */
3042 MUTEX_ENTER(&rx_refcnt_mutex);
3044 MUTEX_EXIT(&rx_refcnt_mutex);
3049 /* Should not reach here, unless the peer is broken: send an
3051 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3052 MUTEX_ENTER(&conn->conn_data_lock);
3053 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3054 MUTEX_ENTER(&rx_refcnt_mutex);
3056 MUTEX_EXIT(&rx_refcnt_mutex);
3057 MUTEX_EXIT(&conn->conn_data_lock);
3062 channel = np->header.cid & RX_CHANNELMASK;
3063 call = conn->call[channel];
3064 #ifdef RX_ENABLE_LOCKS
3066 MUTEX_ENTER(&call->lock);
3067 /* Test to see if call struct is still attached to conn. */
3068 if (call != conn->call[channel]) {
3070 MUTEX_EXIT(&call->lock);
3071 if (type == RX_SERVER_CONNECTION) {
3072 call = conn->call[channel];
3073 /* If we started with no call attached and there is one now,
3074 * another thread is also running this routine and has gotten
3075 * the connection channel. We should drop this packet in the tests
3076 * below. If there was a call on this connection and it's now
3077 * gone, then we'll be making a new call below.
3078 * If there was previously a call and it's now different then
3079 * the old call was freed and another thread running this routine
3080 * has created a call on this channel. One of these two threads
3081 * has a packet for the old call and the code below handles those
3085 MUTEX_ENTER(&call->lock);
3087 /* This packet can't be for this call. If the new call address is
3088 * 0 then no call is running on this channel. If there is a call
3089 * then, since this is a client connection we're getting data for
3090 * it must be for the previous call.
3092 if (rx_stats_active)
3093 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3094 MUTEX_ENTER(&rx_refcnt_mutex);
3096 MUTEX_EXIT(&rx_refcnt_mutex);
3101 currentCallNumber = conn->callNumber[channel];
3103 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3104 if (np->header.callNumber < currentCallNumber) {
3105 if (rx_stats_active)
3106 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3107 #ifdef RX_ENABLE_LOCKS
3109 MUTEX_EXIT(&call->lock);
3111 MUTEX_ENTER(&rx_refcnt_mutex);
3113 MUTEX_EXIT(&rx_refcnt_mutex);
3117 MUTEX_ENTER(&conn->conn_call_lock);
3118 call = rxi_NewCall(conn, channel);
3119 MUTEX_EXIT(&conn->conn_call_lock);
3120 *call->callNumber = np->header.callNumber;
3122 if (np->header.callNumber == 0)
3123 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d\n",
3124 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3125 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3126 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
3128 call->state = RX_STATE_PRECALL;
3129 clock_GetTime(&call->queueTime);
3130 hzero(call->bytesSent);
3131 hzero(call->bytesRcvd);
3133 * If the number of queued calls exceeds the overload
3134 * threshold then abort this call.
3136 if ((rx_BusyThreshold > 0) &&
3137 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3138 struct rx_packet *tp;
3140 rxi_CallError(call, rx_BusyError);
3141 tp = rxi_SendCallAbort(call, np, 1, 0);
3142 MUTEX_EXIT(&call->lock);
3143 MUTEX_ENTER(&rx_refcnt_mutex);
3145 MUTEX_EXIT(&rx_refcnt_mutex);
3146 if (rx_stats_active)
3147 rx_atomic_inc(&rx_stats.nBusies);
3150 rxi_KeepAliveOn(call);
3151 } else if (np->header.callNumber != currentCallNumber) {
3152 /* Wait until the transmit queue is idle before deciding
3153 * whether to reset the current call. Chances are that the
3154 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3157 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3158 if (call->state == RX_STATE_ACTIVE) {
3159 rxi_WaitforTQBusy(call);
3161 * If we entered error state while waiting,
3162 * must call rxi_CallError to permit rxi_ResetCall
3163 * to processed when the tqWaiter count hits zero.
3166 rxi_CallError(call, call->error);
3167 MUTEX_EXIT(&call->lock);
3168 MUTEX_ENTER(&rx_refcnt_mutex);
3170 MUTEX_EXIT(&rx_refcnt_mutex);
3174 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3175 /* If the new call cannot be taken right now send a busy and set
3176 * the error condition in this call, so that it terminates as
3177 * quickly as possible */
3178 if (call->state == RX_STATE_ACTIVE) {
3179 struct rx_packet *tp;
3181 rxi_CallError(call, RX_CALL_DEAD);
3182 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3184 MUTEX_EXIT(&call->lock);
3185 MUTEX_ENTER(&rx_refcnt_mutex);
3187 MUTEX_EXIT(&rx_refcnt_mutex);
3190 rxi_ResetCall(call, 0);
3191 *call->callNumber = np->header.callNumber;
3193 if (np->header.callNumber == 0)
3194 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d\n",
3195 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3196 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3197 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3199 call->state = RX_STATE_PRECALL;
3200 clock_GetTime(&call->queueTime);
3201 hzero(call->bytesSent);
3202 hzero(call->bytesRcvd);
3204 * If the number of queued calls exceeds the overload
3205 * threshold then abort this call.
3207 if ((rx_BusyThreshold > 0) &&
3208 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3209 struct rx_packet *tp;
3211 rxi_CallError(call, rx_BusyError);
3212 tp = rxi_SendCallAbort(call, np, 1, 0);
3213 MUTEX_EXIT(&call->lock);
3214 MUTEX_ENTER(&rx_refcnt_mutex);
3216 MUTEX_EXIT(&rx_refcnt_mutex);
3217 if (rx_stats_active)
3218 rx_atomic_inc(&rx_stats.nBusies);
3221 rxi_KeepAliveOn(call);
3223 /* Continuing call; do nothing here. */
3225 } else { /* we're the client */
3226 /* Ignore all incoming acknowledgements for calls in DALLY state */
3227 if (call && (call->state == RX_STATE_DALLY)
3228 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3229 if (rx_stats_active)
3230 rx_atomic_inc(&rx_stats.ignorePacketDally);
3231 #ifdef RX_ENABLE_LOCKS
3233 MUTEX_EXIT(&call->lock);
3236 MUTEX_ENTER(&rx_refcnt_mutex);
3238 MUTEX_EXIT(&rx_refcnt_mutex);
3242 /* Ignore anything that's not relevant to the current call. If there
3243 * isn't a current call, then no packet is relevant. */
3244 if (!call || (np->header.callNumber != currentCallNumber)) {
3245 if (rx_stats_active)
3246 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3247 #ifdef RX_ENABLE_LOCKS
3249 MUTEX_EXIT(&call->lock);
3252 MUTEX_ENTER(&rx_refcnt_mutex);
3254 MUTEX_EXIT(&rx_refcnt_mutex);
3257 /* If the service security object index stamped in the packet does not
3258 * match the connection's security index, ignore the packet */
3259 if (np->header.securityIndex != conn->securityIndex) {
3260 #ifdef RX_ENABLE_LOCKS
3261 MUTEX_EXIT(&call->lock);
3263 MUTEX_ENTER(&rx_refcnt_mutex);
3265 MUTEX_EXIT(&rx_refcnt_mutex);
3269 /* If we're receiving the response, then all transmit packets are
3270 * implicitly acknowledged. Get rid of them. */
3271 if (np->header.type == RX_PACKET_TYPE_DATA) {
3272 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3273 /* XXX Hack. Because we must release the global rx lock when
3274 * sending packets (osi_NetSend) we drop all acks while we're
3275 * traversing the tq in rxi_Start sending packets out because
3276 * packets may move to the freePacketQueue as result of being here!
3277 * So we drop these packets until we're safely out of the
3278 * traversing. Really ugly!
3279 * For fine grain RX locking, we set the acked field in the
3280 * packets and let rxi_Start remove them from the transmit queue.
3282 if (call->flags & RX_CALL_TQ_BUSY) {
3283 #ifdef RX_ENABLE_LOCKS
3284 rxi_SetAcksInTransmitQueue(call);
3286 MUTEX_ENTER(&rx_refcnt_mutex);
3288 MUTEX_EXIT(&rx_refcnt_mutex);
3289 return np; /* xmitting; drop packet */
3292 rxi_ClearTransmitQueue(call, 0);
3294 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3295 rxi_ClearTransmitQueue(call, 0);
3296 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3298 if (np->header.type == RX_PACKET_TYPE_ACK) {
3299 /* now check to see if this is an ack packet acknowledging that the
3300 * server actually *lost* some hard-acked data. If this happens we
3301 * ignore this packet, as it may indicate that the server restarted in
3302 * the middle of a call. It is also possible that this is an old ack
3303 * packet. We don't abort the connection in this case, because this
3304 * *might* just be an old ack packet. The right way to detect a server
3305 * restart in the midst of a call is to notice that the server epoch
3307 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3308 * XXX unacknowledged. I think that this is off-by-one, but
3309 * XXX I don't dare change it just yet, since it will
3310 * XXX interact badly with the server-restart detection
3311 * XXX code in receiveackpacket. */
3312 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3313 if (rx_stats_active)
3314 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3315 MUTEX_EXIT(&call->lock);
3316 MUTEX_ENTER(&rx_refcnt_mutex);
3318 MUTEX_EXIT(&rx_refcnt_mutex);
3322 } /* else not a data packet */
3325 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3326 /* Set remote user defined status from packet */
3327 call->remoteStatus = np->header.userStatus;
3329 /* Note the gap between the expected next packet and the actual
3330 * packet that arrived, when the new packet has a smaller serial number
3331 * than expected. Rioses frequently reorder packets all by themselves,
3332 * so this will be quite important with very large window sizes.
3333 * Skew is checked against 0 here to avoid any dependence on the type of
3334 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3336 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3337 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3338 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3340 MUTEX_ENTER(&conn->conn_data_lock);
3341 skew = conn->lastSerial - np->header.serial;
3342 conn->lastSerial = np->header.serial;
3343 MUTEX_EXIT(&conn->conn_data_lock);
3345 struct rx_peer *peer;
3347 if (skew > peer->inPacketSkew) {
3348 dpf(("*** In skew changed from %d to %d\n",
3349 peer->inPacketSkew, skew));
3350 peer->inPacketSkew = skew;
3354 /* Now do packet type-specific processing */
3355 switch (np->header.type) {
3356 case RX_PACKET_TYPE_DATA:
3357 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3360 case RX_PACKET_TYPE_ACK:
3361 /* Respond immediately to ack packets requesting acknowledgement
3363 if (np->header.flags & RX_REQUEST_ACK) {
3365 (void)rxi_SendCallAbort(call, 0, 1, 0);
3367 (void)rxi_SendAck(call, 0, np->header.serial,
3368 RX_ACK_PING_RESPONSE, 1);
3370 np = rxi_ReceiveAckPacket(call, np, 1);
3372 case RX_PACKET_TYPE_ABORT: {
3373 /* An abort packet: reset the call, passing the error up to the user. */
3374 /* What if error is zero? */
3375 /* What if the error is -1? the application will treat it as a timeout. */
3376 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3377 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3378 rxi_CallError(call, errdata);
3379 MUTEX_EXIT(&call->lock);
3380 MUTEX_ENTER(&rx_refcnt_mutex);
3382 MUTEX_EXIT(&rx_refcnt_mutex);
3383 return np; /* xmitting; drop packet */
3385 case RX_PACKET_TYPE_BUSY: {
3386 struct clock busyTime;
3388 clock_GetTime(&busyTime);
3390 MUTEX_EXIT(&call->lock);
3392 MUTEX_ENTER(&conn->conn_call_lock);
3393 MUTEX_ENTER(&call->lock);
3394 conn->lastBusy[call->channel] = busyTime.sec;
3395 call->flags |= RX_CALL_PEER_BUSY;
3396 MUTEX_EXIT(&call->lock);
3397 MUTEX_EXIT(&conn->conn_call_lock);
3399 MUTEX_ENTER(&rx_refcnt_mutex);
3401 MUTEX_EXIT(&rx_refcnt_mutex);
3405 case RX_PACKET_TYPE_ACKALL:
3406 /* All packets acknowledged, so we can drop all packets previously
3407 * readied for sending */
3408 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3409 /* XXX Hack. We because we can't release the global rx lock when
3410 * sending packets (osi_NetSend) we drop all ack pkts while we're
3411 * traversing the tq in rxi_Start sending packets out because
3412 * packets may move to the freePacketQueue as result of being
3413 * here! So we drop these packets until we're safely out of the
3414 * traversing. Really ugly!
3415 * For fine grain RX locking, we set the acked field in the packets
3416 * and let rxi_Start remove the packets from the transmit queue.
3418 if (call->flags & RX_CALL_TQ_BUSY) {
3419 #ifdef RX_ENABLE_LOCKS
3420 rxi_SetAcksInTransmitQueue(call);
3422 #else /* RX_ENABLE_LOCKS */
3423 MUTEX_EXIT(&call->lock);
3424 MUTEX_ENTER(&rx_refcnt_mutex);
3426 MUTEX_EXIT(&rx_refcnt_mutex);
3427 return np; /* xmitting; drop packet */
3428 #endif /* RX_ENABLE_LOCKS */
3430 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3431 rxi_ClearTransmitQueue(call, 0);
3434 /* Should not reach here, unless the peer is broken: send an abort
3436 rxi_CallError(call, RX_PROTOCOL_ERROR);
3437 np = rxi_SendCallAbort(call, np, 1, 0);
3440 /* Note when this last legitimate packet was received, for keep-alive
3441 * processing. Note, we delay getting the time until now in the hope that
3442 * the packet will be delivered to the user before any get time is required
3443 * (if not, then the time won't actually be re-evaluated here). */
3444 call->lastReceiveTime = clock_Sec();
3445 /* we've received a legit packet, so the channel is not busy */
3446 call->flags &= ~RX_CALL_PEER_BUSY;
3447 MUTEX_EXIT(&call->lock);
3448 MUTEX_ENTER(&rx_refcnt_mutex);
3450 MUTEX_EXIT(&rx_refcnt_mutex);
3454 /* return true if this is an "interesting" connection from the point of view
3455 of someone trying to debug the system */
3457 rxi_IsConnInteresting(struct rx_connection *aconn)
3460 struct rx_call *tcall;
3462 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3465 for (i = 0; i < RX_MAXCALLS; i++) {
3466 tcall = aconn->call[i];
3468 if ((tcall->state == RX_STATE_PRECALL)
3469 || (tcall->state == RX_STATE_ACTIVE))
3471 if ((tcall->mode == RX_MODE_SENDING)
3472 || (tcall->mode == RX_MODE_RECEIVING))
3480 /* if this is one of the last few packets AND it wouldn't be used by the
3481 receiving call to immediately satisfy a read request, then drop it on
3482 the floor, since accepting it might prevent a lock-holding thread from
3483 making progress in its reading. If a call has been cleared while in
3484 the precall state then ignore all subsequent packets until the call
3485 is assigned to a thread. */
3488 TooLow(struct rx_packet *ap, struct rx_call *acall)
3492 MUTEX_ENTER(&rx_quota_mutex);
3493 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3494 && (acall->state == RX_STATE_PRECALL))
3495 || ((rx_nFreePackets < rxi_dataQuota + 2)
3496 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3497 && (acall->flags & RX_CALL_READER_WAIT)))) {
3500 MUTEX_EXIT(&rx_quota_mutex);
3506 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3508 struct rx_connection *conn = arg1;
3509 struct rx_call *acall = arg2;
3510 struct rx_call *call = acall;
3511 struct clock when, now;
3514 MUTEX_ENTER(&conn->conn_data_lock);
3515 conn->checkReachEvent = NULL;
3516 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3518 MUTEX_ENTER(&rx_refcnt_mutex);
3520 MUTEX_EXIT(&rx_refcnt_mutex);
3522 MUTEX_EXIT(&conn->conn_data_lock);
3526 MUTEX_ENTER(&conn->conn_call_lock);
3527 MUTEX_ENTER(&conn->conn_data_lock);
3528 for (i = 0; i < RX_MAXCALLS; i++) {
3529 struct rx_call *tc = conn->call[i];
3530 if (tc && tc->state == RX_STATE_PRECALL) {
3536 /* Indicate that rxi_CheckReachEvent is no longer running by
3537 * clearing the flag. Must be atomic under conn_data_lock to
3538 * avoid a new call slipping by: rxi_CheckConnReach holds
3539 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3541 conn->flags &= ~RX_CONN_ATTACHWAIT;
3542 MUTEX_EXIT(&conn->conn_data_lock);
3543 MUTEX_EXIT(&conn->conn_call_lock);
3548 MUTEX_ENTER(&call->lock);
3549 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3551 MUTEX_EXIT(&call->lock);
3553 clock_GetTime(&now);
3555 when.sec += RX_CHECKREACH_TIMEOUT;
3556 MUTEX_ENTER(&conn->conn_data_lock);
3557 if (!conn->checkReachEvent) {
3558 MUTEX_ENTER(&rx_refcnt_mutex);
3560 MUTEX_EXIT(&rx_refcnt_mutex);
3561 conn->checkReachEvent =
3562 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3565 MUTEX_EXIT(&conn->conn_data_lock);
3571 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3573 struct rx_service *service = conn->service;
3574 struct rx_peer *peer = conn->peer;
3575 afs_uint32 now, lastReach;
3577 if (service->checkReach == 0)
3581 MUTEX_ENTER(&peer->peer_lock);
3582 lastReach = peer->lastReachTime;
3583 MUTEX_EXIT(&peer->peer_lock);
3584 if (now - lastReach < RX_CHECKREACH_TTL)
3587 MUTEX_ENTER(&conn->conn_data_lock);
3588 if (conn->flags & RX_CONN_ATTACHWAIT) {
3589 MUTEX_EXIT(&conn->conn_data_lock);
3592 conn->flags |= RX_CONN_ATTACHWAIT;
3593 MUTEX_EXIT(&conn->conn_data_lock);
3594 if (!conn->checkReachEvent)
3595 rxi_CheckReachEvent(NULL, conn, call);
3600 /* try to attach call, if authentication is complete */
3602 TryAttach(struct rx_call *acall, osi_socket socket,
3603 int *tnop, struct rx_call **newcallp,
3606 struct rx_connection *conn = acall->conn;
3608 if (conn->type == RX_SERVER_CONNECTION
3609 && acall->state == RX_STATE_PRECALL) {
3610 /* Don't attach until we have any req'd. authentication. */
3611 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3612 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3613 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3614 /* Note: this does not necessarily succeed; there
3615 * may not any proc available
3618 rxi_ChallengeOn(acall->conn);
3623 /* A data packet has been received off the interface. This packet is
3624 * appropriate to the call (the call is in the right state, etc.). This
3625 * routine can return a packet to the caller, for re-use */
3628 rxi_ReceiveDataPacket(struct rx_call *call,
3629 struct rx_packet *np, int istack,
3630 osi_socket socket, afs_uint32 host, u_short port,
3631 int *tnop, struct rx_call **newcallp)
3633 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3638 afs_uint32 serial=0, flags=0;
3640 struct rx_packet *tnp;
3641 struct clock when, now;
3642 if (rx_stats_active)
3643 rx_atomic_inc(&rx_stats.dataPacketsRead);
3646 /* If there are no packet buffers, drop this new packet, unless we can find
3647 * packet buffers from inactive calls */
3649 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3650 MUTEX_ENTER(&rx_freePktQ_lock);
3651 rxi_NeedMorePackets = TRUE;
3652 MUTEX_EXIT(&rx_freePktQ_lock);
3653 if (rx_stats_active)
3654 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3655 call->rprev = np->header.serial;
3656 rxi_calltrace(RX_TRACE_DROP, call);
3657 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3659 rxi_ClearReceiveQueue(call);
3660 clock_GetTime(&now);
3662 clock_Add(&when, &rx_softAckDelay);
3663 if (!call->delayedAckEvent
3664 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3665 rxevent_Cancel(call->delayedAckEvent, call,
3666 RX_CALL_REFCOUNT_DELAY);
3667 MUTEX_ENTER(&rx_refcnt_mutex);
3668 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3669 MUTEX_EXIT(&rx_refcnt_mutex);
3671 call->delayedAckEvent =
3672 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3674 /* we've damaged this call already, might as well do it in. */
3680 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3681 * packet is one of several packets transmitted as a single
3682 * datagram. Do not send any soft or hard acks until all packets
3683 * in a jumbogram have been processed. Send negative acks right away.
3685 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3686 /* tnp is non-null when there are more packets in the
3687 * current jumbo gram */
3694 seq = np->header.seq;
3695 serial = np->header.serial;
3696 flags = np->header.flags;
3698 /* If the call is in an error state, send an abort message */
3700 return rxi_SendCallAbort(call, np, istack, 0);
3702 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3703 * AFS 3.5 jumbogram. */
3704 if (flags & RX_JUMBO_PACKET) {
3705 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3710 if (np->header.spare != 0) {
3711 MUTEX_ENTER(&call->conn->conn_data_lock);
3712 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3713 MUTEX_EXIT(&call->conn->conn_data_lock);
3716 /* The usual case is that this is the expected next packet */
3717 if (seq == call->rnext) {
3719 /* Check to make sure it is not a duplicate of one already queued */
3720 if (queue_IsNotEmpty(&call->rq)
3721 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3722 if (rx_stats_active)
3723 rx_atomic_inc(&rx_stats.dupPacketsRead);
3724 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3725 rxevent_Cancel(call->delayedAckEvent, call,
3726 RX_CALL_REFCOUNT_DELAY);
3727 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3733 /* It's the next packet. Stick it on the receive queue
3734 * for this call. Set newPackets to make sure we wake
3735 * the reader once all packets have been processed */
3736 #ifdef RX_TRACK_PACKETS
3737 np->flags |= RX_PKTFLAG_RQ;
3739 queue_Prepend(&call->rq, np);
3740 #ifdef RXDEBUG_PACKET
3742 #endif /* RXDEBUG_PACKET */
3744 np = NULL; /* We can't use this anymore */
3747 /* If an ack is requested then set a flag to make sure we
3748 * send an acknowledgement for this packet */
3749 if (flags & RX_REQUEST_ACK) {
3750 ackNeeded = RX_ACK_REQUESTED;
3753 /* Keep track of whether we have received the last packet */
3754 if (flags & RX_LAST_PACKET) {
3755 call->flags |= RX_CALL_HAVE_LAST;
3759 /* Check whether we have all of the packets for this call */
3760 if (call->flags & RX_CALL_HAVE_LAST) {
3761 afs_uint32 tseq; /* temporary sequence number */
3762 struct rx_packet *tp; /* Temporary packet pointer */
3763 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3765 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3766 if (tseq != tp->header.seq)
3768 if (tp->header.flags & RX_LAST_PACKET) {
3769 call->flags |= RX_CALL_RECEIVE_DONE;
3776 /* Provide asynchronous notification for those who want it
3777 * (e.g. multi rx) */
3778 if (call->arrivalProc) {
3779 (*call->arrivalProc) (call, call->arrivalProcHandle,
3780 call->arrivalProcArg);
3781 call->arrivalProc = (void (*)())0;
3784 /* Update last packet received */
3787 /* If there is no server process serving this call, grab
3788 * one, if available. We only need to do this once. If a
3789 * server thread is available, this thread becomes a server
3790 * thread and the server thread becomes a listener thread. */
3792 TryAttach(call, socket, tnop, newcallp, 0);
3795 /* This is not the expected next packet. */
3797 /* Determine whether this is a new or old packet, and if it's
3798 * a new one, whether it fits into the current receive window.
3799 * Also figure out whether the packet was delivered in sequence.
3800 * We use the prev variable to determine whether the new packet
3801 * is the successor of its immediate predecessor in the
3802 * receive queue, and the missing flag to determine whether
3803 * any of this packets predecessors are missing. */
3805 afs_uint32 prev; /* "Previous packet" sequence number */
3806 struct rx_packet *tp; /* Temporary packet pointer */
3807 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3808 int missing; /* Are any predecessors missing? */
3810 /* If the new packet's sequence number has been sent to the
3811 * application already, then this is a duplicate */
3812 if (seq < call->rnext) {
3813 if (rx_stats_active)
3814 rx_atomic_inc(&rx_stats.dupPacketsRead);
3815 rxevent_Cancel(call->delayedAckEvent, call,
3816 RX_CALL_REFCOUNT_DELAY);
3817 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3823 /* If the sequence number is greater than what can be
3824 * accomodated by the current window, then send a negative
3825 * acknowledge and drop the packet */
3826 if ((call->rnext + call->rwind) <= seq) {
3827 rxevent_Cancel(call->delayedAckEvent, call,
3828 RX_CALL_REFCOUNT_DELAY);
3829 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3836 /* Look for the packet in the queue of old received packets */
3837 for (prev = call->rnext - 1, missing =
3838 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3839 /*Check for duplicate packet */
3840 if (seq == tp->header.seq) {
3841 if (rx_stats_active)
3842 rx_atomic_inc(&rx_stats.dupPacketsRead);
3843 rxevent_Cancel(call->delayedAckEvent, call,
3844 RX_CALL_REFCOUNT_DELAY);
3845 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3851 /* If we find a higher sequence packet, break out and
3852 * insert the new packet here. */
3853 if (seq < tp->header.seq)
3855 /* Check for missing packet */
3856 if (tp->header.seq != prev + 1) {
3860 prev = tp->header.seq;
3863 /* Keep track of whether we have received the last packet. */
3864 if (flags & RX_LAST_PACKET) {
3865 call->flags |= RX_CALL_HAVE_LAST;
3868 /* It's within the window: add it to the the receive queue.
3869 * tp is left by the previous loop either pointing at the
3870 * packet before which to insert the new packet, or at the
3871 * queue head if the queue is empty or the packet should be
3873 #ifdef RX_TRACK_PACKETS
3874 np->flags |= RX_PKTFLAG_RQ;
3876 #ifdef RXDEBUG_PACKET
3878 #endif /* RXDEBUG_PACKET */
3879 queue_InsertBefore(tp, np);
3883 /* Check whether we have all of the packets for this call */
3884 if ((call->flags & RX_CALL_HAVE_LAST)
3885 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3886 afs_uint32 tseq; /* temporary sequence number */
3889 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3890 if (tseq != tp->header.seq)
3892 if (tp->header.flags & RX_LAST_PACKET) {
3893 call->flags |= RX_CALL_RECEIVE_DONE;
3900 /* We need to send an ack of the packet is out of sequence,
3901 * or if an ack was requested by the peer. */
3902 if (seq != prev + 1 || missing) {
3903 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3904 } else if (flags & RX_REQUEST_ACK) {
3905 ackNeeded = RX_ACK_REQUESTED;
3908 /* Acknowledge the last packet for each call */
3909 if (flags & RX_LAST_PACKET) {
3920 * If the receiver is waiting for an iovec, fill the iovec
3921 * using the data from the receive queue */
3922 if (call->flags & RX_CALL_IOVEC_WAIT) {
3923 didHardAck = rxi_FillReadVec(call, serial);
3924 /* the call may have been aborted */
3933 /* Wakeup the reader if any */
3934 if ((call->flags & RX_CALL_READER_WAIT)
3935 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3936 || (call->iovNext >= call->iovMax)
3937 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3938 call->flags &= ~RX_CALL_READER_WAIT;
3939 #ifdef RX_ENABLE_LOCKS
3940 CV_BROADCAST(&call->cv_rq);
3942 osi_rxWakeup(&call->rq);
3948 * Send an ack when requested by the peer, or once every
3949 * rxi_SoftAckRate packets until the last packet has been
3950 * received. Always send a soft ack for the last packet in
3951 * the server's reply.
3953 * If we have received all of the packets for the call
3954 * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3955 * the peer can empty its packet queue and cancel all resend
3958 if (call->flags & RX_CALL_RECEIVE_DONE) {
3959 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3960 rxi_AckAll(NULL, call, 0);
3961 } else if (ackNeeded) {
3962 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3963 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3964 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3965 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3966 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3967 } else if (call->nSoftAcks) {
3968 clock_GetTime(&now);
3970 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3971 clock_Add(&when, &rx_lastAckDelay);
3973 clock_Add(&when, &rx_softAckDelay);
3975 if (!call->delayedAckEvent
3976 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3977 rxevent_Cancel(call->delayedAckEvent, call,
3978 RX_CALL_REFCOUNT_DELAY);
3979 MUTEX_ENTER(&rx_refcnt_mutex);
3980 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3981 MUTEX_EXIT(&rx_refcnt_mutex);
3982 call->delayedAckEvent =
3983 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3991 static void rxi_ComputeRate();
3995 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3997 struct rx_peer *peer = conn->peer;
3999 MUTEX_ENTER(&peer->peer_lock);
4000 peer->lastReachTime = clock_Sec();
4001 MUTEX_EXIT(&peer->peer_lock);
4003 MUTEX_ENTER(&conn->conn_data_lock);
4004 if (conn->flags & RX_CONN_ATTACHWAIT) {
4007 conn->flags &= ~RX_CONN_ATTACHWAIT;
4008 MUTEX_EXIT(&conn->conn_data_lock);
4010 for (i = 0; i < RX_MAXCALLS; i++) {
4011 struct rx_call *call = conn->call[i];
4014 MUTEX_ENTER(&call->lock);
4015 /* tnop can be null if newcallp is null */
4016 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4018 MUTEX_EXIT(&call->lock);
4022 MUTEX_EXIT(&conn->conn_data_lock);
4025 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4027 rx_ack_reason(int reason)
4030 case RX_ACK_REQUESTED:
4032 case RX_ACK_DUPLICATE:
4034 case RX_ACK_OUT_OF_SEQUENCE:
4036 case RX_ACK_EXCEEDS_WINDOW:
4038 case RX_ACK_NOSPACE:
4042 case RX_ACK_PING_RESPONSE:
4055 /* The real smarts of the whole thing. */
4057 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4060 struct rx_ackPacket *ap;
4062 struct rx_packet *tp;
4063 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4064 struct rx_connection *conn = call->conn;
4065 struct rx_peer *peer = conn->peer;
4066 struct clock now; /* Current time, for RTT calculations */
4070 /* because there are CM's that are bogus, sending weird values for this. */
4071 afs_uint32 skew = 0;
4076 int newAckCount = 0;
4077 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4078 int pktsize = 0; /* Set if we need to update the peer mtu */
4079 int conn_data_locked = 0;
4081 if (rx_stats_active)
4082 rx_atomic_inc(&rx_stats.ackPacketsRead);
4083 ap = (struct rx_ackPacket *)rx_DataOf(np);
4084 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4086 return np; /* truncated ack packet */
4088 /* depends on ack packet struct */
4089 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4090 first = ntohl(ap->firstPacket);
4091 prev = ntohl(ap->previousPacket);
4092 serial = ntohl(ap->serial);
4093 /* temporarily disabled -- needs to degrade over time
4094 * skew = ntohs(ap->maxSkew); */
4096 /* Ignore ack packets received out of order */
4097 if (first < call->tfirst ||
4098 (first == call->tfirst && prev < call->tprev)) {
4104 if (np->header.flags & RX_SLOW_START_OK) {
4105 call->flags |= RX_CALL_SLOW_START_OK;
4108 if (ap->reason == RX_ACK_PING_RESPONSE)
4109 rxi_UpdatePeerReach(conn, call);
4111 if (conn->lastPacketSizeSeq) {
4112 MUTEX_ENTER(&conn->conn_data_lock);
4113 conn_data_locked = 1;
4114 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4115 pktsize = conn->lastPacketSize;
4116 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4119 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4120 if (!conn_data_locked) {
4121 MUTEX_ENTER(&conn->conn_data_lock);
4122 conn_data_locked = 1;
4124 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4125 /* process mtu ping ack */
4126 pktsize = conn->lastPingSize;
4127 conn->lastPingSizeSer = conn->lastPingSize = 0;
4131 if (conn_data_locked) {
4132 MUTEX_EXIT(&conn->conn_data_lock);
4133 conn_data_locked = 0;
4137 if (rxdebug_active) {
4141 len = _snprintf(msg, sizeof(msg),
4142 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4143 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4144 ntohl(ap->serial), ntohl(ap->previousPacket),
4145 (unsigned int)np->header.seq, (unsigned int)skew,
4146 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4150 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4151 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4155 OutputDebugString(msg);
4157 #else /* AFS_NT40_ENV */
4160 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4161 ap->reason, ntohl(ap->previousPacket),
4162 (unsigned int)np->header.seq, (unsigned int)serial,
4163 (unsigned int)skew, ntohl(ap->firstPacket));
4166 for (offset = 0; offset < nAcks; offset++)
4167 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4172 #endif /* AFS_NT40_ENV */
4175 MUTEX_ENTER(&peer->peer_lock);
4178 * Start somewhere. Can't assume we can send what we can receive,
4179 * but we are clearly receiving.
4181 if (!peer->maxPacketSize)
4182 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4184 if (pktsize > peer->maxPacketSize) {
4185 peer->maxPacketSize = pktsize;
4186 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4187 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4188 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4189 rxi_ScheduleGrowMTUEvent(call, 1);
4194 /* Update the outgoing packet skew value to the latest value of
4195 * the peer's incoming packet skew value. The ack packet, of
4196 * course, could arrive out of order, but that won't affect things
4198 peer->outPacketSkew = skew;
4200 /* Check for packets that no longer need to be transmitted, and
4201 * discard them. This only applies to packets positively
4202 * acknowledged as having been sent to the peer's upper level.
4203 * All other packets must be retained. So only packets with
4204 * sequence numbers < ap->firstPacket are candidates. */
4206 clock_GetTime(&now);
4208 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4209 if (tp->header.seq >= first)
4211 call->tfirst = tp->header.seq + 1;
4213 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4216 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4220 rxi_ComputeRate(call->conn->peer, call, p, np, ap->reason);
4223 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4224 /* XXX Hack. Because we have to release the global rx lock when sending
4225 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4226 * in rxi_Start sending packets out because packets may move to the
4227 * freePacketQueue as result of being here! So we drop these packets until
4228 * we're safely out of the traversing. Really ugly!
4229 * To make it even uglier, if we're using fine grain locking, we can
4230 * set the ack bits in the packets and have rxi_Start remove the packets
4231 * when it's done transmitting.
4233 if (call->flags & RX_CALL_TQ_BUSY) {
4234 #ifdef RX_ENABLE_LOCKS
4235 tp->flags |= RX_PKTFLAG_ACKED;
4236 call->flags |= RX_CALL_TQ_SOME_ACKED;
4237 #else /* RX_ENABLE_LOCKS */
4239 #endif /* RX_ENABLE_LOCKS */
4241 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4244 #ifdef RX_TRACK_PACKETS
4245 tp->flags &= ~RX_PKTFLAG_TQ;
4247 #ifdef RXDEBUG_PACKET
4249 #endif /* RXDEBUG_PACKET */
4250 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4255 /* Give rate detector a chance to respond to ping requests */
4256 if (ap->reason == RX_ACK_PING_RESPONSE) {
4257 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4261 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4263 /* Now go through explicit acks/nacks and record the results in
4264 * the waiting packets. These are packets that can't be released
4265 * yet, even with a positive acknowledge. This positive
4266 * acknowledge only means the packet has been received by the
4267 * peer, not that it will be retained long enough to be sent to
4268 * the peer's upper level. In addition, reset the transmit timers
4269 * of any missing packets (those packets that must be missing
4270 * because this packet was out of sequence) */
4272 call->nSoftAcked = 0;
4273 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4275 /* Set the acknowledge flag per packet based on the
4276 * information in the ack packet. An acknowlegded packet can
4277 * be downgraded when the server has discarded a packet it
4278 * soacked previously, or when an ack packet is received
4279 * out of sequence. */
4280 if (tp->header.seq < first) {
4281 /* Implicit ack information */
4282 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4285 tp->flags |= RX_PKTFLAG_ACKED;
4286 } else if (tp->header.seq < first + nAcks) {
4287 /* Explicit ack information: set it in the packet appropriately */
4288 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4289 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4291 tp->flags |= RX_PKTFLAG_ACKED;
4293 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4295 rxi_ComputeRate(call->conn->peer, call, tp, np,
4304 } else /* RX_ACK_TYPE_NACK */ {
4305 tp->flags &= ~RX_PKTFLAG_ACKED;
4309 if (tp->flags & RX_PKTFLAG_ACKED) {
4310 tp->flags &= ~RX_PKTFLAG_ACKED;
4316 * Following the suggestion of Phil Kern, we back off the peer's
4317 * timeout value for future packets until a successful response
4318 * is received for an initial transmission.
4320 if (missing && !peer->backedOff) {
4321 struct clock c = peer->timeout;
4322 struct clock max_to = {3, 0};
4324 clock_Add(&peer->timeout, &c);
4325 if (clock_Gt(&peer->timeout, &max_to))
4326 peer->timeout = max_to;
4327 peer->backedOff = 1;
4330 /* If packet isn't yet acked, and it has been transmitted at least
4331 * once, reset retransmit time using latest timeout
4332 * ie, this should readjust the retransmit timer for all outstanding
4333 * packets... So we don't just retransmit when we should know better*/
4335 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4336 tp->retryTime = tp->timeSent;
4337 clock_Add(&tp->retryTime, &peer->timeout);
4338 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4339 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4343 /* If the window has been extended by this acknowledge packet,
4344 * then wakeup a sender waiting in alloc for window space, or try
4345 * sending packets now, if he's been sitting on packets due to
4346 * lack of window space */
4347 if (call->tnext < (call->tfirst + call->twind)) {
4348 #ifdef RX_ENABLE_LOCKS
4349 CV_SIGNAL(&call->cv_twind);
4351 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4352 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4353 osi_rxWakeup(&call->twind);
4356 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4357 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4361 /* if the ack packet has a receivelen field hanging off it,
4362 * update our state */
4363 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4366 /* If the ack packet has a "recommended" size that is less than
4367 * what I am using now, reduce my size to match */
4368 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4369 (int)sizeof(afs_int32), &tSize);
4370 tSize = (afs_uint32) ntohl(tSize);
4371 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4373 /* Get the maximum packet size to send to this peer */
4374 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4376 tSize = (afs_uint32) ntohl(tSize);
4377 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4378 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4380 /* sanity check - peer might have restarted with different params.
4381 * If peer says "send less", dammit, send less... Peer should never
4382 * be unable to accept packets of the size that prior AFS versions would
4383 * send without asking. */
4384 if (peer->maxMTU != tSize) {
4385 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4387 peer->maxMTU = tSize;
4388 peer->MTU = MIN(tSize, peer->MTU);
4389 call->MTU = MIN(call->MTU, tSize);
4392 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4395 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4396 (int)sizeof(afs_int32), &tSize);
4397 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4398 if (tSize < call->twind) { /* smaller than our send */
4399 call->twind = tSize; /* window, we must send less... */
4400 call->ssthresh = MIN(call->twind, call->ssthresh);
4401 call->conn->twind[call->channel] = call->twind;
4404 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4405 * network MTU confused with the loopback MTU. Calculate the
4406 * maximum MTU here for use in the slow start code below.
4408 /* Did peer restart with older RX version? */
4409 if (peer->maxDgramPackets > 1) {
4410 peer->maxDgramPackets = 1;
4412 } else if (np->length >=
4413 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4416 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4417 sizeof(afs_int32), &tSize);
4418 tSize = (afs_uint32) ntohl(tSize);
4420 * As of AFS 3.5 we set the send window to match the receive window.
4422 if (tSize < call->twind) {
4423 call->twind = tSize;
4424 call->conn->twind[call->channel] = call->twind;
4425 call->ssthresh = MIN(call->twind, call->ssthresh);
4426 } else if (tSize > call->twind) {
4427 call->twind = tSize;
4428 call->conn->twind[call->channel] = call->twind;
4432 * As of AFS 3.5, a jumbogram is more than one fixed size
4433 * packet transmitted in a single UDP datagram. If the remote
4434 * MTU is smaller than our local MTU then never send a datagram
4435 * larger than the natural MTU.
4438 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4439 (int)sizeof(afs_int32), &tSize);
4440 maxDgramPackets = (afs_uint32) ntohl(tSize);
4441 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4443 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4444 if (maxDgramPackets > 1) {
4445 peer->maxDgramPackets = maxDgramPackets;
4446 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4448 peer->maxDgramPackets = 1;
4449 call->MTU = peer->natMTU;
4451 } else if (peer->maxDgramPackets > 1) {
4452 /* Restarted with lower version of RX */
4453 peer->maxDgramPackets = 1;
4455 } else if (peer->maxDgramPackets > 1
4456 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4457 /* Restarted with lower version of RX */
4458 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4459 peer->natMTU = OLD_MAX_PACKET_SIZE;
4460 peer->MTU = OLD_MAX_PACKET_SIZE;
4461 peer->maxDgramPackets = 1;
4462 peer->nDgramPackets = 1;
4464 call->MTU = OLD_MAX_PACKET_SIZE;
4469 * Calculate how many datagrams were successfully received after
4470 * the first missing packet and adjust the negative ack counter
4475 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4476 if (call->nNacks < nNacked) {
4477 call->nNacks = nNacked;
4480 call->nAcks += newAckCount;
4484 if (call->flags & RX_CALL_FAST_RECOVER) {
4486 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4488 call->flags &= ~RX_CALL_FAST_RECOVER;
4489 call->cwind = call->nextCwind;
4490 call->nextCwind = 0;
4493 call->nCwindAcks = 0;
4494 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4495 /* Three negative acks in a row trigger congestion recovery */
4496 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4497 MUTEX_EXIT(&peer->peer_lock);
4498 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4499 /* someone else is waiting to start recovery */
4502 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4503 rxi_WaitforTQBusy(call);
4504 MUTEX_ENTER(&peer->peer_lock);
4505 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4506 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4507 call->flags |= RX_CALL_FAST_RECOVER;
4508 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4510 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4511 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4512 call->nextCwind = call->ssthresh;
4515 peer->MTU = call->MTU;
4516 peer->cwind = call->nextCwind;
4517 peer->nDgramPackets = call->nDgramPackets;
4519 call->congestSeq = peer->congestSeq;
4520 /* Reset the resend times on the packets that were nacked
4521 * so we will retransmit as soon as the window permits*/
4522 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4524 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4525 clock_Zero(&tp->retryTime);
4527 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4532 /* If cwind is smaller than ssthresh, then increase
4533 * the window one packet for each ack we receive (exponential
4535 * If cwind is greater than or equal to ssthresh then increase
4536 * the congestion window by one packet for each cwind acks we
4537 * receive (linear growth). */
4538 if (call->cwind < call->ssthresh) {
4540 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4541 call->nCwindAcks = 0;
4543 call->nCwindAcks += newAckCount;
4544 if (call->nCwindAcks >= call->cwind) {
4545 call->nCwindAcks = 0;
4546 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4550 * If we have received several acknowledgements in a row then
4551 * it is time to increase the size of our datagrams
4553 if ((int)call->nAcks > rx_nDgramThreshold) {
4554 if (peer->maxDgramPackets > 1) {
4555 if (call->nDgramPackets < peer->maxDgramPackets) {
4556 call->nDgramPackets++;
4558 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4559 } else if (call->MTU < peer->maxMTU) {
4560 /* don't upgrade if we can't handle it */
4561 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4562 call->MTU = peer->ifMTU;
4564 call->MTU += peer->natMTU;
4565 call->MTU = MIN(call->MTU, peer->maxMTU);
4572 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4574 /* Servers need to hold the call until all response packets have
4575 * been acknowledged. Soft acks are good enough since clients
4576 * are not allowed to clear their receive queues. */
4577 if (call->state == RX_STATE_HOLD
4578 && call->tfirst + call->nSoftAcked >= call->tnext) {
4579 call->state = RX_STATE_DALLY;
4580 rxi_ClearTransmitQueue(call, 0);
4581 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4582 } else if (!queue_IsEmpty(&call->tq)) {
4583 rxi_Start(0, call, 0, istack);
4588 /* Received a response to a challenge packet */
4590 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4591 struct rx_packet *np, int istack)
4595 /* Ignore the packet if we're the client */
4596 if (conn->type == RX_CLIENT_CONNECTION)
4599 /* If already authenticated, ignore the packet (it's probably a retry) */
4600 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4603 /* Otherwise, have the security object evaluate the response packet */
4604 error = RXS_CheckResponse(conn->securityObject, conn, np);
4606 /* If the response is invalid, reset the connection, sending
4607 * an abort to the peer */
4611 rxi_ConnectionError(conn, error);
4612 MUTEX_ENTER(&conn->conn_data_lock);
4613 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4614 MUTEX_EXIT(&conn->conn_data_lock);
4617 /* If the response is valid, any calls waiting to attach
4618 * servers can now do so */
4621 for (i = 0; i < RX_MAXCALLS; i++) {
4622 struct rx_call *call = conn->call[i];
4624 MUTEX_ENTER(&call->lock);
4625 if (call->state == RX_STATE_PRECALL)
4626 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4627 /* tnop can be null if newcallp is null */
4628 MUTEX_EXIT(&call->lock);
4632 /* Update the peer reachability information, just in case
4633 * some calls went into attach-wait while we were waiting
4634 * for authentication..
4636 rxi_UpdatePeerReach(conn, NULL);
4641 /* A client has received an authentication challenge: the security
4642 * object is asked to cough up a respectable response packet to send
4643 * back to the server. The server is responsible for retrying the
4644 * challenge if it fails to get a response. */
4647 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4648 struct rx_packet *np, int istack)
4652 /* Ignore the challenge if we're the server */
4653 if (conn->type == RX_SERVER_CONNECTION)
4656 /* Ignore the challenge if the connection is otherwise idle; someone's
4657 * trying to use us as an oracle. */
4658 if (!rxi_HasActiveCalls(conn))
4661 /* Send the security object the challenge packet. It is expected to fill
4662 * in the response. */
4663 error = RXS_GetResponse(conn->securityObject, conn, np);
4665 /* If the security object is unable to return a valid response, reset the
4666 * connection and send an abort to the peer. Otherwise send the response
4667 * packet to the peer connection. */
4669 rxi_ConnectionError(conn, error);
4670 MUTEX_ENTER(&conn->conn_data_lock);
4671 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4672 MUTEX_EXIT(&conn->conn_data_lock);
4674 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4675 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4681 /* Find an available server process to service the current request in
4682 * the given call structure. If one isn't available, queue up this
4683 * call so it eventually gets one */
4685 rxi_AttachServerProc(struct rx_call *call,
4686 osi_socket socket, int *tnop,
4687 struct rx_call **newcallp)
4689 struct rx_serverQueueEntry *sq;
4690 struct rx_service *service = call->conn->service;
4693 /* May already be attached */
4694 if (call->state == RX_STATE_ACTIVE)
4697 MUTEX_ENTER(&rx_serverPool_lock);
4699 haveQuota = QuotaOK(service);
4700 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4701 /* If there are no processes available to service this call,
4702 * put the call on the incoming call queue (unless it's
4703 * already on the queue).
4705 #ifdef RX_ENABLE_LOCKS
4707 ReturnToServerPool(service);
4708 #endif /* RX_ENABLE_LOCKS */
4710 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4711 call->flags |= RX_CALL_WAIT_PROC;
4712 rx_atomic_inc(&rx_nWaiting);
4713 rx_atomic_inc(&rx_nWaited);
4714 rxi_calltrace(RX_CALL_ARRIVAL, call);
4715 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4716 queue_Append(&rx_incomingCallQueue, call);
4719 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4721 /* If hot threads are enabled, and both newcallp and sq->socketp
4722 * are non-null, then this thread will process the call, and the
4723 * idle server thread will start listening on this threads socket.
4726 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4729 *sq->socketp = socket;
4730 clock_GetTime(&call->startTime);
4731 MUTEX_ENTER(&rx_refcnt_mutex);
4732 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4733 MUTEX_EXIT(&rx_refcnt_mutex);
4737 if (call->flags & RX_CALL_WAIT_PROC) {
4738 /* Conservative: I don't think this should happen */
4739 call->flags &= ~RX_CALL_WAIT_PROC;
4740 if (queue_IsOnQueue(call)) {
4743 rx_atomic_dec(&rx_nWaiting);
4746 call->state = RX_STATE_ACTIVE;
4747 call->mode = RX_MODE_RECEIVING;
4748 #ifdef RX_KERNEL_TRACE
4750 int glockOwner = ISAFS_GLOCK();
4753 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4754 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4760 if (call->flags & RX_CALL_CLEARED) {
4761 /* send an ack now to start the packet flow up again */
4762 call->flags &= ~RX_CALL_CLEARED;
4763 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4765 #ifdef RX_ENABLE_LOCKS
4768 service->nRequestsRunning++;
4769 MUTEX_ENTER(&rx_quota_mutex);
4770 if (service->nRequestsRunning <= service->minProcs)
4773 MUTEX_EXIT(&rx_quota_mutex);
4777 MUTEX_EXIT(&rx_serverPool_lock);
4780 /* Delay the sending of an acknowledge event for a short while, while
4781 * a new call is being prepared (in the case of a client) or a reply
4782 * is being prepared (in the case of a server). Rather than sending
4783 * an ack packet, an ACKALL packet is sent. */
4785 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4787 #ifdef RX_ENABLE_LOCKS
4789 MUTEX_ENTER(&call->lock);
4790 call->delayedAckEvent = NULL;
4791 MUTEX_ENTER(&rx_refcnt_mutex);
4792 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4793 MUTEX_EXIT(&rx_refcnt_mutex);
4795 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4796 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4798 MUTEX_EXIT(&call->lock);
4799 #else /* RX_ENABLE_LOCKS */
4801 call->delayedAckEvent = NULL;
4802 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4803 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4804 #endif /* RX_ENABLE_LOCKS */
4808 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4810 struct rx_call *call = arg1;
4811 #ifdef RX_ENABLE_LOCKS
4813 MUTEX_ENTER(&call->lock);
4814 if (event == call->delayedAckEvent)
4815 call->delayedAckEvent = NULL;
4816 MUTEX_ENTER(&rx_refcnt_mutex);
4817 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4818 MUTEX_EXIT(&rx_refcnt_mutex);
4820 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4822 MUTEX_EXIT(&call->lock);
4823 #else /* RX_ENABLE_LOCKS */
4825 call->delayedAckEvent = NULL;
4826 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4827 #endif /* RX_ENABLE_LOCKS */
4831 #ifdef RX_ENABLE_LOCKS
4832 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4833 * clearing them out.
4836 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4838 struct rx_packet *p, *tp;
4841 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4842 p->flags |= RX_PKTFLAG_ACKED;
4846 call->flags |= RX_CALL_TQ_CLEARME;
4847 call->flags |= RX_CALL_TQ_SOME_ACKED;
4850 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4851 call->tfirst = call->tnext;
4852 call->nSoftAcked = 0;
4854 if (call->flags & RX_CALL_FAST_RECOVER) {
4855 call->flags &= ~RX_CALL_FAST_RECOVER;
4856 call->cwind = call->nextCwind;
4857 call->nextCwind = 0;
4860 CV_SIGNAL(&call->cv_twind);
4862 #endif /* RX_ENABLE_LOCKS */
4864 /* Clear out the transmit queue for the current call (all packets have
4865 * been received by peer) */
4867 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4869 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4870 struct rx_packet *p, *tp;
4872 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4874 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4875 p->flags |= RX_PKTFLAG_ACKED;
4879 call->flags |= RX_CALL_TQ_CLEARME;
4880 call->flags |= RX_CALL_TQ_SOME_ACKED;
4883 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4884 #ifdef RXDEBUG_PACKET
4886 #endif /* RXDEBUG_PACKET */
4887 rxi_FreePackets(0, &call->tq);
4888 rxi_WakeUpTransmitQueue(call);
4889 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4890 call->flags &= ~RX_CALL_TQ_CLEARME;
4892 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4894 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4895 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4896 call->nSoftAcked = 0;
4898 if (call->flags & RX_CALL_FAST_RECOVER) {
4899 call->flags &= ~RX_CALL_FAST_RECOVER;
4900 call->cwind = call->nextCwind;
4902 #ifdef RX_ENABLE_LOCKS
4903 CV_SIGNAL(&call->cv_twind);
4905 osi_rxWakeup(&call->twind);
4910 rxi_ClearReceiveQueue(struct rx_call *call)
4912 if (queue_IsNotEmpty(&call->rq)) {
4915 count = rxi_FreePackets(0, &call->rq);
4916 rx_packetReclaims += count;
4917 #ifdef RXDEBUG_PACKET
4919 if ( call->rqc != 0 )
4920 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
4922 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4924 if (call->state == RX_STATE_PRECALL) {
4925 call->flags |= RX_CALL_CLEARED;
4929 /* Send an abort packet for the specified call */
4931 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4932 int istack, int force)
4935 struct clock when, now;
4940 /* Clients should never delay abort messages */
4941 if (rx_IsClientConn(call->conn))
4944 if (call->abortCode != call->error) {
4945 call->abortCode = call->error;
4946 call->abortCount = 0;
4949 if (force || rxi_callAbortThreshhold == 0
4950 || call->abortCount < rxi_callAbortThreshhold) {
4951 if (call->delayedAbortEvent) {
4952 rxevent_Cancel(call->delayedAbortEvent, call,
4953 RX_CALL_REFCOUNT_ABORT);
4955 error = htonl(call->error);
4958 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4959 (char *)&error, sizeof(error), istack);
4960 } else if (!call->delayedAbortEvent) {
4961 clock_GetTime(&now);
4963 clock_Addmsec(&when, rxi_callAbortDelay);
4964 MUTEX_ENTER(&rx_refcnt_mutex);
4965 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4966 MUTEX_EXIT(&rx_refcnt_mutex);
4967 call->delayedAbortEvent =
4968 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4973 /* Send an abort packet for the specified connection. Packet is an
4974 * optional pointer to a packet that can be used to send the abort.
4975 * Once the number of abort messages reaches the threshhold, an
4976 * event is scheduled to send the abort. Setting the force flag
4977 * overrides sending delayed abort messages.
4979 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4980 * to send the abort packet.
4983 rxi_SendConnectionAbort(struct rx_connection *conn,
4984 struct rx_packet *packet, int istack, int force)
4987 struct clock when, now;
4992 /* Clients should never delay abort messages */
4993 if (rx_IsClientConn(conn))
4996 if (force || rxi_connAbortThreshhold == 0
4997 || conn->abortCount < rxi_connAbortThreshhold) {
4998 if (conn->delayedAbortEvent) {
4999 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
5001 error = htonl(conn->error);
5003 MUTEX_EXIT(&conn->conn_data_lock);
5005 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5006 RX_PACKET_TYPE_ABORT, (char *)&error,
5007 sizeof(error), istack);
5008 MUTEX_ENTER(&conn->conn_data_lock);
5009 } else if (!conn->delayedAbortEvent) {
5010 clock_GetTime(&now);
5012 clock_Addmsec(&when, rxi_connAbortDelay);
5013 conn->delayedAbortEvent =
5014 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
5019 /* Associate an error all of the calls owned by a connection. Called
5020 * with error non-zero. This is only for really fatal things, like
5021 * bad authentication responses. The connection itself is set in
5022 * error at this point, so that future packets received will be
5025 rxi_ConnectionError(struct rx_connection *conn,
5031 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5033 MUTEX_ENTER(&conn->conn_data_lock);
5034 if (conn->challengeEvent)
5035 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
5036 if (conn->natKeepAliveEvent)
5037 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
5038 if (conn->checkReachEvent) {
5039 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
5040 conn->checkReachEvent = 0;
5041 conn->flags &= ~RX_CONN_ATTACHWAIT;
5042 MUTEX_ENTER(&rx_refcnt_mutex);
5044 MUTEX_EXIT(&rx_refcnt_mutex);
5046 MUTEX_EXIT(&conn->conn_data_lock);
5047 for (i = 0; i < RX_MAXCALLS; i++) {
5048 struct rx_call *call = conn->call[i];
5050 MUTEX_ENTER(&call->lock);
5051 rxi_CallError(call, error);
5052 MUTEX_EXIT(&call->lock);
5055 conn->error = error;
5056 if (rx_stats_active)
5057 rx_atomic_inc(&rx_stats.fatalErrors);
5062 * Interrupt an in-progress call with the specified error and wakeup waiters.
5064 * @param[in] call The call to interrupt
5065 * @param[in] error The error code to send to the peer
5068 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5070 MUTEX_ENTER(&call->lock);
5071 rxi_CallError(call, error);
5072 rxi_SendCallAbort(call, NULL, 0, 1);
5073 MUTEX_EXIT(&call->lock);
5077 rxi_CallError(struct rx_call *call, afs_int32 error)
5080 osirx_AssertMine(&call->lock, "rxi_CallError");
5082 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5084 error = call->error;
5086 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5087 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5088 rxi_ResetCall(call, 0);
5091 rxi_ResetCall(call, 0);
5093 call->error = error;
5096 /* Reset various fields in a call structure, and wakeup waiting
5097 * processes. Some fields aren't changed: state & mode are not
5098 * touched (these must be set by the caller), and bufptr, nLeft, and
5099 * nFree are not reset, since these fields are manipulated by
5100 * unprotected macros, and may only be reset by non-interrupting code.
5103 /* this code requires that call->conn be set properly as a pre-condition. */
5104 #endif /* ADAPT_WINDOW */
5107 rxi_ResetCall(struct rx_call *call, int newcall)
5110 struct rx_peer *peer;
5111 struct rx_packet *packet;
5113 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5115 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5117 /* Notify anyone who is waiting for asynchronous packet arrival */
5118 if (call->arrivalProc) {
5119 (*call->arrivalProc) (call, call->arrivalProcHandle,
5120 call->arrivalProcArg);
5121 call->arrivalProc = (void (*)())0;
5124 if (call->growMTUEvent)
5125 rxevent_Cancel(call->growMTUEvent, call,
5126 RX_CALL_REFCOUNT_ALIVE);
5128 if (call->delayedAbortEvent) {
5129 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5130 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5132 rxi_SendCallAbort(call, packet, 0, 1);
5133 rxi_FreePacket(packet);
5138 * Update the peer with the congestion information in this call
5139 * so other calls on this connection can pick up where this call
5140 * left off. If the congestion sequence numbers don't match then
5141 * another call experienced a retransmission.
5143 peer = call->conn->peer;
5144 MUTEX_ENTER(&peer->peer_lock);
5146 if (call->congestSeq == peer->congestSeq) {
5147 peer->cwind = MAX(peer->cwind, call->cwind);
5148 peer->MTU = MAX(peer->MTU, call->MTU);
5149 peer->nDgramPackets =
5150 MAX(peer->nDgramPackets, call->nDgramPackets);
5153 call->abortCode = 0;
5154 call->abortCount = 0;
5156 if (peer->maxDgramPackets > 1) {
5157 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5159 call->MTU = peer->MTU;
5161 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5162 call->ssthresh = rx_maxSendWindow;
5163 call->nDgramPackets = peer->nDgramPackets;
5164 call->congestSeq = peer->congestSeq;
5165 MUTEX_EXIT(&peer->peer_lock);
5167 flags = call->flags;
5168 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5169 rxi_WaitforTQBusy(call);
5170 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5172 rxi_ClearTransmitQueue(call, 1);
5173 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5174 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5178 if ((flags & RX_CALL_PEER_BUSY)) {
5179 /* The call channel is still busy; resetting the call doesn't change
5181 call->flags |= RX_CALL_PEER_BUSY;
5184 rxi_ClearReceiveQueue(call);
5185 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5189 call->twind = call->conn->twind[call->channel];
5190 call->rwind = call->conn->rwind[call->channel];
5191 call->nSoftAcked = 0;
5192 call->nextCwind = 0;
5195 call->nCwindAcks = 0;
5196 call->nSoftAcks = 0;
5197 call->nHardAcks = 0;
5199 call->tfirst = call->rnext = call->tnext = 1;
5202 call->lastAcked = 0;
5203 call->localStatus = call->remoteStatus = 0;
5205 if (flags & RX_CALL_READER_WAIT) {
5206 #ifdef RX_ENABLE_LOCKS
5207 CV_BROADCAST(&call->cv_rq);
5209 osi_rxWakeup(&call->rq);
5212 if (flags & RX_CALL_WAIT_PACKETS) {
5213 MUTEX_ENTER(&rx_freePktQ_lock);
5214 rxi_PacketsUnWait(); /* XXX */
5215 MUTEX_EXIT(&rx_freePktQ_lock);
5217 #ifdef RX_ENABLE_LOCKS
5218 CV_SIGNAL(&call->cv_twind);
5220 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5221 osi_rxWakeup(&call->twind);
5224 #ifdef RX_ENABLE_LOCKS
5225 /* The following ensures that we don't mess with any queue while some
5226 * other thread might also be doing so. The call_queue_lock field is
5227 * is only modified under the call lock. If the call is in the process
5228 * of being removed from a queue, the call is not locked until the
5229 * the queue lock is dropped and only then is the call_queue_lock field
5230 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5231 * Note that any other routine which removes a call from a queue has to
5232 * obtain the queue lock before examing the queue and removing the call.
5234 if (call->call_queue_lock) {
5235 MUTEX_ENTER(call->call_queue_lock);
5236 if (queue_IsOnQueue(call)) {
5238 if (flags & RX_CALL_WAIT_PROC) {
5239 rx_atomic_dec(&rx_nWaiting);
5242 MUTEX_EXIT(call->call_queue_lock);
5243 CLEAR_CALL_QUEUE_LOCK(call);
5245 #else /* RX_ENABLE_LOCKS */
5246 if (queue_IsOnQueue(call)) {
5248 if (flags & RX_CALL_WAIT_PROC)
5249 rx_atomic_dec(&rx_nWaiting);
5251 #endif /* RX_ENABLE_LOCKS */
5253 rxi_KeepAliveOff(call);
5254 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5257 /* Send an acknowledge for the indicated packet (seq,serial) of the
5258 * indicated call, for the indicated reason (reason). This
5259 * acknowledge will specifically acknowledge receiving the packet, and
5260 * will also specify which other packets for this call have been
5261 * received. This routine returns the packet that was used to the
5262 * caller. The caller is responsible for freeing it or re-using it.
5263 * This acknowledgement also returns the highest sequence number
5264 * actually read out by the higher level to the sender; the sender
5265 * promises to keep around packets that have not been read by the
5266 * higher level yet (unless, of course, the sender decides to abort
5267 * the call altogether). Any of p, seq, serial, pflags, or reason may
5268 * be set to zero without ill effect. That is, if they are zero, they
5269 * will not convey any information.
5270 * NOW there is a trailer field, after the ack where it will safely be
5271 * ignored by mundanes, which indicates the maximum size packet this
5272 * host can swallow. */
5274 struct rx_packet *optionalPacket; use to send ack (or null)
5275 int seq; Sequence number of the packet we are acking
5276 int serial; Serial number of the packet
5277 int pflags; Flags field from packet header
5278 int reason; Reason an acknowledge was prompted
5282 rxi_SendAck(struct rx_call *call,
5283 struct rx_packet *optionalPacket, int serial, int reason,
5286 struct rx_ackPacket *ap;
5287 struct rx_packet *rqp;
5288 struct rx_packet *nxp; /* For queue_Scan */
5289 struct rx_packet *p;
5292 afs_uint32 padbytes = 0;
5293 #ifdef RX_ENABLE_TSFPQ
5294 struct rx_ts_info_t * rx_ts_info;
5298 * Open the receive window once a thread starts reading packets
5300 if (call->rnext > 1) {
5301 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5304 /* Don't attempt to grow MTU if this is a critical ping */
5305 if (reason == RX_ACK_MTU) {
5306 /* keep track of per-call attempts, if we're over max, do in small
5307 * otherwise in larger? set a size to increment by, decrease
5310 if (call->conn->peer->maxPacketSize &&
5311 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5313 padbytes = call->conn->peer->maxPacketSize+16;
5315 padbytes = call->conn->peer->maxMTU + 128;
5317 /* do always try a minimum size ping */
5318 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5320 /* subtract the ack payload */
5321 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5322 reason = RX_ACK_PING;
5325 call->nHardAcks = 0;
5326 call->nSoftAcks = 0;
5327 if (call->rnext > call->lastAcked)
5328 call->lastAcked = call->rnext;
5332 rx_computelen(p, p->length); /* reset length, you never know */
5333 } /* where that's been... */
5334 #ifdef RX_ENABLE_TSFPQ
5336 RX_TS_INFO_GET(rx_ts_info);
5337 if ((p = rx_ts_info->local_special_packet)) {
5338 rx_computelen(p, p->length);
5339 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5340 rx_ts_info->local_special_packet = p;
5341 } else { /* We won't send the ack, but don't panic. */
5342 return optionalPacket;
5346 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5347 /* We won't send the ack, but don't panic. */
5348 return optionalPacket;
5353 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5356 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5357 #ifndef RX_ENABLE_TSFPQ
5358 if (!optionalPacket)
5361 return optionalPacket;
5363 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5364 if (rx_Contiguous(p) < templ) {
5365 #ifndef RX_ENABLE_TSFPQ
5366 if (!optionalPacket)
5369 return optionalPacket;
5374 /* MTUXXX failing to send an ack is very serious. We should */
5375 /* try as hard as possible to send even a partial ack; it's */
5376 /* better than nothing. */
5377 ap = (struct rx_ackPacket *)rx_DataOf(p);
5378 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5379 ap->reason = reason;
5381 /* The skew computation used to be bogus, I think it's better now. */
5382 /* We should start paying attention to skew. XXX */
5383 ap->serial = htonl(serial);
5384 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5386 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5387 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5389 /* No fear of running out of ack packet here because there can only be at most
5390 * one window full of unacknowledged packets. The window size must be constrained
5391 * to be less than the maximum ack size, of course. Also, an ack should always
5392 * fit into a single packet -- it should not ever be fragmented. */
5393 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5394 if (!rqp || !call->rq.next
5395 || (rqp->header.seq > (call->rnext + call->rwind))) {
5396 #ifndef RX_ENABLE_TSFPQ
5397 if (!optionalPacket)
5400 rxi_CallError(call, RX_CALL_DEAD);
5401 return optionalPacket;
5404 while (rqp->header.seq > call->rnext + offset)
5405 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5406 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5408 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5409 #ifndef RX_ENABLE_TSFPQ
5410 if (!optionalPacket)
5413 rxi_CallError(call, RX_CALL_DEAD);
5414 return optionalPacket;
5419 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5421 /* these are new for AFS 3.3 */
5422 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5423 templ = htonl(templ);
5424 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5425 templ = htonl(call->conn->peer->ifMTU);
5426 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5427 sizeof(afs_int32), &templ);
5429 /* new for AFS 3.4 */
5430 templ = htonl(call->rwind);
5431 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5432 sizeof(afs_int32), &templ);
5434 /* new for AFS 3.5 */
5435 templ = htonl(call->conn->peer->ifDgramPackets);
5436 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5437 sizeof(afs_int32), &templ);
5439 p->header.serviceId = call->conn->serviceId;
5440 p->header.cid = (call->conn->cid | call->channel);
5441 p->header.callNumber = *call->callNumber;
5443 p->header.securityIndex = call->conn->securityIndex;
5444 p->header.epoch = call->conn->epoch;
5445 p->header.type = RX_PACKET_TYPE_ACK;
5446 p->header.flags = RX_SLOW_START_OK;
5447 if (reason == RX_ACK_PING) {
5448 p->header.flags |= RX_REQUEST_ACK;
5450 clock_GetTime(&call->pingRequestTime);
5453 p->length = padbytes +
5454 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5457 /* not fast but we can potentially use this if truncated
5458 * fragments are delivered to figure out the mtu.
5460 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5461 sizeof(afs_int32), sizeof(afs_int32),
5465 if (call->conn->type == RX_CLIENT_CONNECTION)
5466 p->header.flags |= RX_CLIENT_INITIATED;
5470 if (rxdebug_active) {
5474 len = _snprintf(msg, sizeof(msg),
5475 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5476 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5477 ntohl(ap->serial), ntohl(ap->previousPacket),
5478 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5479 ap->nAcks, ntohs(ap->bufferSpace) );
5483 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5484 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5488 OutputDebugString(msg);
5490 #else /* AFS_NT40_ENV */
5492 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5493 ap->reason, ntohl(ap->previousPacket),
5494 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5496 for (offset = 0; offset < ap->nAcks; offset++)
5497 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5502 #endif /* AFS_NT40_ENV */
5505 int i, nbytes = p->length;
5507 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5508 if (nbytes <= p->wirevec[i].iov_len) {
5511 savelen = p->wirevec[i].iov_len;
5513 p->wirevec[i].iov_len = nbytes;
5515 rxi_Send(call, p, istack);
5516 p->wirevec[i].iov_len = savelen;
5520 nbytes -= p->wirevec[i].iov_len;
5523 if (rx_stats_active)
5524 rx_atomic_inc(&rx_stats.ackPacketsSent);
5525 #ifndef RX_ENABLE_TSFPQ
5526 if (!optionalPacket)
5529 return optionalPacket; /* Return packet for re-use by caller */
5533 struct rx_packet **list;
5538 /* Send all of the packets in the list in single datagram */
5540 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5541 int istack, int moreFlag)
5546 struct clock now, retryTime;
5547 struct rx_connection *conn = call->conn;
5548 struct rx_peer *peer = conn->peer;
5550 MUTEX_ENTER(&peer->peer_lock);
5551 peer->nSent += xmit->len;
5552 if (xmit->resending)
5553 peer->reSends += xmit->len;
5554 retryTime = peer->timeout;
5555 MUTEX_EXIT(&peer->peer_lock);
5557 if (rx_stats_active) {
5558 if (xmit->resending)
5559 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5561 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5564 clock_GetTime(&now);
5565 clock_Add(&retryTime, &now);
5567 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5571 /* Set the packet flags and schedule the resend events */
5572 /* Only request an ack for the last packet in the list */
5573 for (i = 0; i < xmit->len; i++) {
5574 struct rx_packet *packet = xmit->list[i];
5576 packet->retryTime = retryTime;
5577 if (packet->header.serial) {
5578 /* Exponentially backoff retry times */
5579 if (packet->backoff < MAXBACKOFF) {
5580 /* so it can't stay == 0 */
5581 packet->backoff = (packet->backoff << 1) + 1;
5584 clock_Addmsec(&(packet->retryTime),
5585 ((afs_uint32) packet->backoff) << 8);
5588 /* Wait a little extra for the ack on the last packet */
5590 && !(packet->header.flags & RX_CLIENT_INITIATED)) {
5591 clock_Addmsec(&(packet->retryTime), 400);
5594 /* Record the time sent */
5595 packet->timeSent = now;
5597 /* Ask for an ack on retransmitted packets, on every other packet
5598 * if the peer doesn't support slow start. Ask for an ack on every
5599 * packet until the congestion window reaches the ack rate. */
5600 if (packet->header.serial) {
5603 /* improved RTO calculation- not Karn */
5604 packet->firstSent = now;
5605 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5606 || (!(call->flags & RX_CALL_SLOW_START_OK)
5607 && (packet->header.seq & 1)))) {
5612 /* Tag this packet as not being the last in this group,
5613 * for the receiver's benefit */
5614 if (i < xmit->len - 1 || moreFlag) {
5615 packet->header.flags |= RX_MORE_PACKETS;
5620 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5623 /* Since we're about to send a data packet to the peer, it's
5624 * safe to nuke any scheduled end-of-packets ack */
5625 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5627 MUTEX_EXIT(&call->lock);
5628 MUTEX_ENTER(&rx_refcnt_mutex);
5629 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5630 MUTEX_EXIT(&rx_refcnt_mutex);
5631 if (xmit->len > 1) {
5632 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5634 rxi_SendPacket(call, conn, xmit->list[0], istack);
5636 MUTEX_ENTER(&call->lock);
5637 MUTEX_ENTER(&rx_refcnt_mutex);
5638 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5639 MUTEX_EXIT(&rx_refcnt_mutex);
5641 /* Update last send time for this call (for keep-alive
5642 * processing), and for the connection (so that we can discover
5643 * idle connections) */
5644 conn->lastSendTime = call->lastSendTime = clock_Sec();
5645 /* Let a set of retransmits trigger an idle timeout */
5646 if (!xmit->resending)
5647 call->lastSendData = call->lastSendTime;
5650 /* When sending packets we need to follow these rules:
5651 * 1. Never send more than maxDgramPackets in a jumbogram.
5652 * 2. Never send a packet with more than two iovecs in a jumbogram.
5653 * 3. Never send a retransmitted packet in a jumbogram.
5654 * 4. Never send more than cwind/4 packets in a jumbogram
5655 * We always keep the last list we should have sent so we
5656 * can set the RX_MORE_PACKETS flags correctly.
5660 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5664 struct xmitlist working;
5665 struct xmitlist last;
5667 struct rx_peer *peer = call->conn->peer;
5668 int morePackets = 0;
5670 memset(&last, 0, sizeof(struct xmitlist));
5671 working.list = &list[0];
5673 working.resending = 0;
5675 for (i = 0; i < len; i++) {
5676 /* Does the current packet force us to flush the current list? */
5678 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5679 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5681 /* This sends the 'last' list and then rolls the current working
5682 * set into the 'last' one, and resets the working set */
5685 rxi_SendList(call, &last, istack, 1);
5686 /* If the call enters an error state stop sending, or if
5687 * we entered congestion recovery mode, stop sending */
5688 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5693 working.resending = 0;
5694 working.list = &list[i];
5696 /* Add the current packet to the list if it hasn't been acked.
5697 * Otherwise adjust the list pointer to skip the current packet. */
5698 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5701 if (list[i]->header.serial)
5702 working.resending = 1;
5704 /* Do we need to flush the list? */
5705 if (working.len >= (int)peer->maxDgramPackets
5706 || working.len >= (int)call->nDgramPackets
5707 || working.len >= (int)call->cwind
5708 || list[i]->header.serial
5709 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5711 rxi_SendList(call, &last, istack, 1);
5712 /* If the call enters an error state stop sending, or if
5713 * we entered congestion recovery mode, stop sending */
5715 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5720 working.resending = 0;
5721 working.list = &list[i + 1];
5724 if (working.len != 0) {
5725 osi_Panic("rxi_SendList error");
5727 working.list = &list[i + 1];
5731 /* Send the whole list when the call is in receive mode, when
5732 * the call is in eof mode, when we are in fast recovery mode,
5733 * and when we have the last packet */
5734 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5735 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5736 || (call->flags & RX_CALL_FAST_RECOVER)) {
5737 /* Check for the case where the current list contains
5738 * an acked packet. Since we always send retransmissions
5739 * in a separate packet, we only need to check the first
5740 * packet in the list */
5741 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5745 rxi_SendList(call, &last, istack, morePackets);
5746 /* If the call enters an error state stop sending, or if
5747 * we entered congestion recovery mode, stop sending */
5748 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5752 rxi_SendList(call, &working, istack, 0);
5754 } else if (last.len > 0) {
5755 rxi_SendList(call, &last, istack, 0);
5756 /* Packets which are in 'working' are not sent by this call */
5760 #ifdef RX_ENABLE_LOCKS
5761 /* Call rxi_Start, below, but with the call lock held. */
5763 rxi_StartUnlocked(struct rxevent *event,
5764 void *arg0, void *arg1, int istack)
5766 struct rx_call *call = arg0;
5768 MUTEX_ENTER(&call->lock);
5769 rxi_Start(event, call, arg1, istack);
5770 MUTEX_EXIT(&call->lock);
5772 #endif /* RX_ENABLE_LOCKS */
5774 /* This routine is called when new packets are readied for
5775 * transmission and when retransmission may be necessary, or when the
5776 * transmission window or burst count are favourable. This should be
5777 * better optimized for new packets, the usual case, now that we've
5778 * got rid of queues of send packets. XXXXXXXXXXX */
5780 rxi_Start(struct rxevent *event,
5781 void *arg0, void *arg1, int istack)
5783 struct rx_call *call = arg0;
5785 struct rx_packet *p;
5786 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5787 struct clock now, usenow, retryTime;
5792 /* If rxi_Start is being called as a result of a resend event,
5793 * then make sure that the event pointer is removed from the call
5794 * structure, since there is no longer a per-call retransmission
5796 if (event && event == call->resendEvent) {
5797 MUTEX_ENTER(&rx_refcnt_mutex);
5798 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5799 MUTEX_EXIT(&rx_refcnt_mutex);
5800 call->resendEvent = NULL;
5802 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5803 rxi_CheckBusy(call);
5806 if (queue_IsEmpty(&call->tq)) {
5813 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5814 if (rx_stats_active)
5815 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5820 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5822 clock_GetTime(&now);
5825 /* Send (or resend) any packets that need it, subject to
5826 * window restrictions and congestion burst control
5827 * restrictions. Ask for an ack on the last packet sent in
5828 * this burst. For now, we're relying upon the window being
5829 * considerably bigger than the largest number of packets that
5830 * are typically sent at once by one initial call to
5831 * rxi_Start. This is probably bogus (perhaps we should ask
5832 * for an ack when we're half way through the current
5833 * window?). Also, for non file transfer applications, this
5834 * may end up asking for an ack for every packet. Bogus. XXXX
5837 * But check whether we're here recursively, and let the other guy
5840 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5841 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5842 call->flags |= RX_CALL_TQ_BUSY;
5844 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5846 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5847 call->flags &= ~RX_CALL_NEED_START;
5848 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5850 maxXmitPackets = MIN(call->twind, call->cwind);
5851 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5852 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5853 /* We shouldn't be sending packets if a thread is waiting
5854 * to initiate congestion recovery */
5855 dpf(("call %d waiting to initiate fast recovery\n",
5856 *(call->callNumber)));
5860 && (call->flags & RX_CALL_FAST_RECOVER)) {
5861 /* Only send one packet during fast recovery */
5862 dpf(("call %d restricted to one packet per send during fast recovery\n",
5863 *(call->callNumber)));
5866 #ifdef RX_TRACK_PACKETS
5867 if ((p->flags & RX_PKTFLAG_FREE)
5868 || (!queue_IsEnd(&call->tq, nxp)
5869 && (nxp->flags & RX_PKTFLAG_FREE))
5870 || (p == (struct rx_packet *)&rx_freePacketQueue)
5871 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5872 osi_Panic("rxi_Start: xmit queue clobbered");
5875 if (p->flags & RX_PKTFLAG_ACKED) {
5876 /* Since we may block, don't trust this */
5877 usenow.sec = usenow.usec = 0;
5878 if (rx_stats_active)
5879 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5880 continue; /* Ignore this packet if it has been acknowledged */
5883 /* Turn off all flags except these ones, which are the same
5884 * on each transmission */
5885 p->header.flags &= RX_PRESET_FLAGS;
5887 if (p->header.seq >=
5888 call->tfirst + MIN((int)call->twind,
5889 (int)(call->nSoftAcked +
5891 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5892 /* Note: if we're waiting for more window space, we can
5893 * still send retransmits; hence we don't return here, but
5894 * break out to schedule a retransmit event */
5895 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5896 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5901 /* Transmit the packet if it needs to be sent. */
5902 if (!clock_Lt(&now, &p->retryTime)) {
5903 if (nXmitPackets == maxXmitPackets) {
5904 rxi_SendXmitList(call, call->xmitList,
5905 nXmitPackets, istack);
5908 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u\n",
5909 *(call->callNumber), p,
5911 p->retryTime.sec, p->retryTime.usec));
5912 call->xmitList[nXmitPackets++] = p;
5916 /* xmitList now hold pointers to all of the packets that are
5917 * ready to send. Now we loop to send the packets */
5918 if (nXmitPackets > 0) {
5919 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
5923 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5925 * TQ references no longer protected by this flag; they must remain
5926 * protected by the global lock.
5928 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5929 call->flags &= ~RX_CALL_TQ_BUSY;
5930 rxi_WakeUpTransmitQueue(call);
5934 /* We went into the error state while sending packets. Now is
5935 * the time to reset the call. This will also inform the using
5936 * process that the call is in an error state.
5938 if (rx_stats_active)
5939 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
5940 call->flags &= ~RX_CALL_TQ_BUSY;
5941 rxi_WakeUpTransmitQueue(call);
5942 rxi_CallError(call, call->error);
5945 #ifdef RX_ENABLE_LOCKS
5946 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5948 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5949 /* Some packets have received acks. If they all have, we can clear
5950 * the transmit queue.
5953 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5954 if (p->header.seq < call->tfirst
5955 && (p->flags & RX_PKTFLAG_ACKED)) {
5957 #ifdef RX_TRACK_PACKETS
5958 p->flags &= ~RX_PKTFLAG_TQ;
5960 #ifdef RXDEBUG_PACKET
5968 call->flags |= RX_CALL_TQ_CLEARME;
5970 #endif /* RX_ENABLE_LOCKS */
5971 /* Don't bother doing retransmits if the TQ is cleared. */
5972 if (call->flags & RX_CALL_TQ_CLEARME) {
5973 rxi_ClearTransmitQueue(call, 1);
5975 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5978 /* Always post a resend event, if there is anything in the
5979 * queue, and resend is possible. There should be at least
5980 * one unacknowledged packet in the queue ... otherwise none
5981 * of these packets should be on the queue in the first place.
5983 if (call->resendEvent) {
5984 /* Cancel the existing event and post a new one */
5985 rxevent_Cancel(call->resendEvent, call,
5986 RX_CALL_REFCOUNT_RESEND);
5989 /* The retry time is the retry time on the first unacknowledged
5990 * packet inside the current window */
5992 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5993 /* Don't set timers for packets outside the window */
5994 if (p->header.seq >= call->tfirst + call->twind) {
5998 if (!(p->flags & RX_PKTFLAG_ACKED)
5999 && !clock_IsZero(&p->retryTime)) {
6001 retryTime = p->retryTime;
6006 /* Post a new event to re-run rxi_Start when retries may be needed */
6007 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
6008 #ifdef RX_ENABLE_LOCKS
6009 MUTEX_ENTER(&rx_refcnt_mutex);
6010 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
6011 MUTEX_EXIT(&rx_refcnt_mutex);
6013 rxevent_PostNow2(&retryTime, &usenow,
6015 (void *)call, 0, istack);
6016 #else /* RX_ENABLE_LOCKS */
6018 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
6019 (void *)call, 0, istack);
6020 #endif /* RX_ENABLE_LOCKS */
6023 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6024 } while (call->flags & RX_CALL_NEED_START);
6026 * TQ references no longer protected by this flag; they must remain
6027 * protected by the global lock.
6029 call->flags &= ~RX_CALL_TQ_BUSY;
6030 rxi_WakeUpTransmitQueue(call);
6032 call->flags |= RX_CALL_NEED_START;
6034 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6036 if (call->resendEvent) {
6037 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6042 /* Also adjusts the keep alive parameters for the call, to reflect
6043 * that we have just sent a packet (so keep alives aren't sent
6046 rxi_Send(struct rx_call *call, struct rx_packet *p,
6049 struct rx_connection *conn = call->conn;
6051 /* Stamp each packet with the user supplied status */
6052 p->header.userStatus = call->localStatus;
6054 /* Allow the security object controlling this call's security to
6055 * make any last-minute changes to the packet */
6056 RXS_SendPacket(conn->securityObject, call, p);
6058 /* Since we're about to send SOME sort of packet to the peer, it's
6059 * safe to nuke any scheduled end-of-packets ack */
6060 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6062 /* Actually send the packet, filling in more connection-specific fields */
6063 MUTEX_EXIT(&call->lock);
6064 MUTEX_ENTER(&rx_refcnt_mutex);
6065 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6066 MUTEX_EXIT(&rx_refcnt_mutex);
6067 rxi_SendPacket(call, conn, p, istack);
6068 MUTEX_ENTER(&rx_refcnt_mutex);
6069 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6070 MUTEX_EXIT(&rx_refcnt_mutex);
6071 MUTEX_ENTER(&call->lock);
6073 /* Update last send time for this call (for keep-alive
6074 * processing), and for the connection (so that we can discover
6075 * idle connections) */
6076 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6077 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6078 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6080 conn->lastSendTime = call->lastSendTime = clock_Sec();
6081 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6082 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6083 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6084 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6085 RX_ACK_PING_RESPONSE)))
6086 call->lastSendData = call->lastSendTime;
6090 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6091 * that things are fine. Also called periodically to guarantee that nothing
6092 * falls through the cracks (e.g. (error + dally) connections have keepalive
6093 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6095 * haveCTLock Set if calling from rxi_ReapConnections
6097 #ifdef RX_ENABLE_LOCKS
6099 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6100 #else /* RX_ENABLE_LOCKS */
6102 rxi_CheckCall(struct rx_call *call)
6103 #endif /* RX_ENABLE_LOCKS */
6105 struct rx_connection *conn = call->conn;
6107 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6108 afs_uint32 fudgeFactor;
6112 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6113 if (call->flags & RX_CALL_TQ_BUSY) {
6114 /* Call is active and will be reset by rxi_Start if it's
6115 * in an error state.
6120 /* RTT + 8*MDEV, rounded up to the next second. */
6121 fudgeFactor = (((afs_uint32) conn->peer->rtt >> 3) +
6122 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
6124 deadTime = conn->secondsUntilDead + fudgeFactor;
6126 /* These are computed to the second (+- 1 second). But that's
6127 * good enough for these values, which should be a significant
6128 * number of seconds. */
6129 if (now > (call->lastReceiveTime + deadTime)) {
6130 if (call->state == RX_STATE_ACTIVE) {
6132 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
6134 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6135 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6136 ip_stack_t *ipst = ns->netstack_ip;
6138 ire = ire_cache_lookup(conn->peer->host
6139 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6141 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6143 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6150 if (ire && ire->ire_max_frag > 0)
6151 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6153 #if defined(GLOBAL_NETSTACKID)
6157 #endif /* ADAPT_PMTU */
6158 cerror = RX_CALL_DEAD;
6161 #ifdef RX_ENABLE_LOCKS
6162 /* Cancel pending events */
6163 rxevent_Cancel(call->delayedAckEvent, call,
6164 RX_CALL_REFCOUNT_DELAY);
6165 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6166 rxevent_Cancel(call->keepAliveEvent, call,
6167 RX_CALL_REFCOUNT_ALIVE);
6168 if (call->growMTUEvent)
6169 rxevent_Cancel(call->growMTUEvent, call,
6170 RX_CALL_REFCOUNT_ALIVE);
6171 MUTEX_ENTER(&rx_refcnt_mutex);
6172 if (call->refCount == 0) {
6173 rxi_FreeCall(call, haveCTLock);
6174 MUTEX_EXIT(&rx_refcnt_mutex);
6177 MUTEX_EXIT(&rx_refcnt_mutex);
6179 #else /* RX_ENABLE_LOCKS */
6180 rxi_FreeCall(call, 0);
6182 #endif /* RX_ENABLE_LOCKS */
6184 /* Non-active calls are destroyed if they are not responding
6185 * to pings; active calls are simply flagged in error, so the
6186 * attached process can die reasonably gracefully. */
6189 if (conn->idleDeadTime) {
6190 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6193 /* see if we have a non-activity timeout */
6194 if (call->startWait && idleDeadTime
6195 && ((call->startWait + idleDeadTime) < now) &&
6196 (call->flags & RX_CALL_READER_WAIT)) {
6197 if (call->state == RX_STATE_ACTIVE) {
6198 cerror = RX_CALL_TIMEOUT;
6202 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6203 && ((call->lastSendData + idleDeadTime) < now)) {
6204 if (call->state == RX_STATE_ACTIVE) {
6205 cerror = conn->idleDeadErr;
6210 if (conn->hardDeadTime) {
6211 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6214 /* see if we have a hard timeout */
6216 && (now > (hardDeadTime + call->startTime.sec))) {
6217 if (call->state == RX_STATE_ACTIVE)
6218 rxi_CallError(call, RX_CALL_TIMEOUT);
6223 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6224 && call->lastReceiveTime) {
6225 int oldMTU = conn->peer->ifMTU;
6227 /* if we thought we could send more, perhaps things got worse */
6228 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6229 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6230 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6231 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6233 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6235 /* minimum capped in SetPeerMtu */
6236 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6239 conn->lastPacketSize = 0;
6241 /* needed so ResetCall doesn't clobber us. */
6242 call->MTU = conn->peer->ifMTU;
6244 /* if we never succeeded, let the error pass out as-is */
6245 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6246 cerror = conn->msgsizeRetryErr;
6249 rxi_CallError(call, cerror);
6254 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6256 struct rx_connection *conn = arg1;
6257 struct rx_header theader;
6258 char tbuffer[1 + sizeof(struct rx_header)];
6259 struct sockaddr_in taddr;
6262 struct iovec tmpiov[2];
6265 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6268 tp = &tbuffer[sizeof(struct rx_header)];
6269 taddr.sin_family = AF_INET;
6270 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6271 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6272 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6273 taddr.sin_len = sizeof(struct sockaddr_in);
6275 memset(&theader, 0, sizeof(theader));
6276 theader.epoch = htonl(999);
6278 theader.callNumber = 0;
6281 theader.type = RX_PACKET_TYPE_VERSION;
6282 theader.flags = RX_LAST_PACKET;
6283 theader.serviceId = 0;
6285 memcpy(tbuffer, &theader, sizeof(theader));
6286 memcpy(tp, &a, sizeof(a));
6287 tmpiov[0].iov_base = tbuffer;
6288 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6290 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6292 MUTEX_ENTER(&conn->conn_data_lock);
6293 MUTEX_ENTER(&rx_refcnt_mutex);
6294 /* Only reschedule ourselves if the connection would not be destroyed */
6295 if (conn->refCount <= 1) {
6296 conn->natKeepAliveEvent = NULL;
6297 MUTEX_EXIT(&rx_refcnt_mutex);
6298 MUTEX_EXIT(&conn->conn_data_lock);
6299 rx_DestroyConnection(conn); /* drop the reference for this */
6301 conn->refCount--; /* drop the reference for this */
6302 MUTEX_EXIT(&rx_refcnt_mutex);
6303 conn->natKeepAliveEvent = NULL;
6304 rxi_ScheduleNatKeepAliveEvent(conn);
6305 MUTEX_EXIT(&conn->conn_data_lock);
6310 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6312 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6313 struct clock when, now;
6314 clock_GetTime(&now);
6316 when.sec += conn->secondsUntilNatPing;
6317 MUTEX_ENTER(&rx_refcnt_mutex);
6318 conn->refCount++; /* hold a reference for this */
6319 MUTEX_EXIT(&rx_refcnt_mutex);
6320 conn->natKeepAliveEvent =
6321 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6326 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6328 MUTEX_ENTER(&conn->conn_data_lock);
6329 conn->secondsUntilNatPing = seconds;
6331 rxi_ScheduleNatKeepAliveEvent(conn);
6332 MUTEX_EXIT(&conn->conn_data_lock);
6336 rxi_NatKeepAliveOn(struct rx_connection *conn)
6338 MUTEX_ENTER(&conn->conn_data_lock);
6339 rxi_ScheduleNatKeepAliveEvent(conn);
6340 MUTEX_EXIT(&conn->conn_data_lock);
6343 /* When a call is in progress, this routine is called occasionally to
6344 * make sure that some traffic has arrived (or been sent to) the peer.
6345 * If nothing has arrived in a reasonable amount of time, the call is
6346 * declared dead; if nothing has been sent for a while, we send a
6347 * keep-alive packet (if we're actually trying to keep the call alive)
6350 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6352 struct rx_call *call = arg1;
6353 struct rx_connection *conn;
6356 MUTEX_ENTER(&rx_refcnt_mutex);
6357 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6358 MUTEX_EXIT(&rx_refcnt_mutex);
6359 MUTEX_ENTER(&call->lock);
6360 if (event == call->keepAliveEvent)
6361 call->keepAliveEvent = NULL;
6364 #ifdef RX_ENABLE_LOCKS
6365 if (rxi_CheckCall(call, 0)) {
6366 MUTEX_EXIT(&call->lock);
6369 #else /* RX_ENABLE_LOCKS */
6370 if (rxi_CheckCall(call))
6372 #endif /* RX_ENABLE_LOCKS */
6374 /* Don't try to keep alive dallying calls */
6375 if (call->state == RX_STATE_DALLY) {
6376 MUTEX_EXIT(&call->lock);
6381 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6382 /* Don't try to send keepalives if there is unacknowledged data */
6383 /* the rexmit code should be good enough, this little hack
6384 * doesn't quite work XXX */
6385 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6387 rxi_ScheduleKeepAliveEvent(call);
6388 MUTEX_EXIT(&call->lock);
6391 /* Does what's on the nameplate. */
6393 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6395 struct rx_call *call = arg1;
6396 struct rx_connection *conn;
6398 MUTEX_ENTER(&rx_refcnt_mutex);
6399 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6400 MUTEX_EXIT(&rx_refcnt_mutex);
6401 MUTEX_ENTER(&call->lock);
6403 if (event == call->growMTUEvent)
6404 call->growMTUEvent = NULL;
6406 #ifdef RX_ENABLE_LOCKS
6407 if (rxi_CheckCall(call, 0)) {
6408 MUTEX_EXIT(&call->lock);
6411 #else /* RX_ENABLE_LOCKS */
6412 if (rxi_CheckCall(call))
6414 #endif /* RX_ENABLE_LOCKS */
6416 /* Don't bother with dallying calls */
6417 if (call->state == RX_STATE_DALLY) {
6418 MUTEX_EXIT(&call->lock);
6425 * keep being scheduled, just don't do anything if we're at peak,
6426 * or we're not set up to be properly handled (idle timeout required)
6428 if ((conn->peer->maxPacketSize != 0) &&
6429 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6430 (conn->idleDeadErr))
6431 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6432 rxi_ScheduleGrowMTUEvent(call, 0);
6433 MUTEX_EXIT(&call->lock);
6437 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6439 if (!call->keepAliveEvent) {
6440 struct clock when, now;
6441 clock_GetTime(&now);
6443 when.sec += call->conn->secondsUntilPing;
6444 MUTEX_ENTER(&rx_refcnt_mutex);
6445 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6446 MUTEX_EXIT(&rx_refcnt_mutex);
6447 call->keepAliveEvent =
6448 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6453 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6455 if (!call->growMTUEvent) {
6456 struct clock when, now;
6458 clock_GetTime(&now);
6461 if (call->conn->secondsUntilPing)
6462 secs = (6*call->conn->secondsUntilPing)-1;
6464 if (call->conn->secondsUntilDead)
6465 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6469 MUTEX_ENTER(&rx_refcnt_mutex);
6470 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6471 MUTEX_EXIT(&rx_refcnt_mutex);
6472 call->growMTUEvent =
6473 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6477 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6479 rxi_KeepAliveOn(struct rx_call *call)
6481 /* Pretend last packet received was received now--i.e. if another
6482 * packet isn't received within the keep alive time, then the call
6483 * will die; Initialize last send time to the current time--even
6484 * if a packet hasn't been sent yet. This will guarantee that a
6485 * keep-alive is sent within the ping time */
6486 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6487 rxi_ScheduleKeepAliveEvent(call);
6491 rxi_GrowMTUOn(struct rx_call *call)
6493 struct rx_connection *conn = call->conn;
6494 MUTEX_ENTER(&conn->conn_data_lock);
6495 conn->lastPingSizeSer = conn->lastPingSize = 0;
6496 MUTEX_EXIT(&conn->conn_data_lock);
6497 rxi_ScheduleGrowMTUEvent(call, 1);
6500 /* This routine is called to send connection abort messages
6501 * that have been delayed to throttle looping clients. */
6503 rxi_SendDelayedConnAbort(struct rxevent *event,
6504 void *arg1, void *unused)
6506 struct rx_connection *conn = arg1;
6509 struct rx_packet *packet;
6511 MUTEX_ENTER(&conn->conn_data_lock);
6512 conn->delayedAbortEvent = NULL;
6513 error = htonl(conn->error);
6515 MUTEX_EXIT(&conn->conn_data_lock);
6516 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6519 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6520 RX_PACKET_TYPE_ABORT, (char *)&error,
6522 rxi_FreePacket(packet);
6526 /* This routine is called to send call abort messages
6527 * that have been delayed to throttle looping clients. */
6529 rxi_SendDelayedCallAbort(struct rxevent *event,
6530 void *arg1, void *dummy)
6532 struct rx_call *call = arg1;
6535 struct rx_packet *packet;
6537 MUTEX_ENTER(&call->lock);
6538 call->delayedAbortEvent = NULL;
6539 error = htonl(call->error);
6541 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6544 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6545 (char *)&error, sizeof(error), 0);
6546 rxi_FreePacket(packet);
6548 MUTEX_EXIT(&call->lock);
6549 MUTEX_ENTER(&rx_refcnt_mutex);
6550 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6551 MUTEX_EXIT(&rx_refcnt_mutex);
6554 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6555 * seconds) to ask the client to authenticate itself. The routine
6556 * issues a challenge to the client, which is obtained from the
6557 * security object associated with the connection */
6559 rxi_ChallengeEvent(struct rxevent *event,
6560 void *arg0, void *arg1, int tries)
6562 struct rx_connection *conn = arg0;
6564 conn->challengeEvent = NULL;
6565 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6566 struct rx_packet *packet;
6567 struct clock when, now;
6570 /* We've failed to authenticate for too long.
6571 * Reset any calls waiting for authentication;
6572 * they are all in RX_STATE_PRECALL.
6576 MUTEX_ENTER(&conn->conn_call_lock);
6577 for (i = 0; i < RX_MAXCALLS; i++) {
6578 struct rx_call *call = conn->call[i];
6580 MUTEX_ENTER(&call->lock);
6581 if (call->state == RX_STATE_PRECALL) {
6582 rxi_CallError(call, RX_CALL_DEAD);
6583 rxi_SendCallAbort(call, NULL, 0, 0);
6585 MUTEX_EXIT(&call->lock);
6588 MUTEX_EXIT(&conn->conn_call_lock);
6592 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6594 /* If there's no packet available, do this later. */
6595 RXS_GetChallenge(conn->securityObject, conn, packet);
6596 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6597 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6598 rxi_FreePacket(packet);
6600 clock_GetTime(&now);
6602 when.sec += RX_CHALLENGE_TIMEOUT;
6603 conn->challengeEvent =
6604 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6609 /* Call this routine to start requesting the client to authenticate
6610 * itself. This will continue until authentication is established,
6611 * the call times out, or an invalid response is returned. The
6612 * security object associated with the connection is asked to create
6613 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6614 * defined earlier. */
6616 rxi_ChallengeOn(struct rx_connection *conn)
6618 if (!conn->challengeEvent) {
6619 RXS_CreateChallenge(conn->securityObject, conn);
6620 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6625 /* rxi_ComputeRoundTripTime is called with peer locked. */
6626 /* peer may be null */
6628 rxi_ComputeRoundTripTime(struct rx_packet *p,
6629 struct rx_ackPacket *ack,
6630 struct rx_peer *peer,
6633 struct clock thisRtt, *sentp;
6637 /* If the ACK is delayed, then do nothing */
6638 if (ack->reason == RX_ACK_DELAY)
6641 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6642 * their RTT multiple times, so only include the RTT of the last packet
6644 if (p->flags & RX_JUMBO_PACKET)
6647 /* Use the serial number to determine which transmission the ACK is for,
6648 * and set the sent time to match this. If we have no serial number, then
6649 * only use the ACK for RTT calculations if the packet has not been
6653 serial = ntohl(ack->serial);
6655 if (serial == p->header.serial) {
6656 sentp = &p->timeSent;
6657 } else if (serial == p->firstSerial) {
6658 sentp = &p->firstSent;
6659 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6660 sentp = &p->firstSent;
6664 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6665 sentp = &p->firstSent;
6672 if (clock_Lt(&thisRtt, sentp))
6673 return; /* somebody set the clock back, don't count this time. */
6675 clock_Sub(&thisRtt, sentp);
6676 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6677 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6679 if (clock_IsZero(&thisRtt)) {
6681 * The actual round trip time is shorter than the
6682 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6683 * Since we can't tell which at the moment we will assume 1ms.
6685 thisRtt.usec = 1000;
6688 if (rx_stats_active) {
6689 MUTEX_ENTER(&rx_stats_mutex);
6690 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6691 rx_stats.minRtt = thisRtt;
6692 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6693 if (thisRtt.sec > 60) {
6694 MUTEX_EXIT(&rx_stats_mutex);
6695 return; /* somebody set the clock ahead */
6697 rx_stats.maxRtt = thisRtt;
6699 clock_Add(&rx_stats.totalRtt, &thisRtt);
6700 rx_atomic_inc(&rx_stats.nRttSamples);
6701 MUTEX_EXIT(&rx_stats_mutex);
6704 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6706 /* Apply VanJacobson round-trip estimations */
6711 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6712 * srtt is stored as fixed point with 3 bits after the binary
6713 * point (i.e., scaled by 8). The following magic is
6714 * equivalent to the smoothing algorithm in rfc793 with an
6715 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6716 * srtt'*8 = rtt + srtt*7
6717 * srtt'*8 = srtt*8 + rtt - srtt
6718 * srtt' = srtt + rtt/8 - srtt/8
6719 * srtt' = srtt + (rtt - srtt)/8
6722 delta = _8THMSEC(&thisRtt) - peer->rtt;
6723 peer->rtt += (delta >> 3);
6726 * We accumulate a smoothed rtt variance (actually, a smoothed
6727 * mean difference), then set the retransmit timer to smoothed
6728 * rtt + 4 times the smoothed variance (was 2x in van's original
6729 * paper, but 4x works better for me, and apparently for him as
6731 * rttvar is stored as
6732 * fixed point with 2 bits after the binary point (scaled by
6733 * 4). The following is equivalent to rfc793 smoothing with
6734 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6735 * rttvar'*4 = rttvar*3 + |delta|
6736 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6737 * rttvar' = rttvar + |delta|/4 - rttvar/4
6738 * rttvar' = rttvar + (|delta| - rttvar)/4
6739 * This replaces rfc793's wired-in beta.
6740 * dev*4 = dev*4 + (|actual - expected| - dev)
6746 delta -= (peer->rtt_dev << 1);
6747 peer->rtt_dev += (delta >> 3);
6749 /* I don't have a stored RTT so I start with this value. Since I'm
6750 * probably just starting a call, and will be pushing more data down
6751 * this, I expect congestion to increase rapidly. So I fudge a
6752 * little, and I set deviance to half the rtt. In practice,
6753 * deviance tends to approach something a little less than
6754 * half the smoothed rtt. */
6755 peer->rtt = _8THMSEC(&thisRtt) + 8;
6756 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6758 /* the timeout is RTT + 4*MDEV + rx_minPeerTimeout msec.
6759 * This is because one end or the other of these connections is usually
6760 * in a user process, and can be switched and/or swapped out. So on fast,
6761 * reliable networks, the timeout would otherwise be too short. */
6762 rtt_timeout = ((peer->rtt >> 3) + peer->rtt_dev) + rx_minPeerTimeout;
6763 clock_Zero(&(peer->timeout));
6764 clock_Addmsec(&(peer->timeout), rtt_timeout);
6766 /* Reset the backedOff flag since we just computed a new timeout value */
6767 peer->backedOff = 0;
6769 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6770 p->header.callNumber, p, MSEC(&thisRtt), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6774 /* Find all server connections that have not been active for a long time, and
6777 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6779 struct clock now, when;
6780 clock_GetTime(&now);
6782 /* Find server connection structures that haven't been used for
6783 * greater than rx_idleConnectionTime */
6785 struct rx_connection **conn_ptr, **conn_end;
6786 int i, havecalls = 0;
6787 MUTEX_ENTER(&rx_connHashTable_lock);
6788 for (conn_ptr = &rx_connHashTable[0], conn_end =
6789 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6791 struct rx_connection *conn, *next;
6792 struct rx_call *call;
6796 for (conn = *conn_ptr; conn; conn = next) {
6797 /* XXX -- Shouldn't the connection be locked? */
6800 for (i = 0; i < RX_MAXCALLS; i++) {
6801 call = conn->call[i];
6805 code = MUTEX_TRYENTER(&call->lock);
6808 #ifdef RX_ENABLE_LOCKS
6809 result = rxi_CheckCall(call, 1);
6810 #else /* RX_ENABLE_LOCKS */
6811 result = rxi_CheckCall(call);
6812 #endif /* RX_ENABLE_LOCKS */
6813 MUTEX_EXIT(&call->lock);
6815 /* If CheckCall freed the call, it might
6816 * have destroyed the connection as well,
6817 * which screws up the linked lists.
6823 if (conn->type == RX_SERVER_CONNECTION) {
6824 /* This only actually destroys the connection if
6825 * there are no outstanding calls */
6826 MUTEX_ENTER(&conn->conn_data_lock);
6827 MUTEX_ENTER(&rx_refcnt_mutex);
6828 if (!havecalls && !conn->refCount
6829 && ((conn->lastSendTime + rx_idleConnectionTime) <
6831 conn->refCount++; /* it will be decr in rx_DestroyConn */
6832 MUTEX_EXIT(&rx_refcnt_mutex);
6833 MUTEX_EXIT(&conn->conn_data_lock);
6834 #ifdef RX_ENABLE_LOCKS
6835 rxi_DestroyConnectionNoLock(conn);
6836 #else /* RX_ENABLE_LOCKS */
6837 rxi_DestroyConnection(conn);
6838 #endif /* RX_ENABLE_LOCKS */
6840 #ifdef RX_ENABLE_LOCKS
6842 MUTEX_EXIT(&rx_refcnt_mutex);
6843 MUTEX_EXIT(&conn->conn_data_lock);
6845 #endif /* RX_ENABLE_LOCKS */
6849 #ifdef RX_ENABLE_LOCKS
6850 while (rx_connCleanup_list) {
6851 struct rx_connection *conn;
6852 conn = rx_connCleanup_list;
6853 rx_connCleanup_list = rx_connCleanup_list->next;
6854 MUTEX_EXIT(&rx_connHashTable_lock);
6855 rxi_CleanupConnection(conn);
6856 MUTEX_ENTER(&rx_connHashTable_lock);
6858 MUTEX_EXIT(&rx_connHashTable_lock);
6859 #endif /* RX_ENABLE_LOCKS */
6862 /* Find any peer structures that haven't been used (haven't had an
6863 * associated connection) for greater than rx_idlePeerTime */
6865 struct rx_peer **peer_ptr, **peer_end;
6869 * Why do we need to hold the rx_peerHashTable_lock across
6870 * the incrementing of peer_ptr since the rx_peerHashTable
6871 * array is not changing? We don't.
6873 * By dropping the lock periodically we can permit other
6874 * activities to be performed while a rxi_ReapConnections
6875 * call is in progress. The goal of reap connections
6876 * is to clean up quickly without causing large amounts
6877 * of contention. Therefore, it is important that global
6878 * mutexes not be held for extended periods of time.
6880 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6881 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6883 struct rx_peer *peer, *next, *prev;
6885 MUTEX_ENTER(&rx_peerHashTable_lock);
6886 for (prev = peer = *peer_ptr; peer; peer = next) {
6888 code = MUTEX_TRYENTER(&peer->peer_lock);
6889 if ((code) && (peer->refCount == 0)
6890 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6891 rx_interface_stat_p rpc_stat, nrpc_stat;
6895 * now know that this peer object is one to be
6896 * removed from the hash table. Once it is removed
6897 * it can't be referenced by other threads.
6898 * Lets remove it first and decrement the struct
6899 * nPeerStructs count.
6901 if (peer == *peer_ptr) {
6907 if (rx_stats_active)
6908 rx_atomic_dec(&rx_stats.nPeerStructs);
6911 * Now if we hold references on 'prev' and 'next'
6912 * we can safely drop the rx_peerHashTable_lock
6913 * while we destroy this 'peer' object.
6919 MUTEX_EXIT(&rx_peerHashTable_lock);
6921 MUTEX_EXIT(&peer->peer_lock);
6922 MUTEX_DESTROY(&peer->peer_lock);
6924 (&peer->rpcStats, rpc_stat, nrpc_stat,
6925 rx_interface_stat)) {
6926 unsigned int num_funcs;
6929 queue_Remove(&rpc_stat->queue_header);
6930 queue_Remove(&rpc_stat->all_peers);
6931 num_funcs = rpc_stat->stats[0].func_total;
6933 sizeof(rx_interface_stat_t) +
6934 rpc_stat->stats[0].func_total *
6935 sizeof(rx_function_entry_v1_t);
6937 rxi_Free(rpc_stat, space);
6939 MUTEX_ENTER(&rx_rpc_stats);
6940 rxi_rpc_peer_stat_cnt -= num_funcs;
6941 MUTEX_EXIT(&rx_rpc_stats);
6946 * Regain the rx_peerHashTable_lock and
6947 * decrement the reference count on 'prev'
6950 MUTEX_ENTER(&rx_peerHashTable_lock);
6957 MUTEX_EXIT(&peer->peer_lock);
6962 MUTEX_EXIT(&rx_peerHashTable_lock);
6966 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6967 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6968 * GC, just below. Really, we shouldn't have to keep moving packets from
6969 * one place to another, but instead ought to always know if we can
6970 * afford to hold onto a packet in its particular use. */
6971 MUTEX_ENTER(&rx_freePktQ_lock);
6972 if (rx_waitingForPackets) {
6973 rx_waitingForPackets = 0;
6974 #ifdef RX_ENABLE_LOCKS
6975 CV_BROADCAST(&rx_waitingForPackets_cv);
6977 osi_rxWakeup(&rx_waitingForPackets);
6980 MUTEX_EXIT(&rx_freePktQ_lock);
6983 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6984 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6988 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6989 * rx.h is sort of strange this is better. This is called with a security
6990 * object before it is discarded. Each connection using a security object has
6991 * its own refcount to the object so it won't actually be freed until the last
6992 * connection is destroyed.
6994 * This is the only rxs module call. A hold could also be written but no one
6998 rxs_Release(struct rx_securityClass *aobj)
7000 return RXS_Close(aobj);
7004 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
7005 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
7006 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
7007 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
7009 /* Adjust our estimate of the transmission rate to this peer, given
7010 * that the packet p was just acked. We can adjust peer->timeout and
7011 * call->twind. Pragmatically, this is called
7012 * only with packets of maximal length.
7013 * Called with peer and call locked.
7017 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
7018 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
7020 afs_int32 xferSize, xferMs;
7024 /* Count down packets */
7025 if (peer->rateFlag > 0)
7027 /* Do nothing until we're enabled */
7028 if (peer->rateFlag != 0)
7033 /* Count only when the ack seems legitimate */
7034 switch (ackReason) {
7035 case RX_ACK_REQUESTED:
7037 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
7041 case RX_ACK_PING_RESPONSE:
7042 if (p) /* want the response to ping-request, not data send */
7044 clock_GetTime(&newTO);
7045 if (clock_Gt(&newTO, &call->pingRequestTime)) {
7046 clock_Sub(&newTO, &call->pingRequestTime);
7047 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
7051 xferSize = rx_AckDataSize(rx_maxSendWindow) + RX_HEADER_SIZE;
7058 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)\n",
7059 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
7060 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
7062 /* Track only packets that are big enough. */
7063 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
7067 /* absorb RTT data (in milliseconds) for these big packets */
7068 if (peer->smRtt == 0) {
7069 peer->smRtt = xferMs;
7071 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
7076 if (peer->countDown) {
7080 peer->countDown = 10; /* recalculate only every so often */
7082 /* In practice, we can measure only the RTT for full packets,
7083 * because of the way Rx acks the data that it receives. (If it's
7084 * smaller than a full packet, it often gets implicitly acked
7085 * either by the call response (from a server) or by the next call
7086 * (from a client), and either case confuses transmission times
7087 * with processing times.) Therefore, replace the above
7088 * more-sophisticated processing with a simpler version, where the
7089 * smoothed RTT is kept for full-size packets, and the time to
7090 * transmit a windowful of full-size packets is simply RTT *
7091 * windowSize. Again, we take two steps:
7092 - ensure the timeout is large enough for a single packet's RTT;
7093 - ensure that the window is small enough to fit in the desired timeout.*/
7095 /* First, the timeout check. */
7096 minTime = peer->smRtt;
7097 /* Get a reasonable estimate for a timeout period */
7099 newTO.sec = minTime / 1000;
7100 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
7102 /* Increase the timeout period so that we can always do at least
7103 * one packet exchange */
7104 if (clock_Gt(&newTO, &peer->timeout)) {
7106 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u)\n",
7107 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
7108 newTO.sec, newTO.usec, peer->smRtt));
7110 peer->timeout = newTO;
7113 /* Now, get an estimate for the transmit window size. */
7114 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
7115 /* Now, convert to the number of full packets that could fit in a
7116 * reasonable fraction of that interval */
7117 minTime /= (peer->smRtt << 1);
7118 minTime = MAX(minTime, rx_minPeerTimeout);
7119 xferSize = minTime; /* (make a copy) */
7121 /* Now clamp the size to reasonable bounds. */
7124 else if (minTime > rx_maxSendWindow)
7125 minTime = rx_maxSendWindow;
7126 /* if (minTime != peer->maxWindow) {
7127 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u)\n",
7128 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
7129 peer->timeout.sec, peer->timeout.usec, peer->smRtt));
7130 peer->maxWindow = minTime;
7131 elide... call->twind = minTime;
7135 /* Cut back on the peer timeout if it had earlier grown unreasonably.
7136 * Discern this by calculating the timeout necessary for rx_Window
7138 if ((xferSize > rx_maxSendWindow) && (peer->timeout.sec >= 3)) {
7139 /* calculate estimate for transmission interval in milliseconds */
7140 minTime = rx_maxSendWindow * peer->smRtt;
7141 if (minTime < 1000) {
7142 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u)\n",
7143 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
7144 peer->timeout.usec, peer->smRtt));
7146 newTO.sec = 0; /* cut back on timeout by half a second */
7147 newTO.usec = 500000;
7148 clock_Sub(&peer->timeout, &newTO);
7153 } /* end of rxi_ComputeRate */
7154 #endif /* ADAPT_WINDOW */
7162 #define TRACE_OPTION_RX_DEBUG 16
7170 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7171 0, KEY_QUERY_VALUE, &parmKey);
7172 if (code != ERROR_SUCCESS)
7175 dummyLen = sizeof(TraceOption);
7176 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7177 (BYTE *) &TraceOption, &dummyLen);
7178 if (code == ERROR_SUCCESS) {
7179 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7181 RegCloseKey (parmKey);
7182 #endif /* AFS_NT40_ENV */
7187 rx_DebugOnOff(int on)
7191 rxdebug_active = on;
7197 rx_StatsOnOff(int on)
7199 rx_stats_active = on;
7203 /* Don't call this debugging routine directly; use dpf */
7205 rxi_DebugPrint(char *format, ...)
7214 va_start(ap, format);
7216 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7219 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7221 OutputDebugString(msg);
7227 va_start(ap, format);
7229 clock_GetTime(&now);
7230 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7231 (unsigned int)now.usec);
7232 vfprintf(rx_Log, format, ap);
7240 * This function is used to process the rx_stats structure that is local
7241 * to a process as well as an rx_stats structure received from a remote
7242 * process (via rxdebug). Therefore, it needs to do minimal version
7246 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7247 afs_int32 freePackets, char version)
7251 if (size != sizeof(struct rx_statistics)) {
7253 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7254 size, sizeof(struct rx_statistics));
7257 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7260 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7261 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7262 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7263 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7264 s->specialPktAllocFailures);
7266 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7267 s->receivePktAllocFailures, s->sendPktAllocFailures,
7268 s->specialPktAllocFailures);
7272 " greedy %u, " "bogusReads %u (last from host %x), "
7273 "noPackets %u, " "noBuffers %u, " "selects %u, "
7274 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7275 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7276 s->selects, s->sendSelects);
7278 fprintf(file, " packets read: ");
7279 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7280 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7282 fprintf(file, "\n");
7285 " other read counters: data %u, " "ack %u, " "dup %u "
7286 "spurious %u " "dally %u\n", s->dataPacketsRead,
7287 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7288 s->ignorePacketDally);
7290 fprintf(file, " packets sent: ");
7291 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7292 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7294 fprintf(file, "\n");
7297 " other send counters: ack %u, " "data %u (not resends), "
7298 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7299 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7300 s->dataPacketsPushed, s->ignoreAckedPacket);
7303 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7304 s->netSendFailures, (int)s->fatalErrors);
7306 if (s->nRttSamples) {
7307 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7308 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7310 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7311 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7315 " %d server connections, " "%d client connections, "
7316 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7317 s->nServerConns, s->nClientConns, s->nPeerStructs,
7318 s->nCallStructs, s->nFreeCallStructs);
7320 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7321 fprintf(file, " %d clock updates\n", clock_nUpdates);
7325 /* for backward compatibility */
7327 rx_PrintStats(FILE * file)
7329 MUTEX_ENTER(&rx_stats_mutex);
7330 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7331 sizeof(rx_stats), rx_nFreePackets,
7333 MUTEX_EXIT(&rx_stats_mutex);
7337 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7339 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7340 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7341 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7344 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7345 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7346 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7349 " Packet size %d, " "max in packet skew %d, "
7350 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7351 (int)peer->outPacketSkew);
7355 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7357 * This mutex protects the following static variables:
7361 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7362 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7364 #define LOCK_RX_DEBUG
7365 #define UNLOCK_RX_DEBUG
7366 #endif /* AFS_PTHREAD_ENV */
7368 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7370 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7371 u_char type, void *inputData, size_t inputLength,
7372 void *outputData, size_t outputLength)
7374 static afs_int32 counter = 100;
7375 time_t waitTime, waitCount;
7376 struct rx_header theader;
7379 struct timeval tv_now, tv_wake, tv_delta;
7380 struct sockaddr_in taddr, faddr;
7394 tp = &tbuffer[sizeof(struct rx_header)];
7395 taddr.sin_family = AF_INET;
7396 taddr.sin_port = remotePort;
7397 taddr.sin_addr.s_addr = remoteAddr;
7398 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7399 taddr.sin_len = sizeof(struct sockaddr_in);
7402 memset(&theader, 0, sizeof(theader));
7403 theader.epoch = htonl(999);
7405 theader.callNumber = htonl(counter);
7408 theader.type = type;
7409 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7410 theader.serviceId = 0;
7412 memcpy(tbuffer, &theader, sizeof(theader));
7413 memcpy(tp, inputData, inputLength);
7415 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7416 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7418 /* see if there's a packet available */
7419 gettimeofday(&tv_wake, NULL);
7420 tv_wake.tv_sec += waitTime;
7423 FD_SET(socket, &imask);
7424 tv_delta.tv_sec = tv_wake.tv_sec;
7425 tv_delta.tv_usec = tv_wake.tv_usec;
7426 gettimeofday(&tv_now, NULL);
7428 if (tv_delta.tv_usec < tv_now.tv_usec) {
7430 tv_delta.tv_usec += 1000000;
7433 tv_delta.tv_usec -= tv_now.tv_usec;
7435 if (tv_delta.tv_sec < tv_now.tv_sec) {
7439 tv_delta.tv_sec -= tv_now.tv_sec;
7442 code = select(0, &imask, 0, 0, &tv_delta);
7443 #else /* AFS_NT40_ENV */
7444 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7445 #endif /* AFS_NT40_ENV */
7446 if (code == 1 && FD_ISSET(socket, &imask)) {
7447 /* now receive a packet */
7448 faddrLen = sizeof(struct sockaddr_in);
7450 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7451 (struct sockaddr *)&faddr, &faddrLen);
7454 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7455 if (counter == ntohl(theader.callNumber))
7463 /* see if we've timed out */
7471 code -= sizeof(struct rx_header);
7472 if (code > outputLength)
7473 code = outputLength;
7474 memcpy(outputData, tp, code);
7477 #endif /* RXDEBUG */
7480 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7481 afs_uint16 remotePort, struct rx_debugStats * stat,
7482 afs_uint32 * supportedValues)
7484 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7486 struct rx_debugIn in;
7488 *supportedValues = 0;
7489 in.type = htonl(RX_DEBUGI_GETSTATS);
7492 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7493 &in, sizeof(in), stat, sizeof(*stat));
7496 * If the call was successful, fixup the version and indicate
7497 * what contents of the stat structure are valid.
7498 * Also do net to host conversion of fields here.
7502 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7503 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7505 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7506 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7508 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7509 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7511 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7512 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7514 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7515 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7517 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7518 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7520 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7521 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7523 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7524 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7526 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7527 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7529 stat->nFreePackets = ntohl(stat->nFreePackets);
7530 stat->packetReclaims = ntohl(stat->packetReclaims);
7531 stat->callsExecuted = ntohl(stat->callsExecuted);
7532 stat->nWaiting = ntohl(stat->nWaiting);
7533 stat->idleThreads = ntohl(stat->idleThreads);
7534 stat->nWaited = ntohl(stat->nWaited);
7535 stat->nPackets = ntohl(stat->nPackets);
7544 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7545 afs_uint16 remotePort, struct rx_statistics * stat,
7546 afs_uint32 * supportedValues)
7548 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7550 struct rx_debugIn in;
7551 afs_int32 *lp = (afs_int32 *) stat;
7555 * supportedValues is currently unused, but added to allow future
7556 * versioning of this function.
7559 *supportedValues = 0;
7560 in.type = htonl(RX_DEBUGI_RXSTATS);
7562 memset(stat, 0, sizeof(*stat));
7564 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7565 &in, sizeof(in), stat, sizeof(*stat));
7570 * Do net to host conversion here
7573 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7584 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7585 afs_uint16 remotePort, size_t version_length,
7588 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7590 return MakeDebugCall(socket, remoteAddr, remotePort,
7591 RX_PACKET_TYPE_VERSION, a, 1, version,
7599 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7600 afs_uint16 remotePort, afs_int32 * nextConnection,
7601 int allConnections, afs_uint32 debugSupportedValues,
7602 struct rx_debugConn * conn,
7603 afs_uint32 * supportedValues)
7605 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7607 struct rx_debugIn in;
7611 * supportedValues is currently unused, but added to allow future
7612 * versioning of this function.
7615 *supportedValues = 0;
7616 if (allConnections) {
7617 in.type = htonl(RX_DEBUGI_GETALLCONN);
7619 in.type = htonl(RX_DEBUGI_GETCONN);
7621 in.index = htonl(*nextConnection);
7622 memset(conn, 0, sizeof(*conn));
7624 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7625 &in, sizeof(in), conn, sizeof(*conn));
7628 *nextConnection += 1;
7631 * Convert old connection format to new structure.
7634 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7635 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7636 #define MOVEvL(a) (conn->a = vL->a)
7638 /* any old or unrecognized version... */
7639 for (i = 0; i < RX_MAXCALLS; i++) {
7640 MOVEvL(callState[i]);
7641 MOVEvL(callMode[i]);
7642 MOVEvL(callFlags[i]);
7643 MOVEvL(callOther[i]);
7645 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7646 MOVEvL(secStats.type);
7647 MOVEvL(secStats.level);
7648 MOVEvL(secStats.flags);
7649 MOVEvL(secStats.expires);
7650 MOVEvL(secStats.packetsReceived);
7651 MOVEvL(secStats.packetsSent);
7652 MOVEvL(secStats.bytesReceived);
7653 MOVEvL(secStats.bytesSent);
7658 * Do net to host conversion here
7660 * I don't convert host or port since we are most likely
7661 * going to want these in NBO.
7663 conn->cid = ntohl(conn->cid);
7664 conn->serial = ntohl(conn->serial);
7665 for (i = 0; i < RX_MAXCALLS; i++) {
7666 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7668 conn->error = ntohl(conn->error);
7669 conn->secStats.flags = ntohl(conn->secStats.flags);
7670 conn->secStats.expires = ntohl(conn->secStats.expires);
7671 conn->secStats.packetsReceived =
7672 ntohl(conn->secStats.packetsReceived);
7673 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7674 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7675 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7676 conn->epoch = ntohl(conn->epoch);
7677 conn->natMTU = ntohl(conn->natMTU);
7686 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7687 afs_uint16 remotePort, afs_int32 * nextPeer,
7688 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7689 afs_uint32 * supportedValues)
7691 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7693 struct rx_debugIn in;
7696 * supportedValues is currently unused, but added to allow future
7697 * versioning of this function.
7700 *supportedValues = 0;
7701 in.type = htonl(RX_DEBUGI_GETPEER);
7702 in.index = htonl(*nextPeer);
7703 memset(peer, 0, sizeof(*peer));
7705 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7706 &in, sizeof(in), peer, sizeof(*peer));
7712 * Do net to host conversion here
7714 * I don't convert host or port since we are most likely
7715 * going to want these in NBO.
7717 peer->ifMTU = ntohs(peer->ifMTU);
7718 peer->idleWhen = ntohl(peer->idleWhen);
7719 peer->refCount = ntohs(peer->refCount);
7720 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7721 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7722 peer->rtt = ntohl(peer->rtt);
7723 peer->rtt_dev = ntohl(peer->rtt_dev);
7724 peer->timeout.sec = ntohl(peer->timeout.sec);
7725 peer->timeout.usec = ntohl(peer->timeout.usec);
7726 peer->nSent = ntohl(peer->nSent);
7727 peer->reSends = ntohl(peer->reSends);
7728 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7729 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7730 peer->rateFlag = ntohl(peer->rateFlag);
7731 peer->natMTU = ntohs(peer->natMTU);
7732 peer->maxMTU = ntohs(peer->maxMTU);
7733 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7734 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7735 peer->MTU = ntohs(peer->MTU);
7736 peer->cwind = ntohs(peer->cwind);
7737 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7738 peer->congestSeq = ntohs(peer->congestSeq);
7739 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7740 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7741 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7742 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7751 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7752 struct rx_debugPeer * peerStats)
7755 afs_int32 error = 1; /* default to "did not succeed" */
7756 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7758 MUTEX_ENTER(&rx_peerHashTable_lock);
7759 for(tp = rx_peerHashTable[hashValue];
7760 tp != NULL; tp = tp->next) {
7761 if (tp->host == peerHost)
7767 MUTEX_EXIT(&rx_peerHashTable_lock);
7771 MUTEX_ENTER(&tp->peer_lock);
7772 peerStats->host = tp->host;
7773 peerStats->port = tp->port;
7774 peerStats->ifMTU = tp->ifMTU;
7775 peerStats->idleWhen = tp->idleWhen;
7776 peerStats->refCount = tp->refCount;
7777 peerStats->burstSize = tp->burstSize;
7778 peerStats->burst = tp->burst;
7779 peerStats->burstWait.sec = tp->burstWait.sec;
7780 peerStats->burstWait.usec = tp->burstWait.usec;
7781 peerStats->rtt = tp->rtt;
7782 peerStats->rtt_dev = tp->rtt_dev;
7783 peerStats->timeout.sec = tp->timeout.sec;
7784 peerStats->timeout.usec = tp->timeout.usec;
7785 peerStats->nSent = tp->nSent;
7786 peerStats->reSends = tp->reSends;
7787 peerStats->inPacketSkew = tp->inPacketSkew;
7788 peerStats->outPacketSkew = tp->outPacketSkew;
7789 peerStats->rateFlag = tp->rateFlag;
7790 peerStats->natMTU = tp->natMTU;
7791 peerStats->maxMTU = tp->maxMTU;
7792 peerStats->maxDgramPackets = tp->maxDgramPackets;
7793 peerStats->ifDgramPackets = tp->ifDgramPackets;
7794 peerStats->MTU = tp->MTU;
7795 peerStats->cwind = tp->cwind;
7796 peerStats->nDgramPackets = tp->nDgramPackets;
7797 peerStats->congestSeq = tp->congestSeq;
7798 peerStats->bytesSent.high = tp->bytesSent.high;
7799 peerStats->bytesSent.low = tp->bytesSent.low;
7800 peerStats->bytesReceived.high = tp->bytesReceived.high;
7801 peerStats->bytesReceived.low = tp->bytesReceived.low;
7802 MUTEX_EXIT(&tp->peer_lock);
7804 MUTEX_ENTER(&rx_peerHashTable_lock);
7807 MUTEX_EXIT(&rx_peerHashTable_lock);
7815 struct rx_serverQueueEntry *np;
7818 struct rx_call *call;
7819 struct rx_serverQueueEntry *sq;
7823 if (rxinit_status == 1) {
7825 return; /* Already shutdown. */
7829 #ifndef AFS_PTHREAD_ENV
7830 FD_ZERO(&rx_selectMask);
7831 #endif /* AFS_PTHREAD_ENV */
7832 rxi_dataQuota = RX_MAX_QUOTA;
7833 #ifndef AFS_PTHREAD_ENV
7835 #endif /* AFS_PTHREAD_ENV */
7838 #ifndef AFS_PTHREAD_ENV
7839 #ifndef AFS_USE_GETTIMEOFDAY
7841 #endif /* AFS_USE_GETTIMEOFDAY */
7842 #endif /* AFS_PTHREAD_ENV */
7844 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7845 call = queue_First(&rx_freeCallQueue, rx_call);
7847 rxi_Free(call, sizeof(struct rx_call));
7850 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7851 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7857 struct rx_peer **peer_ptr, **peer_end;
7858 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7859 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7861 struct rx_peer *peer, *next;
7863 MUTEX_ENTER(&rx_peerHashTable_lock);
7864 for (peer = *peer_ptr; peer; peer = next) {
7865 rx_interface_stat_p rpc_stat, nrpc_stat;
7868 MUTEX_ENTER(&rx_rpc_stats);
7869 MUTEX_ENTER(&peer->peer_lock);
7871 (&peer->rpcStats, rpc_stat, nrpc_stat,
7872 rx_interface_stat)) {
7873 unsigned int num_funcs;
7876 queue_Remove(&rpc_stat->queue_header);
7877 queue_Remove(&rpc_stat->all_peers);
7878 num_funcs = rpc_stat->stats[0].func_total;
7880 sizeof(rx_interface_stat_t) +
7881 rpc_stat->stats[0].func_total *
7882 sizeof(rx_function_entry_v1_t);
7884 rxi_Free(rpc_stat, space);
7886 /* rx_rpc_stats must be held */
7887 rxi_rpc_peer_stat_cnt -= num_funcs;
7889 MUTEX_EXIT(&peer->peer_lock);
7890 MUTEX_EXIT(&rx_rpc_stats);
7894 if (rx_stats_active)
7895 rx_atomic_dec(&rx_stats.nPeerStructs);
7897 MUTEX_EXIT(&rx_peerHashTable_lock);
7900 for (i = 0; i < RX_MAX_SERVICES; i++) {
7902 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7904 for (i = 0; i < rx_hashTableSize; i++) {
7905 struct rx_connection *tc, *ntc;
7906 MUTEX_ENTER(&rx_connHashTable_lock);
7907 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7909 for (j = 0; j < RX_MAXCALLS; j++) {
7911 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7914 rxi_Free(tc, sizeof(*tc));
7916 MUTEX_EXIT(&rx_connHashTable_lock);
7919 MUTEX_ENTER(&freeSQEList_lock);
7921 while ((np = rx_FreeSQEList)) {
7922 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7923 MUTEX_DESTROY(&np->lock);
7924 rxi_Free(np, sizeof(*np));
7927 MUTEX_EXIT(&freeSQEList_lock);
7928 MUTEX_DESTROY(&freeSQEList_lock);
7929 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7930 MUTEX_DESTROY(&rx_connHashTable_lock);
7931 MUTEX_DESTROY(&rx_peerHashTable_lock);
7932 MUTEX_DESTROY(&rx_serverPool_lock);
7934 osi_Free(rx_connHashTable,
7935 rx_hashTableSize * sizeof(struct rx_connection *));
7936 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7938 UNPIN(rx_connHashTable,
7939 rx_hashTableSize * sizeof(struct rx_connection *));
7940 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7942 rxi_FreeAllPackets();
7944 MUTEX_ENTER(&rx_quota_mutex);
7945 rxi_dataQuota = RX_MAX_QUOTA;
7946 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7947 MUTEX_EXIT(&rx_quota_mutex);
7952 #ifdef RX_ENABLE_LOCKS
7954 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7956 if (!MUTEX_ISMINE(lockaddr))
7957 osi_Panic("Lock not held: %s", msg);
7959 #endif /* RX_ENABLE_LOCKS */
7964 * Routines to implement connection specific data.
7968 rx_KeyCreate(rx_destructor_t rtn)
7971 MUTEX_ENTER(&rxi_keyCreate_lock);
7972 key = rxi_keyCreate_counter++;
7973 rxi_keyCreate_destructor = (rx_destructor_t *)
7974 realloc((void *)rxi_keyCreate_destructor,
7975 (key + 1) * sizeof(rx_destructor_t));
7976 rxi_keyCreate_destructor[key] = rtn;
7977 MUTEX_EXIT(&rxi_keyCreate_lock);
7982 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7985 MUTEX_ENTER(&conn->conn_data_lock);
7986 if (!conn->specific) {
7987 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7988 for (i = 0; i < key; i++)
7989 conn->specific[i] = NULL;
7990 conn->nSpecific = key + 1;
7991 conn->specific[key] = ptr;
7992 } else if (key >= conn->nSpecific) {
7993 conn->specific = (void **)
7994 realloc(conn->specific, (key + 1) * sizeof(void *));
7995 for (i = conn->nSpecific; i < key; i++)
7996 conn->specific[i] = NULL;
7997 conn->nSpecific = key + 1;
7998 conn->specific[key] = ptr;
8000 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8001 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8002 conn->specific[key] = ptr;
8004 MUTEX_EXIT(&conn->conn_data_lock);
8008 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8011 MUTEX_ENTER(&svc->svc_data_lock);
8012 if (!svc->specific) {
8013 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
8014 for (i = 0; i < key; i++)
8015 svc->specific[i] = NULL;
8016 svc->nSpecific = key + 1;
8017 svc->specific[key] = ptr;
8018 } else if (key >= svc->nSpecific) {
8019 svc->specific = (void **)
8020 realloc(svc->specific, (key + 1) * sizeof(void *));
8021 for (i = svc->nSpecific; i < key; i++)
8022 svc->specific[i] = NULL;
8023 svc->nSpecific = key + 1;
8024 svc->specific[key] = ptr;
8026 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8027 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8028 svc->specific[key] = ptr;
8030 MUTEX_EXIT(&svc->svc_data_lock);
8034 rx_GetSpecific(struct rx_connection *conn, int key)
8037 MUTEX_ENTER(&conn->conn_data_lock);
8038 if (key >= conn->nSpecific)
8041 ptr = conn->specific[key];
8042 MUTEX_EXIT(&conn->conn_data_lock);
8047 rx_GetServiceSpecific(struct rx_service *svc, int key)
8050 MUTEX_ENTER(&svc->svc_data_lock);
8051 if (key >= svc->nSpecific)
8054 ptr = svc->specific[key];
8055 MUTEX_EXIT(&svc->svc_data_lock);
8060 #endif /* !KERNEL */
8063 * processStats is a queue used to store the statistics for the local
8064 * process. Its contents are similar to the contents of the rpcStats
8065 * queue on a rx_peer structure, but the actual data stored within
8066 * this queue contains totals across the lifetime of the process (assuming
8067 * the stats have not been reset) - unlike the per peer structures
8068 * which can come and go based upon the peer lifetime.
8071 static struct rx_queue processStats = { &processStats, &processStats };
8074 * peerStats is a queue used to store the statistics for all peer structs.
8075 * Its contents are the union of all the peer rpcStats queues.
8078 static struct rx_queue peerStats = { &peerStats, &peerStats };
8081 * rxi_monitor_processStats is used to turn process wide stat collection
8085 static int rxi_monitor_processStats = 0;
8088 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8091 static int rxi_monitor_peerStats = 0;
8094 * rxi_AddRpcStat - given all of the information for a particular rpc
8095 * call, create (if needed) and update the stat totals for the rpc.
8099 * IN stats - the queue of stats that will be updated with the new value
8101 * IN rxInterface - a unique number that identifies the rpc interface
8103 * IN currentFunc - the index of the function being invoked
8105 * IN totalFunc - the total number of functions in this interface
8107 * IN queueTime - the amount of time this function waited for a thread
8109 * IN execTime - the amount of time this function invocation took to execute
8111 * IN bytesSent - the number bytes sent by this invocation
8113 * IN bytesRcvd - the number bytes received by this invocation
8115 * IN isServer - if true, this invocation was made to a server
8117 * IN remoteHost - the ip address of the remote host
8119 * IN remotePort - the port of the remote host
8121 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8123 * INOUT counter - if a new stats structure is allocated, the counter will
8124 * be updated with the new number of allocated stat structures
8132 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8133 afs_uint32 currentFunc, afs_uint32 totalFunc,
8134 struct clock *queueTime, struct clock *execTime,
8135 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8136 afs_uint32 remoteHost, afs_uint32 remotePort,
8137 int addToPeerList, unsigned int *counter)
8140 rx_interface_stat_p rpc_stat, nrpc_stat;
8143 * See if there's already a structure for this interface
8146 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8147 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8148 && (rpc_stat->stats[0].remote_is_server == isServer))
8153 * Didn't find a match so allocate a new structure and add it to the
8157 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8158 || (rpc_stat->stats[0].interfaceId != rxInterface)
8159 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8164 sizeof(rx_interface_stat_t) +
8165 totalFunc * sizeof(rx_function_entry_v1_t);
8167 rpc_stat = rxi_Alloc(space);
8168 if (rpc_stat == NULL) {
8172 *counter += totalFunc;
8173 for (i = 0; i < totalFunc; i++) {
8174 rpc_stat->stats[i].remote_peer = remoteHost;
8175 rpc_stat->stats[i].remote_port = remotePort;
8176 rpc_stat->stats[i].remote_is_server = isServer;
8177 rpc_stat->stats[i].interfaceId = rxInterface;
8178 rpc_stat->stats[i].func_total = totalFunc;
8179 rpc_stat->stats[i].func_index = i;
8180 hzero(rpc_stat->stats[i].invocations);
8181 hzero(rpc_stat->stats[i].bytes_sent);
8182 hzero(rpc_stat->stats[i].bytes_rcvd);
8183 rpc_stat->stats[i].queue_time_sum.sec = 0;
8184 rpc_stat->stats[i].queue_time_sum.usec = 0;
8185 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8186 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8187 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8188 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8189 rpc_stat->stats[i].queue_time_max.sec = 0;
8190 rpc_stat->stats[i].queue_time_max.usec = 0;
8191 rpc_stat->stats[i].execution_time_sum.sec = 0;
8192 rpc_stat->stats[i].execution_time_sum.usec = 0;
8193 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8194 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8195 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8196 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8197 rpc_stat->stats[i].execution_time_max.sec = 0;
8198 rpc_stat->stats[i].execution_time_max.usec = 0;
8200 queue_Prepend(stats, rpc_stat);
8201 if (addToPeerList) {
8202 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8207 * Increment the stats for this function
8210 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8211 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8212 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8213 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8214 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8215 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8216 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8218 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8219 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8221 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8222 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8224 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8225 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8227 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8228 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8236 * rx_IncrementTimeAndCount - increment the times and count for a particular
8241 * IN peer - the peer who invoked the rpc
8243 * IN rxInterface - a unique number that identifies the rpc interface
8245 * IN currentFunc - the index of the function being invoked
8247 * IN totalFunc - the total number of functions in this interface
8249 * IN queueTime - the amount of time this function waited for a thread
8251 * IN execTime - the amount of time this function invocation took to execute
8253 * IN bytesSent - the number bytes sent by this invocation
8255 * IN bytesRcvd - the number bytes received by this invocation
8257 * IN isServer - if true, this invocation was made to a server
8265 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8266 afs_uint32 currentFunc, afs_uint32 totalFunc,
8267 struct clock *queueTime, struct clock *execTime,
8268 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8272 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8275 MUTEX_ENTER(&rx_rpc_stats);
8277 if (rxi_monitor_peerStats) {
8278 MUTEX_ENTER(&peer->peer_lock);
8279 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8280 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8281 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8282 MUTEX_EXIT(&peer->peer_lock);
8285 if (rxi_monitor_processStats) {
8286 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8287 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8288 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8291 MUTEX_EXIT(&rx_rpc_stats);
8296 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8300 * IN callerVersion - the rpc stat version of the caller.
8302 * IN count - the number of entries to marshall.
8304 * IN stats - pointer to stats to be marshalled.
8306 * OUT ptr - Where to store the marshalled data.
8313 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8314 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8320 * We only support the first version
8322 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8323 *(ptr++) = stats->remote_peer;
8324 *(ptr++) = stats->remote_port;
8325 *(ptr++) = stats->remote_is_server;
8326 *(ptr++) = stats->interfaceId;
8327 *(ptr++) = stats->func_total;
8328 *(ptr++) = stats->func_index;
8329 *(ptr++) = hgethi(stats->invocations);
8330 *(ptr++) = hgetlo(stats->invocations);
8331 *(ptr++) = hgethi(stats->bytes_sent);
8332 *(ptr++) = hgetlo(stats->bytes_sent);
8333 *(ptr++) = hgethi(stats->bytes_rcvd);
8334 *(ptr++) = hgetlo(stats->bytes_rcvd);
8335 *(ptr++) = stats->queue_time_sum.sec;
8336 *(ptr++) = stats->queue_time_sum.usec;
8337 *(ptr++) = stats->queue_time_sum_sqr.sec;
8338 *(ptr++) = stats->queue_time_sum_sqr.usec;
8339 *(ptr++) = stats->queue_time_min.sec;
8340 *(ptr++) = stats->queue_time_min.usec;
8341 *(ptr++) = stats->queue_time_max.sec;
8342 *(ptr++) = stats->queue_time_max.usec;
8343 *(ptr++) = stats->execution_time_sum.sec;
8344 *(ptr++) = stats->execution_time_sum.usec;
8345 *(ptr++) = stats->execution_time_sum_sqr.sec;
8346 *(ptr++) = stats->execution_time_sum_sqr.usec;
8347 *(ptr++) = stats->execution_time_min.sec;
8348 *(ptr++) = stats->execution_time_min.usec;
8349 *(ptr++) = stats->execution_time_max.sec;
8350 *(ptr++) = stats->execution_time_max.usec;
8356 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8361 * IN callerVersion - the rpc stat version of the caller
8363 * OUT myVersion - the rpc stat version of this function
8365 * OUT clock_sec - local time seconds
8367 * OUT clock_usec - local time microseconds
8369 * OUT allocSize - the number of bytes allocated to contain stats
8371 * OUT statCount - the number stats retrieved from this process.
8373 * OUT stats - the actual stats retrieved from this process.
8377 * Returns void. If successful, stats will != NULL.
8381 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8382 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8383 size_t * allocSize, afs_uint32 * statCount,
8384 afs_uint32 ** stats)
8394 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8397 * Check to see if stats are enabled
8400 MUTEX_ENTER(&rx_rpc_stats);
8401 if (!rxi_monitor_processStats) {
8402 MUTEX_EXIT(&rx_rpc_stats);
8406 clock_GetTime(&now);
8407 *clock_sec = now.sec;
8408 *clock_usec = now.usec;
8411 * Allocate the space based upon the caller version
8413 * If the client is at an older version than we are,
8414 * we return the statistic data in the older data format, but
8415 * we still return our version number so the client knows we
8416 * are maintaining more data than it can retrieve.
8419 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8420 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8421 *statCount = rxi_rpc_process_stat_cnt;
8424 * This can't happen yet, but in the future version changes
8425 * can be handled by adding additional code here
8429 if (space > (size_t) 0) {
8431 ptr = *stats = rxi_Alloc(space);
8434 rx_interface_stat_p rpc_stat, nrpc_stat;
8438 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8440 * Copy the data based upon the caller version
8442 rx_MarshallProcessRPCStats(callerVersion,
8443 rpc_stat->stats[0].func_total,
8444 rpc_stat->stats, &ptr);
8450 MUTEX_EXIT(&rx_rpc_stats);
8455 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8459 * IN callerVersion - the rpc stat version of the caller
8461 * OUT myVersion - the rpc stat version of this function
8463 * OUT clock_sec - local time seconds
8465 * OUT clock_usec - local time microseconds
8467 * OUT allocSize - the number of bytes allocated to contain stats
8469 * OUT statCount - the number of stats retrieved from the individual
8472 * OUT stats - the actual stats retrieved from the individual peer structures.
8476 * Returns void. If successful, stats will != NULL.
8480 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8481 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8482 size_t * allocSize, afs_uint32 * statCount,
8483 afs_uint32 ** stats)
8493 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8496 * Check to see if stats are enabled
8499 MUTEX_ENTER(&rx_rpc_stats);
8500 if (!rxi_monitor_peerStats) {
8501 MUTEX_EXIT(&rx_rpc_stats);
8505 clock_GetTime(&now);
8506 *clock_sec = now.sec;
8507 *clock_usec = now.usec;
8510 * Allocate the space based upon the caller version
8512 * If the client is at an older version than we are,
8513 * we return the statistic data in the older data format, but
8514 * we still return our version number so the client knows we
8515 * are maintaining more data than it can retrieve.
8518 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8519 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8520 *statCount = rxi_rpc_peer_stat_cnt;
8523 * This can't happen yet, but in the future version changes
8524 * can be handled by adding additional code here
8528 if (space > (size_t) 0) {
8530 ptr = *stats = rxi_Alloc(space);
8533 rx_interface_stat_p rpc_stat, nrpc_stat;
8537 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8539 * We have to fix the offset of rpc_stat since we are
8540 * keeping this structure on two rx_queues. The rx_queue
8541 * package assumes that the rx_queue member is the first
8542 * member of the structure. That is, rx_queue assumes that
8543 * any one item is only on one queue at a time. We are
8544 * breaking that assumption and so we have to do a little
8545 * math to fix our pointers.
8548 fix_offset = (char *)rpc_stat;
8549 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8550 rpc_stat = (rx_interface_stat_p) fix_offset;
8553 * Copy the data based upon the caller version
8555 rx_MarshallProcessRPCStats(callerVersion,
8556 rpc_stat->stats[0].func_total,
8557 rpc_stat->stats, &ptr);
8563 MUTEX_EXIT(&rx_rpc_stats);
8568 * rx_FreeRPCStats - free memory allocated by
8569 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8573 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8574 * rx_RetrievePeerRPCStats
8576 * IN allocSize - the number of bytes in stats.
8584 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8586 rxi_Free(stats, allocSize);
8590 * rx_queryProcessRPCStats - see if process rpc stat collection is
8591 * currently enabled.
8597 * Returns 0 if stats are not enabled != 0 otherwise
8601 rx_queryProcessRPCStats(void)
8604 MUTEX_ENTER(&rx_rpc_stats);
8605 rc = rxi_monitor_processStats;
8606 MUTEX_EXIT(&rx_rpc_stats);
8611 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8617 * Returns 0 if stats are not enabled != 0 otherwise
8621 rx_queryPeerRPCStats(void)
8624 MUTEX_ENTER(&rx_rpc_stats);
8625 rc = rxi_monitor_peerStats;
8626 MUTEX_EXIT(&rx_rpc_stats);
8631 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8641 rx_enableProcessRPCStats(void)
8643 MUTEX_ENTER(&rx_rpc_stats);
8644 rx_enable_stats = 1;
8645 rxi_monitor_processStats = 1;
8646 MUTEX_EXIT(&rx_rpc_stats);
8650 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8660 rx_enablePeerRPCStats(void)
8662 MUTEX_ENTER(&rx_rpc_stats);
8663 rx_enable_stats = 1;
8664 rxi_monitor_peerStats = 1;
8665 MUTEX_EXIT(&rx_rpc_stats);
8669 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8679 rx_disableProcessRPCStats(void)
8681 rx_interface_stat_p rpc_stat, nrpc_stat;
8684 MUTEX_ENTER(&rx_rpc_stats);
8687 * Turn off process statistics and if peer stats is also off, turn
8691 rxi_monitor_processStats = 0;
8692 if (rxi_monitor_peerStats == 0) {
8693 rx_enable_stats = 0;
8696 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8697 unsigned int num_funcs = 0;
8700 queue_Remove(rpc_stat);
8701 num_funcs = rpc_stat->stats[0].func_total;
8703 sizeof(rx_interface_stat_t) +
8704 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8706 rxi_Free(rpc_stat, space);
8707 rxi_rpc_process_stat_cnt -= num_funcs;
8709 MUTEX_EXIT(&rx_rpc_stats);
8713 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8723 rx_disablePeerRPCStats(void)
8725 struct rx_peer **peer_ptr, **peer_end;
8729 * Turn off peer statistics and if process stats is also off, turn
8733 rxi_monitor_peerStats = 0;
8734 if (rxi_monitor_processStats == 0) {
8735 rx_enable_stats = 0;
8738 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8739 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8741 struct rx_peer *peer, *next, *prev;
8743 MUTEX_ENTER(&rx_peerHashTable_lock);
8744 MUTEX_ENTER(&rx_rpc_stats);
8745 for (prev = peer = *peer_ptr; peer; peer = next) {
8747 code = MUTEX_TRYENTER(&peer->peer_lock);
8749 rx_interface_stat_p rpc_stat, nrpc_stat;
8752 if (prev == *peer_ptr) {
8763 MUTEX_EXIT(&rx_peerHashTable_lock);
8766 (&peer->rpcStats, rpc_stat, nrpc_stat,
8767 rx_interface_stat)) {
8768 unsigned int num_funcs = 0;
8771 queue_Remove(&rpc_stat->queue_header);
8772 queue_Remove(&rpc_stat->all_peers);
8773 num_funcs = rpc_stat->stats[0].func_total;
8775 sizeof(rx_interface_stat_t) +
8776 rpc_stat->stats[0].func_total *
8777 sizeof(rx_function_entry_v1_t);
8779 rxi_Free(rpc_stat, space);
8780 rxi_rpc_peer_stat_cnt -= num_funcs;
8782 MUTEX_EXIT(&peer->peer_lock);
8784 MUTEX_ENTER(&rx_peerHashTable_lock);
8794 MUTEX_EXIT(&rx_rpc_stats);
8795 MUTEX_EXIT(&rx_peerHashTable_lock);
8800 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8805 * IN clearFlag - flag indicating which stats to clear
8813 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8815 rx_interface_stat_p rpc_stat, nrpc_stat;
8817 MUTEX_ENTER(&rx_rpc_stats);
8819 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8820 unsigned int num_funcs = 0, i;
8821 num_funcs = rpc_stat->stats[0].func_total;
8822 for (i = 0; i < num_funcs; i++) {
8823 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8824 hzero(rpc_stat->stats[i].invocations);
8826 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8827 hzero(rpc_stat->stats[i].bytes_sent);
8829 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8830 hzero(rpc_stat->stats[i].bytes_rcvd);
8832 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8833 rpc_stat->stats[i].queue_time_sum.sec = 0;
8834 rpc_stat->stats[i].queue_time_sum.usec = 0;
8836 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8837 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8838 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8840 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8841 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8842 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8844 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8845 rpc_stat->stats[i].queue_time_max.sec = 0;
8846 rpc_stat->stats[i].queue_time_max.usec = 0;
8848 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8849 rpc_stat->stats[i].execution_time_sum.sec = 0;
8850 rpc_stat->stats[i].execution_time_sum.usec = 0;
8852 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8853 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8854 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8856 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8857 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8858 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8860 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8861 rpc_stat->stats[i].execution_time_max.sec = 0;
8862 rpc_stat->stats[i].execution_time_max.usec = 0;
8867 MUTEX_EXIT(&rx_rpc_stats);
8871 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8876 * IN clearFlag - flag indicating which stats to clear
8884 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8886 rx_interface_stat_p rpc_stat, nrpc_stat;
8888 MUTEX_ENTER(&rx_rpc_stats);
8890 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8891 unsigned int num_funcs = 0, i;
8894 * We have to fix the offset of rpc_stat since we are
8895 * keeping this structure on two rx_queues. The rx_queue
8896 * package assumes that the rx_queue member is the first
8897 * member of the structure. That is, rx_queue assumes that
8898 * any one item is only on one queue at a time. We are
8899 * breaking that assumption and so we have to do a little
8900 * math to fix our pointers.
8903 fix_offset = (char *)rpc_stat;
8904 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8905 rpc_stat = (rx_interface_stat_p) fix_offset;
8907 num_funcs = rpc_stat->stats[0].func_total;
8908 for (i = 0; i < num_funcs; i++) {
8909 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8910 hzero(rpc_stat->stats[i].invocations);
8912 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8913 hzero(rpc_stat->stats[i].bytes_sent);
8915 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8916 hzero(rpc_stat->stats[i].bytes_rcvd);
8918 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8919 rpc_stat->stats[i].queue_time_sum.sec = 0;
8920 rpc_stat->stats[i].queue_time_sum.usec = 0;
8922 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8923 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8924 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8926 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8927 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8928 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8930 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8931 rpc_stat->stats[i].queue_time_max.sec = 0;
8932 rpc_stat->stats[i].queue_time_max.usec = 0;
8934 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8935 rpc_stat->stats[i].execution_time_sum.sec = 0;
8936 rpc_stat->stats[i].execution_time_sum.usec = 0;
8938 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8939 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8940 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8942 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8943 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8944 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8946 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8947 rpc_stat->stats[i].execution_time_max.sec = 0;
8948 rpc_stat->stats[i].execution_time_max.usec = 0;
8953 MUTEX_EXIT(&rx_rpc_stats);
8957 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8958 * is authorized to enable/disable/clear RX statistics.
8960 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8963 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8965 rxi_rxstat_userok = proc;
8969 rx_RxStatUserOk(struct rx_call *call)
8971 if (!rxi_rxstat_userok)
8973 return rxi_rxstat_userok(call);
8978 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8979 * function in the MSVC runtime DLL (msvcrt.dll).
8981 * Note: the system serializes calls to this function.
8984 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8985 DWORD reason, /* reason function is being called */
8986 LPVOID reserved) /* reserved for future use */
8989 case DLL_PROCESS_ATTACH:
8990 /* library is being attached to a process */
8994 case DLL_PROCESS_DETACH:
9001 #endif /* AFS_NT40_ENV */
9004 int rx_DumpCalls(FILE *outputFile, char *cookie)
9006 #ifdef RXDEBUG_PACKET
9007 #ifdef KDUMP_RX_LOCK
9008 struct rx_call_rx_lock *c;
9015 #define RXDPRINTF sprintf
9016 #define RXDPRINTOUT output
9018 #define RXDPRINTF fprintf
9019 #define RXDPRINTOUT outputFile
9022 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9024 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9027 for (c = rx_allCallsp; c; c = c->allNextp) {
9028 u_short rqc, tqc, iovqc;
9029 struct rx_packet *p, *np;
9031 MUTEX_ENTER(&c->lock);
9032 queue_Count(&c->rq, p, np, rx_packet, rqc);
9033 queue_Count(&c->tq, p, np, rx_packet, tqc);
9034 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9036 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, "
9037 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9038 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9039 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9040 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9041 #ifdef RX_ENABLE_LOCKS
9044 #ifdef RX_REFCOUNT_CHECK
9045 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9046 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9049 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,
9050 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9051 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9052 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9053 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9054 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9055 #ifdef RX_ENABLE_LOCKS
9056 , (afs_uint32)c->refCount
9058 #ifdef RX_REFCOUNT_CHECK
9059 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9062 MUTEX_EXIT(&c->lock);
9065 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9068 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9070 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9072 #endif /* RXDEBUG_PACKET */