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>
14 #include "afs/param.h"
16 #include <afs/param.h>
23 #include "afs/sysincludes.h"
24 #include "afsincludes.h"
30 #include <net/net_globals.h>
31 #endif /* AFS_OSF_ENV */
32 #ifdef AFS_LINUX20_ENV
35 #include "netinet/in.h"
36 #include "afs/afs_args.h"
37 #include "afs/afs_osi.h"
38 #ifdef RX_KERNEL_TRACE
39 #include "rx_kcommon.h"
41 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
45 #undef RXDEBUG /* turn off debugging */
47 #if defined(AFS_SGI_ENV)
48 #include "sys/debug.h"
57 #endif /* AFS_ALPHA_ENV */
59 #include "afs/sysincludes.h"
60 #include "afsincludes.h"
63 #include "rx_kmutex.h"
64 #include "rx_kernel.h"
68 #include "rx_globals.h"
70 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
71 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
72 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
74 extern afs_int32 afs_termState;
76 #include "sys/lockl.h"
77 #include "sys/lock_def.h"
78 #endif /* AFS_AIX41_ENV */
79 # include "rxgen_consts.h"
81 # include <sys/types.h>
86 # include <afs/afsutil.h>
88 # include <sys/socket.h>
89 # include <sys/file.h>
91 # include <sys/stat.h>
92 # include <netinet/in.h>
93 # include <sys/time.h>
103 # include "rx_user.h"
104 # include "rx_clock.h"
105 # include "rx_queue.h"
106 # include "rx_globals.h"
107 # include "rx_trace.h"
108 # include <afs/rxgen_consts.h>
111 int (*registerProgram) () = 0;
112 int (*swapNameProgram) () = 0;
114 /* Local static routines */
115 static void rxi_DestroyConnectionNoLock(register struct rx_connection *conn);
116 #ifdef RX_ENABLE_LOCKS
117 static void rxi_SetAcksInTransmitQueue(register struct rx_call *call);
120 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
122 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
123 afs_int32 rxi_start_in_error;
125 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
128 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
129 * currently allocated within rx. This number is used to allocate the
130 * memory required to return the statistics when queried.
133 static unsigned int rxi_rpc_peer_stat_cnt;
136 * rxi_rpc_process_stat_cnt counts the total number of local process stat
137 * structures currently allocated within rx. The number is used to allocate
138 * the memory required to return the statistics when queried.
141 static unsigned int rxi_rpc_process_stat_cnt;
143 #if !defined(offsetof)
144 #include <stddef.h> /* for definition of offsetof() */
147 #ifdef AFS_PTHREAD_ENV
151 * Use procedural initialization of mutexes/condition variables
155 extern pthread_mutex_t rx_stats_mutex;
156 extern pthread_mutex_t rxkad_stats_mutex;
157 extern pthread_mutex_t des_init_mutex;
158 extern pthread_mutex_t des_random_mutex;
159 extern pthread_mutex_t rx_clock_mutex;
160 extern pthread_mutex_t rxi_connCacheMutex;
161 extern pthread_mutex_t rx_event_mutex;
162 extern pthread_mutex_t osi_malloc_mutex;
163 extern pthread_mutex_t event_handler_mutex;
164 extern pthread_mutex_t listener_mutex;
165 extern pthread_mutex_t rx_if_init_mutex;
166 extern pthread_mutex_t rx_if_mutex;
167 extern pthread_mutex_t rxkad_client_uid_mutex;
168 extern pthread_mutex_t rxkad_random_mutex;
170 extern pthread_cond_t rx_event_handler_cond;
171 extern pthread_cond_t rx_listener_cond;
173 static pthread_mutex_t epoch_mutex;
174 static pthread_mutex_t rx_init_mutex;
175 static pthread_mutex_t rx_debug_mutex;
178 rxi_InitPthread(void)
180 assert(pthread_mutex_init(&rx_clock_mutex, (const pthread_mutexattr_t *)0)
182 assert(pthread_mutex_init(&rx_stats_mutex, (const pthread_mutexattr_t *)0)
184 assert(pthread_mutex_init
185 (&rxi_connCacheMutex, (const pthread_mutexattr_t *)0) == 0);
186 assert(pthread_mutex_init(&rx_init_mutex, (const pthread_mutexattr_t *)0)
188 assert(pthread_mutex_init(&epoch_mutex, (const pthread_mutexattr_t *)0) ==
190 assert(pthread_mutex_init(&rx_event_mutex, (const pthread_mutexattr_t *)0)
192 assert(pthread_mutex_init(&des_init_mutex, (const pthread_mutexattr_t *)0)
194 assert(pthread_mutex_init
195 (&des_random_mutex, (const pthread_mutexattr_t *)0) == 0);
196 assert(pthread_mutex_init
197 (&osi_malloc_mutex, (const pthread_mutexattr_t *)0) == 0);
198 assert(pthread_mutex_init
199 (&event_handler_mutex, (const pthread_mutexattr_t *)0) == 0);
200 assert(pthread_mutex_init(&listener_mutex, (const pthread_mutexattr_t *)0)
202 assert(pthread_mutex_init
203 (&rx_if_init_mutex, (const pthread_mutexattr_t *)0) == 0);
204 assert(pthread_mutex_init(&rx_if_mutex, (const pthread_mutexattr_t *)0) ==
206 assert(pthread_mutex_init
207 (&rxkad_client_uid_mutex, (const pthread_mutexattr_t *)0) == 0);
208 assert(pthread_mutex_init
209 (&rxkad_random_mutex, (const pthread_mutexattr_t *)0) == 0);
210 assert(pthread_mutex_init
211 (&rxkad_stats_mutex, (const pthread_mutexattr_t *)0) == 0);
212 assert(pthread_mutex_init(&rx_debug_mutex, (const pthread_mutexattr_t *)0)
215 assert(pthread_cond_init
216 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
217 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
219 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
222 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
223 #define INIT_PTHREAD_LOCKS \
224 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0);
226 * The rx_stats_mutex mutex protects the following global variables:
231 * rxi_lowConnRefCount
232 * rxi_lowPeerRefCount
241 #define INIT_PTHREAD_LOCKS
245 /* Variables for handling the minProcs implementation. availProcs gives the
246 * number of threads available in the pool at this moment (not counting dudes
247 * executing right now). totalMin gives the total number of procs required
248 * for handling all minProcs requests. minDeficit is a dynamic variable
249 * tracking the # of procs required to satisfy all of the remaining minProcs
251 * For fine grain locking to work, the quota check and the reservation of
252 * a server thread has to come while rxi_availProcs and rxi_minDeficit
253 * are locked. To this end, the code has been modified under #ifdef
254 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
255 * same time. A new function, ReturnToServerPool() returns the allocation.
257 * A call can be on several queue's (but only one at a time). When
258 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
259 * that no one else is touching the queue. To this end, we store the address
260 * of the queue lock in the call structure (under the call lock) when we
261 * put the call on a queue, and we clear the call_queue_lock when the
262 * call is removed from a queue (once the call lock has been obtained).
263 * This allows rxi_ResetCall to safely synchronize with others wishing
264 * to manipulate the queue.
267 #ifdef RX_ENABLE_LOCKS
268 static afs_kmutex_t rx_rpc_stats;
269 void rxi_StartUnlocked();
272 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
273 ** pretty good that the next packet coming in is from the same connection
274 ** as the last packet, since we're send multiple packets in a transmit window.
276 struct rx_connection *rxLastConn = 0;
278 #ifdef RX_ENABLE_LOCKS
279 /* The locking hierarchy for rx fine grain locking is composed of these
282 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
283 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
284 * call->lock - locks call data fields.
285 * These are independent of each other:
286 * rx_freeCallQueue_lock
291 * serverQueueEntry->lock
293 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
294 * peer->lock - locks peer data fields.
295 * conn_data_lock - that more than one thread is not updating a conn data
296 * field at the same time.
304 * Do we need a lock to protect the peer field in the conn structure?
305 * conn->peer was previously a constant for all intents and so has no
306 * lock protecting this field. The multihomed client delta introduced
307 * a RX code change : change the peer field in the connection structure
308 * to that remote inetrface from which the last packet for this
309 * connection was sent out. This may become an issue if further changes
312 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
313 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
315 /* rxdb_fileID is used to identify the lock location, along with line#. */
316 static int rxdb_fileID = RXDB_FILE_RX;
317 #endif /* RX_LOCKS_DB */
318 #else /* RX_ENABLE_LOCKS */
319 #define SET_CALL_QUEUE_LOCK(C, L)
320 #define CLEAR_CALL_QUEUE_LOCK(C)
321 #endif /* RX_ENABLE_LOCKS */
322 struct rx_serverQueueEntry *rx_waitForPacket = 0;
323 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
325 /* ------------Exported Interfaces------------- */
327 /* This function allows rxkad to set the epoch to a suitably random number
328 * which rx_NewConnection will use in the future. The principle purpose is to
329 * get rxnull connections to use the same epoch as the rxkad connections do, at
330 * least once the first rxkad connection is established. This is important now
331 * that the host/port addresses aren't used in FindConnection: the uniqueness
332 * of epoch/cid matters and the start time won't do. */
334 #ifdef AFS_PTHREAD_ENV
336 * This mutex protects the following global variables:
340 #define LOCK_EPOCH assert(pthread_mutex_lock(&epoch_mutex)==0);
341 #define UNLOCK_EPOCH assert(pthread_mutex_unlock(&epoch_mutex)==0);
345 #endif /* AFS_PTHREAD_ENV */
348 rx_SetEpoch(afs_uint32 epoch)
350 LOCK_EPOCH rx_epoch = epoch;
353 /* Initialize rx. A port number may be mentioned, in which case this
354 * becomes the default port number for any service installed later.
355 * If 0 is provided for the port number, a random port will be chosen
356 * by the kernel. Whether this will ever overlap anything in
357 * /etc/services is anybody's guess... Returns 0 on success, -1 on
359 static int rxinit_status = 1;
360 #ifdef AFS_PTHREAD_ENV
362 * This mutex protects the following global variables:
366 #define LOCK_RX_INIT assert(pthread_mutex_lock(&rx_init_mutex)==0);
367 #define UNLOCK_RX_INIT assert(pthread_mutex_unlock(&rx_init_mutex)==0);
370 #define UNLOCK_RX_INIT
381 char *htable, *ptable;
384 #if defined(AFS_DJGPP_ENV) && !defined(DEBUG)
385 __djgpp_set_quiet_socket(1);
390 INIT_PTHREAD_LOCKS LOCK_RX_INIT if (rxinit_status == 0) {
391 tmp_status = rxinit_status;
392 UNLOCK_RX_INIT return tmp_status; /* Already started; return previous error code. */
395 if (afs_winsockInit() < 0)
401 * Initialize anything necessary to provide a non-premptive threading
404 rxi_InitializeThreadSupport();
407 /* Allocate and initialize a socket for client and perhaps server
410 rx_socket = rxi_GetUDPSocket((u_short) port);
411 if (rx_socket == OSI_NULLSOCKET) {
412 UNLOCK_RX_INIT return RX_ADDRINUSE;
414 #ifdef RX_ENABLE_LOCKS
417 #endif /* RX_LOCKS_DB */
418 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
419 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
420 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
421 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
422 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
424 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
426 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
428 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
430 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
432 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
434 #if defined(KERNEL) && defined(AFS_HPUX110_ENV)
436 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
437 #endif /* KERNEL && AFS_HPUX110_ENV */
438 #else /* RX_ENABLE_LOCKS */
439 #if defined(KERNEL) && defined(AFS_GLOBAL_SUNLOCK) && !defined(AFS_HPUX_ENV) && !defined(AFS_OBSD_ENV)
440 mutex_init(&afs_rxglobal_lock, "afs_rxglobal_lock", MUTEX_DEFAULT, NULL);
441 #endif /* AFS_GLOBAL_SUNLOCK */
442 #endif /* RX_ENABLE_LOCKS */
445 rx_connDeadTime = 12;
446 rx_tranquil = 0; /* reset flag */
447 memset((char *)&rx_stats, 0, sizeof(struct rx_stats));
449 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
450 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
451 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
452 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
453 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
454 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
456 /* Malloc up a bunch of packets & buffers */
458 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
459 queue_Init(&rx_freePacketQueue);
460 rxi_NeedMorePackets = FALSE;
461 rxi_MorePackets(rx_nPackets);
469 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
470 tv.tv_sec = clock_now.sec;
471 tv.tv_usec = clock_now.usec;
472 srand((unsigned int)tv.tv_usec);
479 #if defined(KERNEL) && !defined(UKERNEL)
480 /* Really, this should never happen in a real kernel */
483 struct sockaddr_in addr;
484 int addrlen = sizeof(addr);
485 if (getsockname((int)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
489 rx_port = addr.sin_port;
492 rx_stats.minRtt.sec = 9999999;
494 rx_SetEpoch(tv.tv_sec | 0x80000000);
496 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
497 * will provide a randomer value. */
499 MUTEX_ENTER(&rx_stats_mutex);
500 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
501 MUTEX_EXIT(&rx_stats_mutex);
502 /* *Slightly* random start time for the cid. This is just to help
503 * out with the hashing function at the peer */
504 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
505 rx_connHashTable = (struct rx_connection **)htable;
506 rx_peerHashTable = (struct rx_peer **)ptable;
508 rx_lastAckDelay.sec = 0;
509 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
510 rx_hardAckDelay.sec = 0;
511 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
512 rx_softAckDelay.sec = 0;
513 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
515 rxevent_Init(20, rxi_ReScheduleEvents);
517 /* Initialize various global queues */
518 queue_Init(&rx_idleServerQueue);
519 queue_Init(&rx_incomingCallQueue);
520 queue_Init(&rx_freeCallQueue);
522 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
523 /* Initialize our list of usable IP addresses. */
527 /* Start listener process (exact function is dependent on the
528 * implementation environment--kernel or user space) */
533 tmp_status = rxinit_status = 0;
534 UNLOCK_RX_INIT return tmp_status;
537 /* called with unincremented nRequestsRunning to see if it is OK to start
538 * a new thread in this service. Could be "no" for two reasons: over the
539 * max quota, or would prevent others from reaching their min quota.
541 #ifdef RX_ENABLE_LOCKS
542 /* This verion of QuotaOK reserves quota if it's ok while the
543 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
546 QuotaOK(register struct rx_service *aservice)
548 /* check if over max quota */
549 if (aservice->nRequestsRunning >= aservice->maxProcs) {
553 /* under min quota, we're OK */
554 /* otherwise, can use only if there are enough to allow everyone
555 * to go to their min quota after this guy starts.
557 MUTEX_ENTER(&rx_stats_mutex);
558 if ((aservice->nRequestsRunning < aservice->minProcs)
559 || (rxi_availProcs > rxi_minDeficit)) {
560 aservice->nRequestsRunning++;
561 /* just started call in minProcs pool, need fewer to maintain
563 if (aservice->nRequestsRunning <= aservice->minProcs)
566 MUTEX_EXIT(&rx_stats_mutex);
569 MUTEX_EXIT(&rx_stats_mutex);
575 ReturnToServerPool(register struct rx_service *aservice)
577 aservice->nRequestsRunning--;
578 MUTEX_ENTER(&rx_stats_mutex);
579 if (aservice->nRequestsRunning < aservice->minProcs)
582 MUTEX_EXIT(&rx_stats_mutex);
585 #else /* RX_ENABLE_LOCKS */
587 QuotaOK(register struct rx_service *aservice)
590 /* under min quota, we're OK */
591 if (aservice->nRequestsRunning < aservice->minProcs)
594 /* check if over max quota */
595 if (aservice->nRequestsRunning >= aservice->maxProcs)
598 /* otherwise, can use only if there are enough to allow everyone
599 * to go to their min quota after this guy starts.
601 if (rxi_availProcs > rxi_minDeficit)
605 #endif /* RX_ENABLE_LOCKS */
608 /* Called by rx_StartServer to start up lwp's to service calls.
609 NExistingProcs gives the number of procs already existing, and which
610 therefore needn't be created. */
612 rxi_StartServerProcs(int nExistingProcs)
614 register struct rx_service *service;
619 /* For each service, reserve N processes, where N is the "minimum"
620 * number of processes that MUST be able to execute a request in parallel,
621 * at any time, for that process. Also compute the maximum difference
622 * between any service's maximum number of processes that can run
623 * (i.e. the maximum number that ever will be run, and a guarantee
624 * that this number will run if other services aren't running), and its
625 * minimum number. The result is the extra number of processes that
626 * we need in order to provide the latter guarantee */
627 for (i = 0; i < RX_MAX_SERVICES; i++) {
629 service = rx_services[i];
630 if (service == (struct rx_service *)0)
632 nProcs += service->minProcs;
633 diff = service->maxProcs - service->minProcs;
637 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
638 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
639 for (i = 0; i < nProcs; i++) {
640 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
645 /* This routine must be called if any services are exported. If the
646 * donateMe flag is set, the calling process is donated to the server
649 rx_StartServer(int donateMe)
651 register struct rx_service *service;
652 register int i, nProcs = 0;
658 /* Start server processes, if necessary (exact function is dependent
659 * on the implementation environment--kernel or user space). DonateMe
660 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
661 * case, one less new proc will be created rx_StartServerProcs.
663 rxi_StartServerProcs(donateMe);
665 /* count up the # of threads in minProcs, and add set the min deficit to
666 * be that value, too.
668 for (i = 0; i < RX_MAX_SERVICES; i++) {
669 service = rx_services[i];
670 if (service == (struct rx_service *)0)
672 MUTEX_ENTER(&rx_stats_mutex);
673 rxi_totalMin += service->minProcs;
674 /* below works even if a thread is running, since minDeficit would
675 * still have been decremented and later re-incremented.
677 rxi_minDeficit += service->minProcs;
678 MUTEX_EXIT(&rx_stats_mutex);
681 /* Turn on reaping of idle server connections */
682 rxi_ReapConnections();
691 #ifdef AFS_PTHREAD_ENV
693 pid = (pid_t) pthread_self();
694 #else /* AFS_PTHREAD_ENV */
696 LWP_CurrentProcess(&pid);
697 #endif /* AFS_PTHREAD_ENV */
699 sprintf(name, "srv_%d", ++nProcs);
701 (*registerProgram) (pid, name);
703 #endif /* AFS_NT40_ENV */
704 rx_ServerProc(); /* Never returns */
709 /* Create a new client connection to the specified service, using the
710 * specified security object to implement the security model for this
712 struct rx_connection *
713 rx_NewConnection(register afs_uint32 shost, u_short sport, u_short sservice,
714 register struct rx_securityClass *securityObject,
715 int serviceSecurityIndex)
719 register struct rx_connection *conn;
724 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n", shost, sport, sservice, securityObject, serviceSecurityIndex));
726 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
727 * the case of kmem_alloc? */
728 conn = rxi_AllocConnection();
729 #ifdef RX_ENABLE_LOCKS
730 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
731 MUTEX_INIT(&conn->conn_data_lock, "conn call lock", MUTEX_DEFAULT, 0);
732 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
736 MUTEX_ENTER(&rx_connHashTable_lock);
737 cid = (rx_nextCid += RX_MAXCALLS);
738 conn->type = RX_CLIENT_CONNECTION;
740 conn->epoch = rx_epoch;
741 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
742 conn->serviceId = sservice;
743 conn->securityObject = securityObject;
744 /* This doesn't work in all compilers with void (they're buggy), so fake it
746 conn->securityData = (VOID *) 0;
747 conn->securityIndex = serviceSecurityIndex;
748 rx_SetConnDeadTime(conn, rx_connDeadTime);
749 conn->ackRate = RX_FAST_ACK_RATE;
751 conn->specific = NULL;
752 conn->challengeEvent = NULL;
753 conn->delayedAbortEvent = NULL;
754 conn->abortCount = 0;
757 RXS_NewConnection(securityObject, conn);
759 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
761 conn->refCount++; /* no lock required since only this thread knows... */
762 conn->next = rx_connHashTable[hashindex];
763 rx_connHashTable[hashindex] = conn;
764 MUTEX_ENTER(&rx_stats_mutex);
765 rx_stats.nClientConns++;
766 MUTEX_EXIT(&rx_stats_mutex);
768 MUTEX_EXIT(&rx_connHashTable_lock);
775 rx_SetConnDeadTime(register struct rx_connection *conn, register int seconds)
777 /* The idea is to set the dead time to a value that allows several
778 * keepalives to be dropped without timing out the connection. */
779 conn->secondsUntilDead = MAX(seconds, 6);
780 conn->secondsUntilPing = conn->secondsUntilDead / 6;
783 int rxi_lowPeerRefCount = 0;
784 int rxi_lowConnRefCount = 0;
787 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
788 * NOTE: must not be called with rx_connHashTable_lock held.
791 rxi_CleanupConnection(struct rx_connection *conn)
793 /* Notify the service exporter, if requested, that this connection
794 * is being destroyed */
795 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
796 (*conn->service->destroyConnProc) (conn);
798 /* Notify the security module that this connection is being destroyed */
799 RXS_DestroyConnection(conn->securityObject, conn);
801 /* If this is the last connection using the rx_peer struct, set its
802 * idle time to now. rxi_ReapConnections will reap it if it's still
803 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
805 MUTEX_ENTER(&rx_peerHashTable_lock);
806 if (--conn->peer->refCount <= 0) {
807 conn->peer->idleWhen = clock_Sec();
808 if (conn->peer->refCount < 0) {
809 conn->peer->refCount = 0;
810 MUTEX_ENTER(&rx_stats_mutex);
811 rxi_lowPeerRefCount++;
812 MUTEX_EXIT(&rx_stats_mutex);
815 MUTEX_EXIT(&rx_peerHashTable_lock);
817 MUTEX_ENTER(&rx_stats_mutex);
818 if (conn->type == RX_SERVER_CONNECTION)
819 rx_stats.nServerConns--;
821 rx_stats.nClientConns--;
822 MUTEX_EXIT(&rx_stats_mutex);
825 if (conn->specific) {
827 for (i = 0; i < conn->nSpecific; i++) {
828 if (conn->specific[i] && rxi_keyCreate_destructor[i])
829 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
830 conn->specific[i] = NULL;
832 free(conn->specific);
834 conn->specific = NULL;
838 MUTEX_DESTROY(&conn->conn_call_lock);
839 MUTEX_DESTROY(&conn->conn_data_lock);
840 CV_DESTROY(&conn->conn_call_cv);
842 rxi_FreeConnection(conn);
845 /* Destroy the specified connection */
847 rxi_DestroyConnection(register struct rx_connection *conn)
849 MUTEX_ENTER(&rx_connHashTable_lock);
850 rxi_DestroyConnectionNoLock(conn);
851 /* conn should be at the head of the cleanup list */
852 if (conn == rx_connCleanup_list) {
853 rx_connCleanup_list = rx_connCleanup_list->next;
854 MUTEX_EXIT(&rx_connHashTable_lock);
855 rxi_CleanupConnection(conn);
857 #ifdef RX_ENABLE_LOCKS
859 MUTEX_EXIT(&rx_connHashTable_lock);
861 #endif /* RX_ENABLE_LOCKS */
865 rxi_DestroyConnectionNoLock(register struct rx_connection *conn)
867 register struct rx_connection **conn_ptr;
868 register int havecalls = 0;
869 struct rx_packet *packet;
876 MUTEX_ENTER(&conn->conn_data_lock);
877 if (conn->refCount > 0)
880 MUTEX_ENTER(&rx_stats_mutex);
881 rxi_lowConnRefCount++;
882 MUTEX_EXIT(&rx_stats_mutex);
885 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
886 /* Busy; wait till the last guy before proceeding */
887 MUTEX_EXIT(&conn->conn_data_lock);
892 /* If the client previously called rx_NewCall, but it is still
893 * waiting, treat this as a running call, and wait to destroy the
894 * connection later when the call completes. */
895 if ((conn->type == RX_CLIENT_CONNECTION)
896 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
897 conn->flags |= RX_CONN_DESTROY_ME;
898 MUTEX_EXIT(&conn->conn_data_lock);
902 MUTEX_EXIT(&conn->conn_data_lock);
904 /* Check for extant references to this connection */
905 for (i = 0; i < RX_MAXCALLS; i++) {
906 register struct rx_call *call = conn->call[i];
909 if (conn->type == RX_CLIENT_CONNECTION) {
910 MUTEX_ENTER(&call->lock);
911 if (call->delayedAckEvent) {
912 /* Push the final acknowledgment out now--there
913 * won't be a subsequent call to acknowledge the
914 * last reply packets */
915 rxevent_Cancel(call->delayedAckEvent, call,
916 RX_CALL_REFCOUNT_DELAY);
917 if (call->state == RX_STATE_PRECALL
918 || call->state == RX_STATE_ACTIVE) {
919 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
921 rxi_AckAll(NULL, call, 0);
924 MUTEX_EXIT(&call->lock);
928 #ifdef RX_ENABLE_LOCKS
930 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
931 MUTEX_EXIT(&conn->conn_data_lock);
933 /* Someone is accessing a packet right now. */
937 #endif /* RX_ENABLE_LOCKS */
940 /* Don't destroy the connection if there are any call
941 * structures still in use */
942 MUTEX_ENTER(&conn->conn_data_lock);
943 conn->flags |= RX_CONN_DESTROY_ME;
944 MUTEX_EXIT(&conn->conn_data_lock);
949 if (conn->delayedAbortEvent) {
950 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
951 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
953 MUTEX_ENTER(&conn->conn_data_lock);
954 rxi_SendConnectionAbort(conn, packet, 0, 1);
955 MUTEX_EXIT(&conn->conn_data_lock);
956 rxi_FreePacket(packet);
960 /* Remove from connection hash table before proceeding */
962 &rx_connHashTable[CONN_HASH
963 (peer->host, peer->port, conn->cid, conn->epoch,
965 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
966 if (*conn_ptr == conn) {
967 *conn_ptr = conn->next;
971 /* if the conn that we are destroying was the last connection, then we
972 * clear rxLastConn as well */
973 if (rxLastConn == conn)
976 /* Make sure the connection is completely reset before deleting it. */
977 /* get rid of pending events that could zap us later */
978 if (conn->challengeEvent)
979 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
980 if (conn->checkReachEvent)
981 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
983 /* Add the connection to the list of destroyed connections that
984 * need to be cleaned up. This is necessary to avoid deadlocks
985 * in the routines we call to inform others that this connection is
986 * being destroyed. */
987 conn->next = rx_connCleanup_list;
988 rx_connCleanup_list = conn;
991 /* Externally available version */
993 rx_DestroyConnection(register struct rx_connection *conn)
999 rxi_DestroyConnection(conn);
1004 /* Start a new rx remote procedure call, on the specified connection.
1005 * If wait is set to 1, wait for a free call channel; otherwise return
1006 * 0. Maxtime gives the maximum number of seconds this call may take,
1007 * after rx_MakeCall returns. After this time interval, a call to any
1008 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1009 * For fine grain locking, we hold the conn_call_lock in order to
1010 * to ensure that we don't get signalle after we found a call in an active
1011 * state and before we go to sleep.
1014 rx_NewCall(register struct rx_connection *conn)
1017 register struct rx_call *call;
1018 struct clock queueTime;
1022 dpf(("rx_MakeCall(conn %x)\n", conn));
1025 clock_GetTime(&queueTime);
1027 MUTEX_ENTER(&conn->conn_call_lock);
1030 * Check if there are others waiting for a new call.
1031 * If so, let them go first to avoid starving them.
1032 * This is a fairly simple scheme, and might not be
1033 * a complete solution for large numbers of waiters.
1035 if (conn->makeCallWaiters) {
1036 #ifdef RX_ENABLE_LOCKS
1037 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1044 for (i = 0; i < RX_MAXCALLS; i++) {
1045 call = conn->call[i];
1047 MUTEX_ENTER(&call->lock);
1048 if (call->state == RX_STATE_DALLY) {
1049 rxi_ResetCall(call, 0);
1050 (*call->callNumber)++;
1053 MUTEX_EXIT(&call->lock);
1055 call = rxi_NewCall(conn, i);
1059 if (i < RX_MAXCALLS) {
1062 MUTEX_ENTER(&conn->conn_data_lock);
1063 conn->flags |= RX_CONN_MAKECALL_WAITING;
1064 MUTEX_EXIT(&conn->conn_data_lock);
1066 conn->makeCallWaiters++;
1067 #ifdef RX_ENABLE_LOCKS
1068 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1072 conn->makeCallWaiters--;
1075 * Wake up anyone else who might be giving us a chance to
1076 * run (see code above that avoids resource starvation).
1078 #ifdef RX_ENABLE_LOCKS
1079 CV_BROADCAST(&conn->conn_call_cv);
1084 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1086 /* Client is initially in send mode */
1087 call->state = RX_STATE_ACTIVE;
1088 call->mode = RX_MODE_SENDING;
1090 /* remember start time for call in case we have hard dead time limit */
1091 call->queueTime = queueTime;
1092 clock_GetTime(&call->startTime);
1093 hzero(call->bytesSent);
1094 hzero(call->bytesRcvd);
1096 /* Turn on busy protocol. */
1097 rxi_KeepAliveOn(call);
1099 MUTEX_EXIT(&call->lock);
1100 MUTEX_EXIT(&conn->conn_call_lock);
1104 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1105 /* Now, if TQ wasn't cleared earlier, do it now. */
1107 MUTEX_ENTER(&call->lock);
1108 while (call->flags & RX_CALL_TQ_BUSY) {
1109 call->flags |= RX_CALL_TQ_WAIT;
1110 #ifdef RX_ENABLE_LOCKS
1111 CV_WAIT(&call->cv_tq, &call->lock);
1112 #else /* RX_ENABLE_LOCKS */
1113 osi_rxSleep(&call->tq);
1114 #endif /* RX_ENABLE_LOCKS */
1116 if (call->flags & RX_CALL_TQ_CLEARME) {
1117 rxi_ClearTransmitQueue(call, 0);
1118 queue_Init(&call->tq);
1120 MUTEX_EXIT(&call->lock);
1122 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1128 rxi_HasActiveCalls(register struct rx_connection *aconn)
1131 register struct rx_call *tcall;
1135 for (i = 0; i < RX_MAXCALLS; i++) {
1136 if ((tcall = aconn->call[i])) {
1137 if ((tcall->state == RX_STATE_ACTIVE)
1138 || (tcall->state == RX_STATE_PRECALL)) {
1149 rxi_GetCallNumberVector(register struct rx_connection *aconn,
1150 register afs_int32 * aint32s)
1153 register struct rx_call *tcall;
1157 for (i = 0; i < RX_MAXCALLS; i++) {
1158 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1159 aint32s[i] = aconn->callNumber[i] + 1;
1161 aint32s[i] = aconn->callNumber[i];
1168 rxi_SetCallNumberVector(register struct rx_connection *aconn,
1169 register afs_int32 * aint32s)
1172 register struct rx_call *tcall;
1176 for (i = 0; i < RX_MAXCALLS; i++) {
1177 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1178 aconn->callNumber[i] = aint32s[i] - 1;
1180 aconn->callNumber[i] = aint32s[i];
1186 /* Advertise a new service. A service is named locally by a UDP port
1187 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1190 char *serviceName; Name for identification purposes (e.g. the
1191 service name might be used for probing for
1194 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1195 struct rx_securityClass **securityObjects, int nSecurityObjects,
1196 afs_int32(*serviceProc) (struct rx_call * acall))
1198 osi_socket socket = OSI_NULLSOCKET;
1199 register struct rx_service *tservice;
1205 if (serviceId == 0) {
1207 "rx_NewService: service id for service %s is not non-zero.\n",
1214 "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",
1222 tservice = rxi_AllocService();
1225 for (i = 0; i < RX_MAX_SERVICES; i++) {
1226 register struct rx_service *service = rx_services[i];
1228 if (port == service->servicePort) {
1229 if (service->serviceId == serviceId) {
1230 /* The identical service has already been
1231 * installed; if the caller was intending to
1232 * change the security classes used by this
1233 * service, he/she loses. */
1235 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1236 serviceName, serviceId, service->serviceName);
1239 rxi_FreeService(tservice);
1242 /* Different service, same port: re-use the socket
1243 * which is bound to the same port */
1244 socket = service->socket;
1247 if (socket == OSI_NULLSOCKET) {
1248 /* If we don't already have a socket (from another
1249 * service on same port) get a new one */
1250 socket = rxi_GetUDPSocket(port);
1251 if (socket == OSI_NULLSOCKET) {
1254 rxi_FreeService(tservice);
1259 service->socket = socket;
1260 service->servicePort = port;
1261 service->serviceId = serviceId;
1262 service->serviceName = serviceName;
1263 service->nSecurityObjects = nSecurityObjects;
1264 service->securityObjects = securityObjects;
1265 service->minProcs = 0;
1266 service->maxProcs = 1;
1267 service->idleDeadTime = 60;
1268 service->connDeadTime = rx_connDeadTime;
1269 service->executeRequestProc = serviceProc;
1270 service->checkReach = 0;
1271 rx_services[i] = service; /* not visible until now */
1279 rxi_FreeService(tservice);
1280 (osi_Msg "rx_NewService: cannot support > %d services\n",
1285 /* Generic request processing loop. This routine should be called
1286 * by the implementation dependent rx_ServerProc. If socketp is
1287 * non-null, it will be set to the file descriptor that this thread
1288 * is now listening on. If socketp is null, this routine will never
1291 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1293 register struct rx_call *call;
1294 register afs_int32 code;
1295 register struct rx_service *tservice = NULL;
1302 call = rx_GetCall(threadID, tservice, socketp);
1303 if (socketp && *socketp != OSI_NULLSOCKET) {
1304 /* We are now a listener thread */
1309 /* if server is restarting( typically smooth shutdown) then do not
1310 * allow any new calls.
1313 if (rx_tranquil && (call != NULL)) {
1318 MUTEX_ENTER(&call->lock);
1320 rxi_CallError(call, RX_RESTARTING);
1321 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1323 MUTEX_EXIT(&call->lock);
1328 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1329 #ifdef RX_ENABLE_LOCKS
1331 #endif /* RX_ENABLE_LOCKS */
1332 afs_termState = AFSOP_STOP_AFS;
1333 afs_osi_Wakeup(&afs_termState);
1334 #ifdef RX_ENABLE_LOCKS
1336 #endif /* RX_ENABLE_LOCKS */
1341 tservice = call->conn->service;
1343 if (tservice->beforeProc)
1344 (*tservice->beforeProc) (call);
1346 code = call->conn->service->executeRequestProc(call);
1348 if (tservice->afterProc)
1349 (*tservice->afterProc) (call, code);
1351 rx_EndCall(call, code);
1352 MUTEX_ENTER(&rx_stats_mutex);
1354 MUTEX_EXIT(&rx_stats_mutex);
1360 rx_WakeupServerProcs(void)
1362 struct rx_serverQueueEntry *np, *tqp;
1367 MUTEX_ENTER(&rx_serverPool_lock);
1369 #ifdef RX_ENABLE_LOCKS
1370 if (rx_waitForPacket)
1371 CV_BROADCAST(&rx_waitForPacket->cv);
1372 #else /* RX_ENABLE_LOCKS */
1373 if (rx_waitForPacket)
1374 osi_rxWakeup(rx_waitForPacket);
1375 #endif /* RX_ENABLE_LOCKS */
1376 MUTEX_ENTER(&freeSQEList_lock);
1377 for (np = rx_FreeSQEList; np; np = tqp) {
1378 tqp = *(struct rx_serverQueueEntry **)np;
1379 #ifdef RX_ENABLE_LOCKS
1380 CV_BROADCAST(&np->cv);
1381 #else /* RX_ENABLE_LOCKS */
1383 #endif /* RX_ENABLE_LOCKS */
1385 MUTEX_EXIT(&freeSQEList_lock);
1386 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1387 #ifdef RX_ENABLE_LOCKS
1388 CV_BROADCAST(&np->cv);
1389 #else /* RX_ENABLE_LOCKS */
1391 #endif /* RX_ENABLE_LOCKS */
1393 MUTEX_EXIT(&rx_serverPool_lock);
1399 * One thing that seems to happen is that all the server threads get
1400 * tied up on some empty or slow call, and then a whole bunch of calls
1401 * arrive at once, using up the packet pool, so now there are more
1402 * empty calls. The most critical resources here are server threads
1403 * and the free packet pool. The "doreclaim" code seems to help in
1404 * general. I think that eventually we arrive in this state: there
1405 * are lots of pending calls which do have all their packets present,
1406 * so they won't be reclaimed, are multi-packet calls, so they won't
1407 * be scheduled until later, and thus are tying up most of the free
1408 * packet pool for a very long time.
1410 * 1. schedule multi-packet calls if all the packets are present.
1411 * Probably CPU-bound operation, useful to return packets to pool.
1412 * Do what if there is a full window, but the last packet isn't here?
1413 * 3. preserve one thread which *only* runs "best" calls, otherwise
1414 * it sleeps and waits for that type of call.
1415 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1416 * the current dataquota business is badly broken. The quota isn't adjusted
1417 * to reflect how many packets are presently queued for a running call.
1418 * So, when we schedule a queued call with a full window of packets queued
1419 * up for it, that *should* free up a window full of packets for other 2d-class
1420 * calls to be able to use from the packet pool. But it doesn't.
1422 * NB. Most of the time, this code doesn't run -- since idle server threads
1423 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1424 * as a new call arrives.
1426 /* Sleep until a call arrives. Returns a pointer to the call, ready
1427 * for an rx_Read. */
1428 #ifdef RX_ENABLE_LOCKS
1430 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1432 struct rx_serverQueueEntry *sq;
1433 register struct rx_call *call = (struct rx_call *)0;
1434 struct rx_service *service = NULL;
1437 MUTEX_ENTER(&freeSQEList_lock);
1439 if ((sq = rx_FreeSQEList)) {
1440 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1441 MUTEX_EXIT(&freeSQEList_lock);
1442 } else { /* otherwise allocate a new one and return that */
1443 MUTEX_EXIT(&freeSQEList_lock);
1444 sq = (struct rx_serverQueueEntry *)
1445 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1446 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1447 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1450 MUTEX_ENTER(&rx_serverPool_lock);
1451 if (cur_service != NULL) {
1452 ReturnToServerPool(cur_service);
1455 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1456 register struct rx_call *tcall, *ncall, *choice2 = NULL;
1458 /* Scan for eligible incoming calls. A call is not eligible
1459 * if the maximum number of calls for its service type are
1460 * already executing */
1461 /* One thread will process calls FCFS (to prevent starvation),
1462 * while the other threads may run ahead looking for calls which
1463 * have all their input data available immediately. This helps
1464 * keep threads from blocking, waiting for data from the client. */
1465 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1466 service = tcall->conn->service;
1467 if (!QuotaOK(service)) {
1470 if (tno == rxi_fcfs_thread_num
1471 || !tcall->queue_item_header.next) {
1472 /* If we're the fcfs thread , then we'll just use
1473 * this call. If we haven't been able to find an optimal
1474 * choice, and we're at the end of the list, then use a
1475 * 2d choice if one has been identified. Otherwise... */
1476 call = (choice2 ? choice2 : tcall);
1477 service = call->conn->service;
1478 } else if (!queue_IsEmpty(&tcall->rq)) {
1479 struct rx_packet *rp;
1480 rp = queue_First(&tcall->rq, rx_packet);
1481 if (rp->header.seq == 1) {
1483 || (rp->header.flags & RX_LAST_PACKET)) {
1485 } else if (rxi_2dchoice && !choice2
1486 && !(tcall->flags & RX_CALL_CLEARED)
1487 && (tcall->rprev > rxi_HardAckRate)) {
1496 ReturnToServerPool(service);
1503 MUTEX_EXIT(&rx_serverPool_lock);
1504 MUTEX_ENTER(&call->lock);
1506 if (call->flags & RX_CALL_WAIT_PROC) {
1507 call->flags &= ~RX_CALL_WAIT_PROC;
1508 MUTEX_ENTER(&rx_stats_mutex);
1510 MUTEX_EXIT(&rx_stats_mutex);
1513 if (call->state != RX_STATE_PRECALL || call->error) {
1514 MUTEX_EXIT(&call->lock);
1515 MUTEX_ENTER(&rx_serverPool_lock);
1516 ReturnToServerPool(service);
1521 if (queue_IsEmpty(&call->rq)
1522 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1523 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1525 CLEAR_CALL_QUEUE_LOCK(call);
1528 /* If there are no eligible incoming calls, add this process
1529 * to the idle server queue, to wait for one */
1533 *socketp = OSI_NULLSOCKET;
1535 sq->socketp = socketp;
1536 queue_Append(&rx_idleServerQueue, sq);
1537 #ifndef AFS_AIX41_ENV
1538 rx_waitForPacket = sq;
1540 rx_waitingForPacket = sq;
1541 #endif /* AFS_AIX41_ENV */
1543 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1545 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1546 MUTEX_EXIT(&rx_serverPool_lock);
1547 return (struct rx_call *)0;
1550 } while (!(call = sq->newcall)
1551 && !(socketp && *socketp != OSI_NULLSOCKET));
1552 MUTEX_EXIT(&rx_serverPool_lock);
1554 MUTEX_ENTER(&call->lock);
1560 MUTEX_ENTER(&freeSQEList_lock);
1561 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1562 rx_FreeSQEList = sq;
1563 MUTEX_EXIT(&freeSQEList_lock);
1566 clock_GetTime(&call->startTime);
1567 call->state = RX_STATE_ACTIVE;
1568 call->mode = RX_MODE_RECEIVING;
1569 #ifdef RX_KERNEL_TRACE
1570 if (ICL_SETACTIVE(afs_iclSetp)) {
1571 int glockOwner = ISAFS_GLOCK();
1574 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1575 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1582 rxi_calltrace(RX_CALL_START, call);
1583 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1584 call->conn->service->servicePort, call->conn->service->serviceId,
1587 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1588 MUTEX_EXIT(&call->lock);
1590 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1595 #else /* RX_ENABLE_LOCKS */
1597 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1599 struct rx_serverQueueEntry *sq;
1600 register struct rx_call *call = (struct rx_call *)0, *choice2;
1601 struct rx_service *service = NULL;
1606 MUTEX_ENTER(&freeSQEList_lock);
1608 if ((sq = rx_FreeSQEList)) {
1609 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1610 MUTEX_EXIT(&freeSQEList_lock);
1611 } else { /* otherwise allocate a new one and return that */
1612 MUTEX_EXIT(&freeSQEList_lock);
1613 sq = (struct rx_serverQueueEntry *)
1614 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1615 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1616 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1618 MUTEX_ENTER(&sq->lock);
1620 if (cur_service != NULL) {
1621 cur_service->nRequestsRunning--;
1622 if (cur_service->nRequestsRunning < cur_service->minProcs)
1626 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1627 register struct rx_call *tcall, *ncall;
1628 /* Scan for eligible incoming calls. A call is not eligible
1629 * if the maximum number of calls for its service type are
1630 * already executing */
1631 /* One thread will process calls FCFS (to prevent starvation),
1632 * while the other threads may run ahead looking for calls which
1633 * have all their input data available immediately. This helps
1634 * keep threads from blocking, waiting for data from the client. */
1635 choice2 = (struct rx_call *)0;
1636 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1637 service = tcall->conn->service;
1638 if (QuotaOK(service)) {
1639 if (tno == rxi_fcfs_thread_num
1640 || !tcall->queue_item_header.next) {
1641 /* If we're the fcfs thread, then we'll just use
1642 * this call. If we haven't been able to find an optimal
1643 * choice, and we're at the end of the list, then use a
1644 * 2d choice if one has been identified. Otherwise... */
1645 call = (choice2 ? choice2 : tcall);
1646 service = call->conn->service;
1647 } else if (!queue_IsEmpty(&tcall->rq)) {
1648 struct rx_packet *rp;
1649 rp = queue_First(&tcall->rq, rx_packet);
1650 if (rp->header.seq == 1
1652 || (rp->header.flags & RX_LAST_PACKET))) {
1654 } else if (rxi_2dchoice && !choice2
1655 && !(tcall->flags & RX_CALL_CLEARED)
1656 && (tcall->rprev > rxi_HardAckRate)) {
1669 /* we can't schedule a call if there's no data!!! */
1670 /* send an ack if there's no data, if we're missing the
1671 * first packet, or we're missing something between first
1672 * and last -- there's a "hole" in the incoming data. */
1673 if (queue_IsEmpty(&call->rq)
1674 || queue_First(&call->rq, rx_packet)->header.seq != 1
1675 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1676 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1678 call->flags &= (~RX_CALL_WAIT_PROC);
1679 service->nRequestsRunning++;
1680 /* just started call in minProcs pool, need fewer to maintain
1682 if (service->nRequestsRunning <= service->minProcs)
1686 /* MUTEX_EXIT(&call->lock); */
1688 /* If there are no eligible incoming calls, add this process
1689 * to the idle server queue, to wait for one */
1692 *socketp = OSI_NULLSOCKET;
1694 sq->socketp = socketp;
1695 queue_Append(&rx_idleServerQueue, sq);
1699 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1702 return (struct rx_call *)0;
1705 } while (!(call = sq->newcall)
1706 && !(socketp && *socketp != OSI_NULLSOCKET));
1708 MUTEX_EXIT(&sq->lock);
1710 MUTEX_ENTER(&freeSQEList_lock);
1711 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1712 rx_FreeSQEList = sq;
1713 MUTEX_EXIT(&freeSQEList_lock);
1716 clock_GetTime(&call->startTime);
1717 call->state = RX_STATE_ACTIVE;
1718 call->mode = RX_MODE_RECEIVING;
1719 #ifdef RX_KERNEL_TRACE
1720 if (ICL_SETACTIVE(afs_iclSetp)) {
1721 int glockOwner = ISAFS_GLOCK();
1724 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1725 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1732 rxi_calltrace(RX_CALL_START, call);
1733 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1734 call->conn->service->servicePort, call->conn->service->serviceId,
1737 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1745 #endif /* RX_ENABLE_LOCKS */
1749 /* Establish a procedure to be called when a packet arrives for a
1750 * call. This routine will be called at most once after each call,
1751 * and will also be called if there is an error condition on the or
1752 * the call is complete. Used by multi rx to build a selection
1753 * function which determines which of several calls is likely to be a
1754 * good one to read from.
1755 * NOTE: the way this is currently implemented it is probably only a
1756 * good idea to (1) use it immediately after a newcall (clients only)
1757 * and (2) only use it once. Other uses currently void your warranty
1760 rx_SetArrivalProc(register struct rx_call *call,
1761 register VOID(*proc) (register struct rx_call * call,
1762 register struct multi_handle * mh,
1763 register int index),
1764 register VOID * handle, register VOID * arg)
1766 call->arrivalProc = proc;
1767 call->arrivalProcHandle = handle;
1768 call->arrivalProcArg = arg;
1771 /* Call is finished (possibly prematurely). Return rc to the peer, if
1772 * appropriate, and return the final error code from the conversation
1776 rx_EndCall(register struct rx_call *call, afs_int32 rc)
1778 register struct rx_connection *conn = call->conn;
1779 register struct rx_service *service;
1780 register struct rx_packet *tp; /* Temporary packet pointer */
1781 register struct rx_packet *nxp; /* Next packet pointer, for queue_Scan */
1785 dpf(("rx_EndCall(call %x)\n", call));
1789 MUTEX_ENTER(&call->lock);
1791 if (rc == 0 && call->error == 0) {
1792 call->abortCode = 0;
1793 call->abortCount = 0;
1796 call->arrivalProc = (VOID(*)())0;
1797 if (rc && call->error == 0) {
1798 rxi_CallError(call, rc);
1799 /* Send an abort message to the peer if this error code has
1800 * only just been set. If it was set previously, assume the
1801 * peer has already been sent the error code or will request it
1803 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1805 if (conn->type == RX_SERVER_CONNECTION) {
1806 /* Make sure reply or at least dummy reply is sent */
1807 if (call->mode == RX_MODE_RECEIVING) {
1808 rxi_WriteProc(call, 0, 0);
1810 if (call->mode == RX_MODE_SENDING) {
1811 rxi_FlushWrite(call);
1813 service = conn->service;
1814 rxi_calltrace(RX_CALL_END, call);
1815 /* Call goes to hold state until reply packets are acknowledged */
1816 if (call->tfirst + call->nSoftAcked < call->tnext) {
1817 call->state = RX_STATE_HOLD;
1819 call->state = RX_STATE_DALLY;
1820 rxi_ClearTransmitQueue(call, 0);
1821 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
1822 rxevent_Cancel(call->keepAliveEvent, call,
1823 RX_CALL_REFCOUNT_ALIVE);
1825 } else { /* Client connection */
1827 /* Make sure server receives input packets, in the case where
1828 * no reply arguments are expected */
1829 if ((call->mode == RX_MODE_SENDING)
1830 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
1831 (void)rxi_ReadProc(call, &dummy, 1);
1834 /* If we had an outstanding delayed ack, be nice to the server
1835 * and force-send it now.
1837 if (call->delayedAckEvent) {
1838 rxevent_Cancel(call->delayedAckEvent, call,
1839 RX_CALL_REFCOUNT_DELAY);
1840 call->delayedAckEvent = NULL;
1841 rxi_SendDelayedAck(NULL, call, NULL);
1844 /* We need to release the call lock since it's lower than the
1845 * conn_call_lock and we don't want to hold the conn_call_lock
1846 * over the rx_ReadProc call. The conn_call_lock needs to be held
1847 * here for the case where rx_NewCall is perusing the calls on
1848 * the connection structure. We don't want to signal until
1849 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
1850 * have checked this call, found it active and by the time it
1851 * goes to sleep, will have missed the signal.
1853 MUTEX_EXIT(&call->lock);
1854 MUTEX_ENTER(&conn->conn_call_lock);
1855 MUTEX_ENTER(&call->lock);
1856 MUTEX_ENTER(&conn->conn_data_lock);
1857 conn->flags |= RX_CONN_BUSY;
1858 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
1859 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
1860 MUTEX_EXIT(&conn->conn_data_lock);
1861 #ifdef RX_ENABLE_LOCKS
1862 CV_BROADCAST(&conn->conn_call_cv);
1867 #ifdef RX_ENABLE_LOCKS
1869 MUTEX_EXIT(&conn->conn_data_lock);
1871 #endif /* RX_ENABLE_LOCKS */
1872 call->state = RX_STATE_DALLY;
1874 error = call->error;
1876 /* currentPacket, nLeft, and NFree must be zeroed here, because
1877 * ResetCall cannot: ResetCall may be called at splnet(), in the
1878 * kernel version, and may interrupt the macros rx_Read or
1879 * rx_Write, which run at normal priority for efficiency. */
1880 if (call->currentPacket) {
1881 rxi_FreePacket(call->currentPacket);
1882 call->currentPacket = (struct rx_packet *)0;
1883 call->nLeft = call->nFree = call->curlen = 0;
1885 call->nLeft = call->nFree = call->curlen = 0;
1887 /* Free any packets from the last call to ReadvProc/WritevProc */
1888 for (queue_Scan(&call->iovq, tp, nxp, rx_packet)) {
1893 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1894 MUTEX_EXIT(&call->lock);
1895 if (conn->type == RX_CLIENT_CONNECTION) {
1896 MUTEX_EXIT(&conn->conn_call_lock);
1897 conn->flags &= ~RX_CONN_BUSY;
1902 * Map errors to the local host's errno.h format.
1904 error = ntoh_syserr_conv(error);
1908 #if !defined(KERNEL)
1910 /* Call this routine when shutting down a server or client (especially
1911 * clients). This will allow Rx to gracefully garbage collect server
1912 * connections, and reduce the number of retries that a server might
1913 * make to a dead client.
1914 * This is not quite right, since some calls may still be ongoing and
1915 * we can't lock them to destroy them. */
1919 register struct rx_connection **conn_ptr, **conn_end;
1921 INIT_PTHREAD_LOCKS LOCK_RX_INIT if (rxinit_status == 1) {
1922 UNLOCK_RX_INIT return; /* Already shutdown. */
1924 rxi_DeleteCachedConnections();
1925 if (rx_connHashTable) {
1926 MUTEX_ENTER(&rx_connHashTable_lock);
1927 for (conn_ptr = &rx_connHashTable[0], conn_end =
1928 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
1930 struct rx_connection *conn, *next;
1931 for (conn = *conn_ptr; conn; conn = next) {
1933 if (conn->type == RX_CLIENT_CONNECTION) {
1934 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
1936 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
1937 #ifdef RX_ENABLE_LOCKS
1938 rxi_DestroyConnectionNoLock(conn);
1939 #else /* RX_ENABLE_LOCKS */
1940 rxi_DestroyConnection(conn);
1941 #endif /* RX_ENABLE_LOCKS */
1945 #ifdef RX_ENABLE_LOCKS
1946 while (rx_connCleanup_list) {
1947 struct rx_connection *conn;
1948 conn = rx_connCleanup_list;
1949 rx_connCleanup_list = rx_connCleanup_list->next;
1950 MUTEX_EXIT(&rx_connHashTable_lock);
1951 rxi_CleanupConnection(conn);
1952 MUTEX_ENTER(&rx_connHashTable_lock);
1954 MUTEX_EXIT(&rx_connHashTable_lock);
1955 #endif /* RX_ENABLE_LOCKS */
1963 /* if we wakeup packet waiter too often, can get in loop with two
1964 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
1966 rxi_PacketsUnWait(void)
1968 if (!rx_waitingForPackets) {
1972 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
1973 return; /* still over quota */
1976 rx_waitingForPackets = 0;
1977 #ifdef RX_ENABLE_LOCKS
1978 CV_BROADCAST(&rx_waitingForPackets_cv);
1980 osi_rxWakeup(&rx_waitingForPackets);
1986 /* ------------------Internal interfaces------------------------- */
1988 /* Return this process's service structure for the
1989 * specified socket and service */
1991 rxi_FindService(register osi_socket socket, register u_short serviceId)
1993 register struct rx_service **sp;
1994 for (sp = &rx_services[0]; *sp; sp++) {
1995 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2001 /* Allocate a call structure, for the indicated channel of the
2002 * supplied connection. The mode and state of the call must be set by
2003 * the caller. Returns the call with mutex locked. */
2005 rxi_NewCall(register struct rx_connection *conn, register int channel)
2007 register struct rx_call *call;
2008 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2009 register struct rx_call *cp; /* Call pointer temp */
2010 register struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2011 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2013 /* Grab an existing call structure, or allocate a new one.
2014 * Existing call structures are assumed to have been left reset by
2016 MUTEX_ENTER(&rx_freeCallQueue_lock);
2018 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2020 * EXCEPT that the TQ might not yet be cleared out.
2021 * Skip over those with in-use TQs.
2024 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2025 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2031 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2032 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2033 call = queue_First(&rx_freeCallQueue, rx_call);
2034 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2036 MUTEX_ENTER(&rx_stats_mutex);
2037 rx_stats.nFreeCallStructs--;
2038 MUTEX_EXIT(&rx_stats_mutex);
2039 MUTEX_EXIT(&rx_freeCallQueue_lock);
2040 MUTEX_ENTER(&call->lock);
2041 CLEAR_CALL_QUEUE_LOCK(call);
2042 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2043 /* Now, if TQ wasn't cleared earlier, do it now. */
2044 if (call->flags & RX_CALL_TQ_CLEARME) {
2045 rxi_ClearTransmitQueue(call, 0);
2046 queue_Init(&call->tq);
2048 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2049 /* Bind the call to its connection structure */
2051 rxi_ResetCall(call, 1);
2053 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2055 MUTEX_EXIT(&rx_freeCallQueue_lock);
2056 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2057 MUTEX_ENTER(&call->lock);
2058 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2059 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2060 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2062 MUTEX_ENTER(&rx_stats_mutex);
2063 rx_stats.nCallStructs++;
2064 MUTEX_EXIT(&rx_stats_mutex);
2065 /* Initialize once-only items */
2066 queue_Init(&call->tq);
2067 queue_Init(&call->rq);
2068 queue_Init(&call->iovq);
2069 /* Bind the call to its connection structure (prereq for reset) */
2071 rxi_ResetCall(call, 1);
2073 call->channel = channel;
2074 call->callNumber = &conn->callNumber[channel];
2075 /* Note that the next expected call number is retained (in
2076 * conn->callNumber[i]), even if we reallocate the call structure
2078 conn->call[channel] = call;
2079 /* if the channel's never been used (== 0), we should start at 1, otherwise
2080 * the call number is valid from the last time this channel was used */
2081 if (*call->callNumber == 0)
2082 *call->callNumber = 1;
2087 /* A call has been inactive long enough that so we can throw away
2088 * state, including the call structure, which is placed on the call
2090 * Call is locked upon entry.
2091 * haveCTLock set if called from rxi_ReapConnections
2093 #ifdef RX_ENABLE_LOCKS
2095 rxi_FreeCall(register struct rx_call *call, int haveCTLock)
2096 #else /* RX_ENABLE_LOCKS */
2098 rxi_FreeCall(register struct rx_call *call)
2099 #endif /* RX_ENABLE_LOCKS */
2101 register int channel = call->channel;
2102 register struct rx_connection *conn = call->conn;
2105 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2106 (*call->callNumber)++;
2107 rxi_ResetCall(call, 0);
2108 call->conn->call[channel] = (struct rx_call *)0;
2110 MUTEX_ENTER(&rx_freeCallQueue_lock);
2111 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2112 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2113 /* A call may be free even though its transmit queue is still in use.
2114 * Since we search the call list from head to tail, put busy calls at
2115 * the head of the list, and idle calls at the tail.
2117 if (call->flags & RX_CALL_TQ_BUSY)
2118 queue_Prepend(&rx_freeCallQueue, call);
2120 queue_Append(&rx_freeCallQueue, call);
2121 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2122 queue_Append(&rx_freeCallQueue, call);
2123 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2124 MUTEX_ENTER(&rx_stats_mutex);
2125 rx_stats.nFreeCallStructs++;
2126 MUTEX_EXIT(&rx_stats_mutex);
2128 MUTEX_EXIT(&rx_freeCallQueue_lock);
2130 /* Destroy the connection if it was previously slated for
2131 * destruction, i.e. the Rx client code previously called
2132 * rx_DestroyConnection (client connections), or
2133 * rxi_ReapConnections called the same routine (server
2134 * connections). Only do this, however, if there are no
2135 * outstanding calls. Note that for fine grain locking, there appears
2136 * to be a deadlock in that rxi_FreeCall has a call locked and
2137 * DestroyConnectionNoLock locks each call in the conn. But note a
2138 * few lines up where we have removed this call from the conn.
2139 * If someone else destroys a connection, they either have no
2140 * call lock held or are going through this section of code.
2142 if (conn->flags & RX_CONN_DESTROY_ME) {
2143 MUTEX_ENTER(&conn->conn_data_lock);
2145 MUTEX_EXIT(&conn->conn_data_lock);
2146 #ifdef RX_ENABLE_LOCKS
2148 rxi_DestroyConnectionNoLock(conn);
2150 rxi_DestroyConnection(conn);
2151 #else /* RX_ENABLE_LOCKS */
2152 rxi_DestroyConnection(conn);
2153 #endif /* RX_ENABLE_LOCKS */
2157 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2159 rxi_Alloc(register size_t size)
2163 #if defined(AFS_AIX41_ENV) && defined(KERNEL)
2164 /* Grab the AFS filesystem lock. See afs/osi.h for the lock
2167 int glockOwner = ISAFS_GLOCK();
2171 MUTEX_ENTER(&rx_stats_mutex);
2173 rxi_Allocsize += size;
2174 MUTEX_EXIT(&rx_stats_mutex);
2175 #if (defined(AFS_AIX32_ENV) || defined(AFS_HPUX_ENV)) && !defined(AFS_HPUX100_ENV) && defined(KERNEL)
2176 if (size > AFS_SMALLOCSIZ) {
2177 p = (char *)osi_AllocMediumSpace(size);
2179 p = (char *)osi_AllocSmall(size, 1);
2180 #if defined(AFS_AIX41_ENV) && defined(KERNEL)
2185 p = (char *)osi_Alloc(size);
2188 osi_Panic("rxi_Alloc error");
2194 rxi_Free(void *addr, register size_t size)
2196 #if defined(AFS_AIX41_ENV) && defined(KERNEL)
2197 /* Grab the AFS filesystem lock. See afs/osi.h for the lock
2200 int glockOwner = ISAFS_GLOCK();
2204 MUTEX_ENTER(&rx_stats_mutex);
2206 rxi_Allocsize -= size;
2207 MUTEX_EXIT(&rx_stats_mutex);
2208 #if (defined(AFS_AIX32_ENV) || defined(AFS_HPUX_ENV)) && !defined(AFS_HPUX100_ENV) && defined(KERNEL)
2209 if (size > AFS_SMALLOCSIZ)
2210 osi_FreeMediumSpace(addr);
2212 osi_FreeSmall(addr);
2213 #if defined(AFS_AIX41_ENV) && defined(KERNEL)
2218 osi_Free(addr, size);
2222 /* Find the peer process represented by the supplied (host,port)
2223 * combination. If there is no appropriate active peer structure, a
2224 * new one will be allocated and initialized
2225 * The origPeer, if set, is a pointer to a peer structure on which the
2226 * refcount will be be decremented. This is used to replace the peer
2227 * structure hanging off a connection structure */
2229 rxi_FindPeer(register afs_uint32 host, register u_short port,
2230 struct rx_peer *origPeer, int create)
2232 register struct rx_peer *pp;
2234 hashIndex = PEER_HASH(host, port);
2235 MUTEX_ENTER(&rx_peerHashTable_lock);
2236 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2237 if ((pp->host == host) && (pp->port == port))
2242 pp = rxi_AllocPeer(); /* This bzero's *pp */
2243 pp->host = host; /* set here or in InitPeerParams is zero */
2245 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2246 queue_Init(&pp->congestionQueue);
2247 queue_Init(&pp->rpcStats);
2248 pp->next = rx_peerHashTable[hashIndex];
2249 rx_peerHashTable[hashIndex] = pp;
2250 rxi_InitPeerParams(pp);
2251 MUTEX_ENTER(&rx_stats_mutex);
2252 rx_stats.nPeerStructs++;
2253 MUTEX_EXIT(&rx_stats_mutex);
2260 origPeer->refCount--;
2261 MUTEX_EXIT(&rx_peerHashTable_lock);
2266 /* Find the connection at (host, port) started at epoch, and with the
2267 * given connection id. Creates the server connection if necessary.
2268 * The type specifies whether a client connection or a server
2269 * connection is desired. In both cases, (host, port) specify the
2270 * peer's (host, pair) pair. Client connections are not made
2271 * automatically by this routine. The parameter socket gives the
2272 * socket descriptor on which the packet was received. This is used,
2273 * in the case of server connections, to check that *new* connections
2274 * come via a valid (port, serviceId). Finally, the securityIndex
2275 * parameter must match the existing index for the connection. If a
2276 * server connection is created, it will be created using the supplied
2277 * index, if the index is valid for this service */
2278 struct rx_connection *
2279 rxi_FindConnection(osi_socket socket, register afs_int32 host,
2280 register u_short port, u_short serviceId, afs_uint32 cid,
2281 afs_uint32 epoch, int type, u_int securityIndex)
2283 int hashindex, flag;
2284 register struct rx_connection *conn;
2285 hashindex = CONN_HASH(host, port, cid, epoch, type);
2286 MUTEX_ENTER(&rx_connHashTable_lock);
2287 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2288 rx_connHashTable[hashindex],
2291 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2292 && (epoch == conn->epoch)) {
2293 register struct rx_peer *pp = conn->peer;
2294 if (securityIndex != conn->securityIndex) {
2295 /* this isn't supposed to happen, but someone could forge a packet
2296 * like this, and there seems to be some CM bug that makes this
2297 * happen from time to time -- in which case, the fileserver
2299 MUTEX_EXIT(&rx_connHashTable_lock);
2300 return (struct rx_connection *)0;
2302 if (pp->host == host && pp->port == port)
2304 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2306 if (type == RX_CLIENT_CONNECTION && (conn->epoch & 0x80000000))
2310 /* the connection rxLastConn that was used the last time is not the
2311 ** one we are looking for now. Hence, start searching in the hash */
2313 conn = rx_connHashTable[hashindex];
2318 struct rx_service *service;
2319 if (type == RX_CLIENT_CONNECTION) {
2320 MUTEX_EXIT(&rx_connHashTable_lock);
2321 return (struct rx_connection *)0;
2323 service = rxi_FindService(socket, serviceId);
2324 if (!service || (securityIndex >= service->nSecurityObjects)
2325 || (service->securityObjects[securityIndex] == 0)) {
2326 MUTEX_EXIT(&rx_connHashTable_lock);
2327 return (struct rx_connection *)0;
2329 conn = rxi_AllocConnection(); /* This bzero's the connection */
2330 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2331 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2332 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2333 conn->next = rx_connHashTable[hashindex];
2334 rx_connHashTable[hashindex] = conn;
2335 conn->peer = rxi_FindPeer(host, port, 0, 1);
2336 conn->type = RX_SERVER_CONNECTION;
2337 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2338 conn->epoch = epoch;
2339 conn->cid = cid & RX_CIDMASK;
2340 /* conn->serial = conn->lastSerial = 0; */
2341 /* conn->timeout = 0; */
2342 conn->ackRate = RX_FAST_ACK_RATE;
2343 conn->service = service;
2344 conn->serviceId = serviceId;
2345 conn->securityIndex = securityIndex;
2346 conn->securityObject = service->securityObjects[securityIndex];
2347 conn->nSpecific = 0;
2348 conn->specific = NULL;
2349 rx_SetConnDeadTime(conn, service->connDeadTime);
2350 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2351 /* Notify security object of the new connection */
2352 RXS_NewConnection(conn->securityObject, conn);
2353 /* XXXX Connection timeout? */
2354 if (service->newConnProc)
2355 (*service->newConnProc) (conn);
2356 MUTEX_ENTER(&rx_stats_mutex);
2357 rx_stats.nServerConns++;
2358 MUTEX_EXIT(&rx_stats_mutex);
2361 MUTEX_ENTER(&conn->conn_data_lock);
2363 MUTEX_EXIT(&conn->conn_data_lock);
2365 rxLastConn = conn; /* store this connection as the last conn used */
2366 MUTEX_EXIT(&rx_connHashTable_lock);
2370 /* There are two packet tracing routines available for testing and monitoring
2371 * Rx. One is called just after every packet is received and the other is
2372 * called just before every packet is sent. Received packets, have had their
2373 * headers decoded, and packets to be sent have not yet had their headers
2374 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2375 * containing the network address. Both can be modified. The return value, if
2376 * non-zero, indicates that the packet should be dropped. */
2378 int (*rx_justReceived) () = 0;
2379 int (*rx_almostSent) () = 0;
2381 /* A packet has been received off the interface. Np is the packet, socket is
2382 * the socket number it was received from (useful in determining which service
2383 * this packet corresponds to), and (host, port) reflect the host,port of the
2384 * sender. This call returns the packet to the caller if it is finished with
2385 * it, rather than de-allocating it, just as a small performance hack */
2388 rxi_ReceivePacket(register struct rx_packet *np, osi_socket socket,
2389 afs_uint32 host, u_short port, int *tnop,
2390 struct rx_call **newcallp)
2392 register struct rx_call *call;
2393 register struct rx_connection *conn;
2395 afs_uint32 currentCallNumber;
2401 struct rx_packet *tnp;
2404 /* We don't print out the packet until now because (1) the time may not be
2405 * accurate enough until now in the lwp implementation (rx_Listener only gets
2406 * the time after the packet is read) and (2) from a protocol point of view,
2407 * this is the first time the packet has been seen */
2408 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2409 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2410 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2411 np->header.serial, packetType, host, port, np->header.serviceId,
2412 np->header.epoch, np->header.cid, np->header.callNumber,
2413 np->header.seq, np->header.flags, np));
2416 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2417 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2420 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2421 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2424 /* If an input tracer function is defined, call it with the packet and
2425 * network address. Note this function may modify its arguments. */
2426 if (rx_justReceived) {
2427 struct sockaddr_in addr;
2429 addr.sin_family = AF_INET;
2430 addr.sin_port = port;
2431 addr.sin_addr.s_addr = host;
2432 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2433 addr.sin_len = sizeof(addr);
2434 #endif /* AFS_OSF_ENV */
2435 drop = (*rx_justReceived) (np, &addr);
2436 /* drop packet if return value is non-zero */
2439 port = addr.sin_port; /* in case fcn changed addr */
2440 host = addr.sin_addr.s_addr;
2444 /* If packet was not sent by the client, then *we* must be the client */
2445 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2446 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2448 /* Find the connection (or fabricate one, if we're the server & if
2449 * necessary) associated with this packet */
2451 rxi_FindConnection(socket, host, port, np->header.serviceId,
2452 np->header.cid, np->header.epoch, type,
2453 np->header.securityIndex);
2456 /* If no connection found or fabricated, just ignore the packet.
2457 * (An argument could be made for sending an abort packet for
2462 MUTEX_ENTER(&conn->conn_data_lock);
2463 if (conn->maxSerial < np->header.serial)
2464 conn->maxSerial = np->header.serial;
2465 MUTEX_EXIT(&conn->conn_data_lock);
2467 /* If the connection is in an error state, send an abort packet and ignore
2468 * the incoming packet */
2470 /* Don't respond to an abort packet--we don't want loops! */
2471 MUTEX_ENTER(&conn->conn_data_lock);
2472 if (np->header.type != RX_PACKET_TYPE_ABORT)
2473 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2475 MUTEX_EXIT(&conn->conn_data_lock);
2479 /* Check for connection-only requests (i.e. not call specific). */
2480 if (np->header.callNumber == 0) {
2481 switch (np->header.type) {
2482 case RX_PACKET_TYPE_ABORT:
2483 /* What if the supplied error is zero? */
2484 rxi_ConnectionError(conn, ntohl(rx_GetInt32(np, 0)));
2485 MUTEX_ENTER(&conn->conn_data_lock);
2487 MUTEX_EXIT(&conn->conn_data_lock);
2489 case RX_PACKET_TYPE_CHALLENGE:
2490 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2491 MUTEX_ENTER(&conn->conn_data_lock);
2493 MUTEX_EXIT(&conn->conn_data_lock);
2495 case RX_PACKET_TYPE_RESPONSE:
2496 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2497 MUTEX_ENTER(&conn->conn_data_lock);
2499 MUTEX_EXIT(&conn->conn_data_lock);
2501 case RX_PACKET_TYPE_PARAMS:
2502 case RX_PACKET_TYPE_PARAMS + 1:
2503 case RX_PACKET_TYPE_PARAMS + 2:
2504 /* ignore these packet types for now */
2505 MUTEX_ENTER(&conn->conn_data_lock);
2507 MUTEX_EXIT(&conn->conn_data_lock);
2512 /* Should not reach here, unless the peer is broken: send an
2514 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2515 MUTEX_ENTER(&conn->conn_data_lock);
2516 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2518 MUTEX_EXIT(&conn->conn_data_lock);
2523 channel = np->header.cid & RX_CHANNELMASK;
2524 call = conn->call[channel];
2525 #ifdef RX_ENABLE_LOCKS
2527 MUTEX_ENTER(&call->lock);
2528 /* Test to see if call struct is still attached to conn. */
2529 if (call != conn->call[channel]) {
2531 MUTEX_EXIT(&call->lock);
2532 if (type == RX_SERVER_CONNECTION) {
2533 call = conn->call[channel];
2534 /* If we started with no call attached and there is one now,
2535 * another thread is also running this routine and has gotten
2536 * the connection channel. We should drop this packet in the tests
2537 * below. If there was a call on this connection and it's now
2538 * gone, then we'll be making a new call below.
2539 * If there was previously a call and it's now different then
2540 * the old call was freed and another thread running this routine
2541 * has created a call on this channel. One of these two threads
2542 * has a packet for the old call and the code below handles those
2546 MUTEX_ENTER(&call->lock);
2548 /* This packet can't be for this call. If the new call address is
2549 * 0 then no call is running on this channel. If there is a call
2550 * then, since this is a client connection we're getting data for
2551 * it must be for the previous call.
2553 MUTEX_ENTER(&rx_stats_mutex);
2554 rx_stats.spuriousPacketsRead++;
2555 MUTEX_EXIT(&rx_stats_mutex);
2556 MUTEX_ENTER(&conn->conn_data_lock);
2558 MUTEX_EXIT(&conn->conn_data_lock);
2563 currentCallNumber = conn->callNumber[channel];
2565 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2566 if (np->header.callNumber < currentCallNumber) {
2567 MUTEX_ENTER(&rx_stats_mutex);
2568 rx_stats.spuriousPacketsRead++;
2569 MUTEX_EXIT(&rx_stats_mutex);
2570 #ifdef RX_ENABLE_LOCKS
2572 MUTEX_EXIT(&call->lock);
2574 MUTEX_ENTER(&conn->conn_data_lock);
2576 MUTEX_EXIT(&conn->conn_data_lock);
2580 MUTEX_ENTER(&conn->conn_call_lock);
2581 call = rxi_NewCall(conn, channel);
2582 MUTEX_EXIT(&conn->conn_call_lock);
2583 *call->callNumber = np->header.callNumber;
2584 call->state = RX_STATE_PRECALL;
2585 clock_GetTime(&call->queueTime);
2586 hzero(call->bytesSent);
2587 hzero(call->bytesRcvd);
2588 rxi_KeepAliveOn(call);
2589 } else if (np->header.callNumber != currentCallNumber) {
2590 /* Wait until the transmit queue is idle before deciding
2591 * whether to reset the current call. Chances are that the
2592 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2595 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2596 while ((call->state == RX_STATE_ACTIVE)
2597 && (call->flags & RX_CALL_TQ_BUSY)) {
2598 call->flags |= RX_CALL_TQ_WAIT;
2599 #ifdef RX_ENABLE_LOCKS
2600 CV_WAIT(&call->cv_tq, &call->lock);
2601 #else /* RX_ENABLE_LOCKS */
2602 osi_rxSleep(&call->tq);
2603 #endif /* RX_ENABLE_LOCKS */
2605 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2606 /* If the new call cannot be taken right now send a busy and set
2607 * the error condition in this call, so that it terminates as
2608 * quickly as possible */
2609 if (call->state == RX_STATE_ACTIVE) {
2610 struct rx_packet *tp;
2612 rxi_CallError(call, RX_CALL_DEAD);
2613 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2615 MUTEX_EXIT(&call->lock);
2616 MUTEX_ENTER(&conn->conn_data_lock);
2618 MUTEX_EXIT(&conn->conn_data_lock);
2621 rxi_ResetCall(call, 0);
2622 *call->callNumber = np->header.callNumber;
2623 call->state = RX_STATE_PRECALL;
2624 clock_GetTime(&call->queueTime);
2625 hzero(call->bytesSent);
2626 hzero(call->bytesRcvd);
2628 * If the number of queued calls exceeds the overload
2629 * threshold then abort this call.
2631 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2632 struct rx_packet *tp;
2634 rxi_CallError(call, rx_BusyError);
2635 tp = rxi_SendCallAbort(call, np, 1, 0);
2636 MUTEX_EXIT(&call->lock);
2637 MUTEX_ENTER(&conn->conn_data_lock);
2639 MUTEX_EXIT(&conn->conn_data_lock);
2642 rxi_KeepAliveOn(call);
2644 /* Continuing call; do nothing here. */
2646 } else { /* we're the client */
2647 /* Ignore all incoming acknowledgements for calls in DALLY state */
2648 if (call && (call->state == RX_STATE_DALLY)
2649 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2650 MUTEX_ENTER(&rx_stats_mutex);
2651 rx_stats.ignorePacketDally++;
2652 MUTEX_EXIT(&rx_stats_mutex);
2653 #ifdef RX_ENABLE_LOCKS
2655 MUTEX_EXIT(&call->lock);
2658 MUTEX_ENTER(&conn->conn_data_lock);
2660 MUTEX_EXIT(&conn->conn_data_lock);
2664 /* Ignore anything that's not relevant to the current call. If there
2665 * isn't a current call, then no packet is relevant. */
2666 if (!call || (np->header.callNumber != currentCallNumber)) {
2667 MUTEX_ENTER(&rx_stats_mutex);
2668 rx_stats.spuriousPacketsRead++;
2669 MUTEX_EXIT(&rx_stats_mutex);
2670 #ifdef RX_ENABLE_LOCKS
2672 MUTEX_EXIT(&call->lock);
2675 MUTEX_ENTER(&conn->conn_data_lock);
2677 MUTEX_EXIT(&conn->conn_data_lock);
2680 /* If the service security object index stamped in the packet does not
2681 * match the connection's security index, ignore the packet */
2682 if (np->header.securityIndex != conn->securityIndex) {
2683 #ifdef RX_ENABLE_LOCKS
2684 MUTEX_EXIT(&call->lock);
2686 MUTEX_ENTER(&conn->conn_data_lock);
2688 MUTEX_EXIT(&conn->conn_data_lock);
2692 /* If we're receiving the response, then all transmit packets are
2693 * implicitly acknowledged. Get rid of them. */
2694 if (np->header.type == RX_PACKET_TYPE_DATA) {
2695 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2696 /* XXX Hack. Because we must release the global rx lock when
2697 * sending packets (osi_NetSend) we drop all acks while we're
2698 * traversing the tq in rxi_Start sending packets out because
2699 * packets may move to the freePacketQueue as result of being here!
2700 * So we drop these packets until we're safely out of the
2701 * traversing. Really ugly!
2702 * For fine grain RX locking, we set the acked field in the
2703 * packets and let rxi_Start remove them from the transmit queue.
2705 if (call->flags & RX_CALL_TQ_BUSY) {
2706 #ifdef RX_ENABLE_LOCKS
2707 rxi_SetAcksInTransmitQueue(call);
2710 return np; /* xmitting; drop packet */
2713 rxi_ClearTransmitQueue(call, 0);
2715 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2716 rxi_ClearTransmitQueue(call, 0);
2717 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2719 if (np->header.type == RX_PACKET_TYPE_ACK) {
2720 /* now check to see if this is an ack packet acknowledging that the
2721 * server actually *lost* some hard-acked data. If this happens we
2722 * ignore this packet, as it may indicate that the server restarted in
2723 * the middle of a call. It is also possible that this is an old ack
2724 * packet. We don't abort the connection in this case, because this
2725 * *might* just be an old ack packet. The right way to detect a server
2726 * restart in the midst of a call is to notice that the server epoch
2728 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2729 * XXX unacknowledged. I think that this is off-by-one, but
2730 * XXX I don't dare change it just yet, since it will
2731 * XXX interact badly with the server-restart detection
2732 * XXX code in receiveackpacket. */
2733 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2734 MUTEX_ENTER(&rx_stats_mutex);
2735 rx_stats.spuriousPacketsRead++;
2736 MUTEX_EXIT(&rx_stats_mutex);
2737 MUTEX_EXIT(&call->lock);
2738 MUTEX_ENTER(&conn->conn_data_lock);
2740 MUTEX_EXIT(&conn->conn_data_lock);
2744 } /* else not a data packet */
2747 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2748 /* Set remote user defined status from packet */
2749 call->remoteStatus = np->header.userStatus;
2751 /* Note the gap between the expected next packet and the actual
2752 * packet that arrived, when the new packet has a smaller serial number
2753 * than expected. Rioses frequently reorder packets all by themselves,
2754 * so this will be quite important with very large window sizes.
2755 * Skew is checked against 0 here to avoid any dependence on the type of
2756 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2758 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2759 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2760 * I think using a beta of 1/8 is probably appropriate. 93.04.21
2762 MUTEX_ENTER(&conn->conn_data_lock);
2763 skew = conn->lastSerial - np->header.serial;
2764 conn->lastSerial = np->header.serial;
2765 MUTEX_EXIT(&conn->conn_data_lock);
2767 register struct rx_peer *peer;
2769 if (skew > peer->inPacketSkew) {
2770 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
2772 peer->inPacketSkew = skew;
2776 /* Now do packet type-specific processing */
2777 switch (np->header.type) {
2778 case RX_PACKET_TYPE_DATA:
2779 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
2782 case RX_PACKET_TYPE_ACK:
2783 /* Respond immediately to ack packets requesting acknowledgement
2785 if (np->header.flags & RX_REQUEST_ACK) {
2787 (void)rxi_SendCallAbort(call, 0, 1, 0);
2789 (void)rxi_SendAck(call, 0, np->header.serial,
2790 RX_ACK_PING_RESPONSE, 1);
2792 np = rxi_ReceiveAckPacket(call, np, 1);
2794 case RX_PACKET_TYPE_ABORT:
2795 /* An abort packet: reset the connection, passing the error up to
2797 /* What if error is zero? */
2798 rxi_CallError(call, ntohl(*(afs_int32 *) rx_DataOf(np)));
2800 case RX_PACKET_TYPE_BUSY:
2803 case RX_PACKET_TYPE_ACKALL:
2804 /* All packets acknowledged, so we can drop all packets previously
2805 * readied for sending */
2806 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2807 /* XXX Hack. We because we can't release the global rx lock when
2808 * sending packets (osi_NetSend) we drop all ack pkts while we're
2809 * traversing the tq in rxi_Start sending packets out because
2810 * packets may move to the freePacketQueue as result of being
2811 * here! So we drop these packets until we're safely out of the
2812 * traversing. Really ugly!
2813 * For fine grain RX locking, we set the acked field in the packets
2814 * and let rxi_Start remove the packets from the transmit queue.
2816 if (call->flags & RX_CALL_TQ_BUSY) {
2817 #ifdef RX_ENABLE_LOCKS
2818 rxi_SetAcksInTransmitQueue(call);
2820 #else /* RX_ENABLE_LOCKS */
2822 return np; /* xmitting; drop packet */
2823 #endif /* RX_ENABLE_LOCKS */
2825 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2826 rxi_ClearTransmitQueue(call, 0);
2829 /* Should not reach here, unless the peer is broken: send an abort
2831 rxi_CallError(call, RX_PROTOCOL_ERROR);
2832 np = rxi_SendCallAbort(call, np, 1, 0);
2835 /* Note when this last legitimate packet was received, for keep-alive
2836 * processing. Note, we delay getting the time until now in the hope that
2837 * the packet will be delivered to the user before any get time is required
2838 * (if not, then the time won't actually be re-evaluated here). */
2839 call->lastReceiveTime = clock_Sec();
2840 MUTEX_EXIT(&call->lock);
2841 MUTEX_ENTER(&conn->conn_data_lock);
2843 MUTEX_EXIT(&conn->conn_data_lock);
2847 /* return true if this is an "interesting" connection from the point of view
2848 of someone trying to debug the system */
2850 rxi_IsConnInteresting(struct rx_connection *aconn)
2853 register struct rx_call *tcall;
2855 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
2857 for (i = 0; i < RX_MAXCALLS; i++) {
2858 tcall = aconn->call[i];
2860 if ((tcall->state == RX_STATE_PRECALL)
2861 || (tcall->state == RX_STATE_ACTIVE))
2863 if ((tcall->mode == RX_MODE_SENDING)
2864 || (tcall->mode == RX_MODE_RECEIVING))
2872 /* if this is one of the last few packets AND it wouldn't be used by the
2873 receiving call to immediately satisfy a read request, then drop it on
2874 the floor, since accepting it might prevent a lock-holding thread from
2875 making progress in its reading. If a call has been cleared while in
2876 the precall state then ignore all subsequent packets until the call
2877 is assigned to a thread. */
2880 TooLow(struct rx_packet *ap, struct rx_call *acall)
2883 MUTEX_ENTER(&rx_stats_mutex);
2884 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
2885 && (acall->state == RX_STATE_PRECALL))
2886 || ((rx_nFreePackets < rxi_dataQuota + 2)
2887 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
2888 && (acall->flags & RX_CALL_READER_WAIT)))) {
2891 MUTEX_EXIT(&rx_stats_mutex);
2897 rxi_CheckReachEvent(struct rxevent *event, struct rx_connection *conn,
2898 struct rx_call *acall)
2900 struct rx_call *call = acall;
2904 MUTEX_ENTER(&conn->conn_data_lock);
2905 conn->checkReachEvent = NULL;
2906 waiting = conn->flags & RX_CONN_ATTACHWAIT;
2909 MUTEX_EXIT(&conn->conn_data_lock);
2913 MUTEX_ENTER(&conn->conn_call_lock);
2914 MUTEX_ENTER(&conn->conn_data_lock);
2915 for (i = 0; i < RX_MAXCALLS; i++) {
2916 struct rx_call *tc = conn->call[i];
2917 if (tc && tc->state == RX_STATE_PRECALL) {
2923 /* Indicate that rxi_CheckReachEvent is no longer running by
2924 * clearing the flag. Must be atomic under conn_data_lock to
2925 * avoid a new call slipping by: rxi_CheckConnReach holds
2926 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
2928 conn->flags &= ~RX_CONN_ATTACHWAIT;
2929 MUTEX_EXIT(&conn->conn_data_lock);
2930 MUTEX_EXIT(&conn->conn_call_lock);
2935 MUTEX_ENTER(&call->lock);
2936 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
2938 MUTEX_EXIT(&call->lock);
2940 clock_GetTime(&when);
2941 when.sec += RX_CHECKREACH_TIMEOUT;
2942 MUTEX_ENTER(&conn->conn_data_lock);
2943 if (!conn->checkReachEvent) {
2945 conn->checkReachEvent =
2946 rxevent_Post(&when, rxi_CheckReachEvent, conn, NULL);
2948 MUTEX_EXIT(&conn->conn_data_lock);
2954 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
2956 struct rx_service *service = conn->service;
2957 struct rx_peer *peer = conn->peer;
2958 afs_uint32 now, lastReach;
2960 if (service->checkReach == 0)
2964 MUTEX_ENTER(&peer->peer_lock);
2965 lastReach = peer->lastReachTime;
2966 MUTEX_EXIT(&peer->peer_lock);
2967 if (now - lastReach < RX_CHECKREACH_TTL)
2970 MUTEX_ENTER(&conn->conn_data_lock);
2971 if (conn->flags & RX_CONN_ATTACHWAIT) {
2972 MUTEX_EXIT(&conn->conn_data_lock);
2975 conn->flags |= RX_CONN_ATTACHWAIT;
2976 MUTEX_EXIT(&conn->conn_data_lock);
2977 if (!conn->checkReachEvent)
2978 rxi_CheckReachEvent(NULL, conn, call);
2983 /* try to attach call, if authentication is complete */
2985 TryAttach(register struct rx_call *acall, register osi_socket socket,
2986 register int *tnop, register struct rx_call **newcallp,
2989 struct rx_connection *conn = acall->conn;
2991 if (conn->type == RX_SERVER_CONNECTION
2992 && acall->state == RX_STATE_PRECALL) {
2993 /* Don't attach until we have any req'd. authentication. */
2994 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
2995 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
2996 rxi_AttachServerProc(acall, socket, tnop, newcallp);
2997 /* Note: this does not necessarily succeed; there
2998 * may not any proc available
3001 rxi_ChallengeOn(acall->conn);
3006 /* A data packet has been received off the interface. This packet is
3007 * appropriate to the call (the call is in the right state, etc.). This
3008 * routine can return a packet to the caller, for re-use */
3011 rxi_ReceiveDataPacket(register struct rx_call *call,
3012 register struct rx_packet *np, int istack,
3013 osi_socket socket, afs_uint32 host, u_short port,
3014 int *tnop, struct rx_call **newcallp)
3016 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3020 afs_uint32 seq, serial, flags;
3022 struct rx_packet *tnp;
3024 MUTEX_ENTER(&rx_stats_mutex);
3025 rx_stats.dataPacketsRead++;
3026 MUTEX_EXIT(&rx_stats_mutex);
3029 /* If there are no packet buffers, drop this new packet, unless we can find
3030 * packet buffers from inactive calls */
3032 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3033 MUTEX_ENTER(&rx_freePktQ_lock);
3034 rxi_NeedMorePackets = TRUE;
3035 MUTEX_EXIT(&rx_freePktQ_lock);
3036 MUTEX_ENTER(&rx_stats_mutex);
3037 rx_stats.noPacketBuffersOnRead++;
3038 MUTEX_EXIT(&rx_stats_mutex);
3039 call->rprev = np->header.serial;
3040 rxi_calltrace(RX_TRACE_DROP, call);
3041 dpf(("packet %x dropped on receipt - quota problems", np));
3043 rxi_ClearReceiveQueue(call);
3044 clock_GetTime(&when);
3045 clock_Add(&when, &rx_softAckDelay);
3046 if (!call->delayedAckEvent
3047 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3048 rxevent_Cancel(call->delayedAckEvent, call,
3049 RX_CALL_REFCOUNT_DELAY);
3050 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3051 call->delayedAckEvent =
3052 rxevent_Post(&when, rxi_SendDelayedAck, call, 0);
3054 /* we've damaged this call already, might as well do it in. */
3060 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3061 * packet is one of several packets transmitted as a single
3062 * datagram. Do not send any soft or hard acks until all packets
3063 * in a jumbogram have been processed. Send negative acks right away.
3065 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3066 /* tnp is non-null when there are more packets in the
3067 * current jumbo gram */
3074 seq = np->header.seq;
3075 serial = np->header.serial;
3076 flags = np->header.flags;
3078 /* If the call is in an error state, send an abort message */
3080 return rxi_SendCallAbort(call, np, istack, 0);
3082 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3083 * AFS 3.5 jumbogram. */
3084 if (flags & RX_JUMBO_PACKET) {
3085 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3090 if (np->header.spare != 0) {
3091 MUTEX_ENTER(&call->conn->conn_data_lock);
3092 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3093 MUTEX_EXIT(&call->conn->conn_data_lock);
3096 /* The usual case is that this is the expected next packet */
3097 if (seq == call->rnext) {
3099 /* Check to make sure it is not a duplicate of one already queued */
3100 if (queue_IsNotEmpty(&call->rq)
3101 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3102 MUTEX_ENTER(&rx_stats_mutex);
3103 rx_stats.dupPacketsRead++;
3104 MUTEX_EXIT(&rx_stats_mutex);
3105 dpf(("packet %x dropped on receipt - duplicate", np));
3106 rxevent_Cancel(call->delayedAckEvent, call,
3107 RX_CALL_REFCOUNT_DELAY);
3108 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3114 /* It's the next packet. Stick it on the receive queue
3115 * for this call. Set newPackets to make sure we wake
3116 * the reader once all packets have been processed */
3117 queue_Prepend(&call->rq, np);
3119 np = NULL; /* We can't use this anymore */
3122 /* If an ack is requested then set a flag to make sure we
3123 * send an acknowledgement for this packet */
3124 if (flags & RX_REQUEST_ACK) {
3125 ackNeeded = RX_ACK_REQUESTED;
3128 /* Keep track of whether we have received the last packet */
3129 if (flags & RX_LAST_PACKET) {
3130 call->flags |= RX_CALL_HAVE_LAST;
3134 /* Check whether we have all of the packets for this call */
3135 if (call->flags & RX_CALL_HAVE_LAST) {
3136 afs_uint32 tseq; /* temporary sequence number */
3137 struct rx_packet *tp; /* Temporary packet pointer */
3138 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3140 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3141 if (tseq != tp->header.seq)
3143 if (tp->header.flags & RX_LAST_PACKET) {
3144 call->flags |= RX_CALL_RECEIVE_DONE;
3151 /* Provide asynchronous notification for those who want it
3152 * (e.g. multi rx) */
3153 if (call->arrivalProc) {
3154 (*call->arrivalProc) (call, call->arrivalProcHandle,
3155 (int)call->arrivalProcArg);
3156 call->arrivalProc = (VOID(*)())0;
3159 /* Update last packet received */
3162 /* If there is no server process serving this call, grab
3163 * one, if available. We only need to do this once. If a
3164 * server thread is available, this thread becomes a server
3165 * thread and the server thread becomes a listener thread. */
3167 TryAttach(call, socket, tnop, newcallp, 0);
3170 /* This is not the expected next packet. */
3172 /* Determine whether this is a new or old packet, and if it's
3173 * a new one, whether it fits into the current receive window.
3174 * Also figure out whether the packet was delivered in sequence.
3175 * We use the prev variable to determine whether the new packet
3176 * is the successor of its immediate predecessor in the
3177 * receive queue, and the missing flag to determine whether
3178 * any of this packets predecessors are missing. */
3180 afs_uint32 prev; /* "Previous packet" sequence number */
3181 struct rx_packet *tp; /* Temporary packet pointer */
3182 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3183 int missing; /* Are any predecessors missing? */
3185 /* If the new packet's sequence number has been sent to the
3186 * application already, then this is a duplicate */
3187 if (seq < call->rnext) {
3188 MUTEX_ENTER(&rx_stats_mutex);
3189 rx_stats.dupPacketsRead++;
3190 MUTEX_EXIT(&rx_stats_mutex);
3191 rxevent_Cancel(call->delayedAckEvent, call,
3192 RX_CALL_REFCOUNT_DELAY);
3193 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3199 /* If the sequence number is greater than what can be
3200 * accomodated by the current window, then send a negative
3201 * acknowledge and drop the packet */
3202 if ((call->rnext + call->rwind) <= seq) {
3203 rxevent_Cancel(call->delayedAckEvent, call,
3204 RX_CALL_REFCOUNT_DELAY);
3205 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3212 /* Look for the packet in the queue of old received packets */
3213 for (prev = call->rnext - 1, missing =
3214 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3215 /*Check for duplicate packet */
3216 if (seq == tp->header.seq) {
3217 MUTEX_ENTER(&rx_stats_mutex);
3218 rx_stats.dupPacketsRead++;
3219 MUTEX_EXIT(&rx_stats_mutex);
3220 rxevent_Cancel(call->delayedAckEvent, call,
3221 RX_CALL_REFCOUNT_DELAY);
3222 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3228 /* If we find a higher sequence packet, break out and
3229 * insert the new packet here. */
3230 if (seq < tp->header.seq)
3232 /* Check for missing packet */
3233 if (tp->header.seq != prev + 1) {
3237 prev = tp->header.seq;
3240 /* Keep track of whether we have received the last packet. */
3241 if (flags & RX_LAST_PACKET) {
3242 call->flags |= RX_CALL_HAVE_LAST;
3245 /* It's within the window: add it to the the receive queue.
3246 * tp is left by the previous loop either pointing at the
3247 * packet before which to insert the new packet, or at the
3248 * queue head if the queue is empty or the packet should be
3250 queue_InsertBefore(tp, np);
3254 /* Check whether we have all of the packets for this call */
3255 if ((call->flags & RX_CALL_HAVE_LAST)
3256 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3257 afs_uint32 tseq; /* temporary sequence number */
3260 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3261 if (tseq != tp->header.seq)
3263 if (tp->header.flags & RX_LAST_PACKET) {
3264 call->flags |= RX_CALL_RECEIVE_DONE;
3271 /* We need to send an ack of the packet is out of sequence,
3272 * or if an ack was requested by the peer. */
3273 if (seq != prev + 1 || missing || (flags & RX_REQUEST_ACK)) {
3274 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3277 /* Acknowledge the last packet for each call */
3278 if (flags & RX_LAST_PACKET) {
3289 * If the receiver is waiting for an iovec, fill the iovec
3290 * using the data from the receive queue */
3291 if (call->flags & RX_CALL_IOVEC_WAIT) {
3292 didHardAck = rxi_FillReadVec(call, serial);
3293 /* the call may have been aborted */
3302 /* Wakeup the reader if any */
3303 if ((call->flags & RX_CALL_READER_WAIT)
3304 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3305 || (call->iovNext >= call->iovMax)
3306 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3307 call->flags &= ~RX_CALL_READER_WAIT;
3308 #ifdef RX_ENABLE_LOCKS
3309 CV_BROADCAST(&call->cv_rq);
3311 osi_rxWakeup(&call->rq);
3317 * Send an ack when requested by the peer, or once every
3318 * rxi_SoftAckRate packets until the last packet has been
3319 * received. Always send a soft ack for the last packet in
3320 * the server's reply. */
3322 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3323 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3324 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3325 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3326 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3327 } else if (call->nSoftAcks) {
3328 clock_GetTime(&when);
3329 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3330 clock_Add(&when, &rx_lastAckDelay);
3332 clock_Add(&when, &rx_softAckDelay);
3334 if (!call->delayedAckEvent
3335 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3336 rxevent_Cancel(call->delayedAckEvent, call,
3337 RX_CALL_REFCOUNT_DELAY);
3338 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3339 call->delayedAckEvent =
3340 rxevent_Post(&when, rxi_SendDelayedAck, call, 0);
3342 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3343 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3350 static void rxi_ComputeRate();
3354 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3356 struct rx_peer *peer = conn->peer;
3358 MUTEX_ENTER(&peer->peer_lock);
3359 peer->lastReachTime = clock_Sec();
3360 MUTEX_EXIT(&peer->peer_lock);
3362 MUTEX_ENTER(&conn->conn_data_lock);
3363 if (conn->flags & RX_CONN_ATTACHWAIT) {
3366 conn->flags &= ~RX_CONN_ATTACHWAIT;
3367 MUTEX_EXIT(&conn->conn_data_lock);
3369 for (i = 0; i < RX_MAXCALLS; i++) {
3370 struct rx_call *call = conn->call[i];
3373 MUTEX_ENTER(&call->lock);
3374 /* tnop can be null if newcallp is null */
3375 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3377 MUTEX_EXIT(&call->lock);
3381 MUTEX_EXIT(&conn->conn_data_lock);
3384 /* rxi_ComputePeerNetStats
3386 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3387 * estimates (like RTT and throughput) based on ack packets. Caller
3388 * must ensure that the packet in question is the right one (i.e.
3389 * serial number matches).
3392 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3393 struct rx_ackPacket *ap, struct rx_packet *np)
3395 struct rx_peer *peer = call->conn->peer;
3397 /* Use RTT if not delayed by client. */
3398 if (ap->reason != RX_ACK_DELAY)
3399 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3401 rxi_ComputeRate(peer, call, p, np, ap->reason);
3405 /* The real smarts of the whole thing. */
3407 rxi_ReceiveAckPacket(register struct rx_call *call, struct rx_packet *np,
3410 struct rx_ackPacket *ap;
3412 register struct rx_packet *tp;
3413 register struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3414 register struct rx_connection *conn = call->conn;
3415 struct rx_peer *peer = conn->peer;
3418 /* because there are CM's that are bogus, sending weird values for this. */
3419 afs_uint32 skew = 0;
3424 int newAckCount = 0;
3425 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3426 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3428 MUTEX_ENTER(&rx_stats_mutex);
3429 rx_stats.ackPacketsRead++;
3430 MUTEX_EXIT(&rx_stats_mutex);
3431 ap = (struct rx_ackPacket *)rx_DataOf(np);
3432 nbytes = rx_Contiguous(np) - ((ap->acks) - (u_char *) ap);
3434 return np; /* truncated ack packet */
3436 /* depends on ack packet struct */
3437 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3438 first = ntohl(ap->firstPacket);
3439 serial = ntohl(ap->serial);
3440 /* temporarily disabled -- needs to degrade over time
3441 * skew = ntohs(ap->maxSkew); */
3443 /* Ignore ack packets received out of order */
3444 if (first < call->tfirst) {
3448 if (np->header.flags & RX_SLOW_START_OK) {
3449 call->flags |= RX_CALL_SLOW_START_OK;
3452 if (ap->reason == RX_ACK_PING_RESPONSE)
3453 rxi_UpdatePeerReach(conn, call);
3458 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3459 ap->reason, ntohl(ap->previousPacket),
3460 (unsigned int)np->header.seq, (unsigned int)serial,
3461 (unsigned int)skew, ntohl(ap->firstPacket));
3464 for (offset = 0; offset < nAcks; offset++)
3465 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3472 /* Update the outgoing packet skew value to the latest value of
3473 * the peer's incoming packet skew value. The ack packet, of
3474 * course, could arrive out of order, but that won't affect things
3476 MUTEX_ENTER(&peer->peer_lock);
3477 peer->outPacketSkew = skew;
3479 /* Check for packets that no longer need to be transmitted, and
3480 * discard them. This only applies to packets positively
3481 * acknowledged as having been sent to the peer's upper level.
3482 * All other packets must be retained. So only packets with
3483 * sequence numbers < ap->firstPacket are candidates. */
3484 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3485 if (tp->header.seq >= first)
3487 call->tfirst = tp->header.seq + 1;
3489 && (tp->header.serial == serial || tp->firstSerial == serial))
3490 rxi_ComputePeerNetStats(call, tp, ap, np);
3491 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3492 /* XXX Hack. Because we have to release the global rx lock when sending
3493 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3494 * in rxi_Start sending packets out because packets may move to the
3495 * freePacketQueue as result of being here! So we drop these packets until
3496 * we're safely out of the traversing. Really ugly!
3497 * To make it even uglier, if we're using fine grain locking, we can
3498 * set the ack bits in the packets and have rxi_Start remove the packets
3499 * when it's done transmitting.
3501 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3504 if (call->flags & RX_CALL_TQ_BUSY) {
3505 #ifdef RX_ENABLE_LOCKS
3506 tp->flags |= RX_PKTFLAG_ACKED;
3507 call->flags |= RX_CALL_TQ_SOME_ACKED;
3508 #else /* RX_ENABLE_LOCKS */
3510 #endif /* RX_ENABLE_LOCKS */
3512 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3515 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3520 /* Give rate detector a chance to respond to ping requests */
3521 if (ap->reason == RX_ACK_PING_RESPONSE) {
3522 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3526 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3528 /* Now go through explicit acks/nacks and record the results in
3529 * the waiting packets. These are packets that can't be released
3530 * yet, even with a positive acknowledge. This positive
3531 * acknowledge only means the packet has been received by the
3532 * peer, not that it will be retained long enough to be sent to
3533 * the peer's upper level. In addition, reset the transmit timers
3534 * of any missing packets (those packets that must be missing
3535 * because this packet was out of sequence) */
3537 call->nSoftAcked = 0;
3538 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3539 /* Update round trip time if the ack was stimulated on receipt
3541 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3542 #ifdef RX_ENABLE_LOCKS
3543 if (tp->header.seq >= first)
3544 #endif /* RX_ENABLE_LOCKS */
3545 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3547 && (tp->header.serial == serial || tp->firstSerial == serial))
3548 rxi_ComputePeerNetStats(call, tp, ap, np);
3550 /* Set the acknowledge flag per packet based on the
3551 * information in the ack packet. An acknowlegded packet can
3552 * be downgraded when the server has discarded a packet it
3553 * soacked previously, or when an ack packet is received
3554 * out of sequence. */
3555 if (tp->header.seq < first) {
3556 /* Implicit ack information */
3557 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3560 tp->flags |= RX_PKTFLAG_ACKED;
3561 } else if (tp->header.seq < first + nAcks) {
3562 /* Explicit ack information: set it in the packet appropriately */
3563 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3564 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3566 tp->flags |= RX_PKTFLAG_ACKED;
3574 tp->flags &= ~RX_PKTFLAG_ACKED;
3578 tp->flags &= ~RX_PKTFLAG_ACKED;
3582 /* If packet isn't yet acked, and it has been transmitted at least
3583 * once, reset retransmit time using latest timeout
3584 * ie, this should readjust the retransmit timer for all outstanding
3585 * packets... So we don't just retransmit when we should know better*/
3587 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3588 tp->retryTime = tp->timeSent;
3589 clock_Add(&tp->retryTime, &peer->timeout);
3590 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3591 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3595 /* If the window has been extended by this acknowledge packet,
3596 * then wakeup a sender waiting in alloc for window space, or try
3597 * sending packets now, if he's been sitting on packets due to
3598 * lack of window space */
3599 if (call->tnext < (call->tfirst + call->twind)) {
3600 #ifdef RX_ENABLE_LOCKS
3601 CV_SIGNAL(&call->cv_twind);
3603 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3604 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3605 osi_rxWakeup(&call->twind);
3608 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3609 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3613 /* if the ack packet has a receivelen field hanging off it,
3614 * update our state */
3615 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3618 /* If the ack packet has a "recommended" size that is less than
3619 * what I am using now, reduce my size to match */
3620 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3621 sizeof(afs_int32), &tSize);
3622 tSize = (afs_uint32) ntohl(tSize);
3623 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3625 /* Get the maximum packet size to send to this peer */
3626 rx_packetread(np, rx_AckDataSize(ap->nAcks), sizeof(afs_int32),
3628 tSize = (afs_uint32) ntohl(tSize);
3629 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3630 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3632 /* sanity check - peer might have restarted with different params.
3633 * If peer says "send less", dammit, send less... Peer should never
3634 * be unable to accept packets of the size that prior AFS versions would
3635 * send without asking. */
3636 if (peer->maxMTU != tSize) {
3637 peer->maxMTU = tSize;
3638 peer->MTU = MIN(tSize, peer->MTU);
3639 call->MTU = MIN(call->MTU, tSize);
3643 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3646 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3647 sizeof(afs_int32), &tSize);
3648 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3649 if (tSize < call->twind) { /* smaller than our send */
3650 call->twind = tSize; /* window, we must send less... */
3651 call->ssthresh = MIN(call->twind, call->ssthresh);
3654 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3655 * network MTU confused with the loopback MTU. Calculate the
3656 * maximum MTU here for use in the slow start code below.
3658 maxMTU = peer->maxMTU;
3659 /* Did peer restart with older RX version? */
3660 if (peer->maxDgramPackets > 1) {
3661 peer->maxDgramPackets = 1;
3663 } else if (np->length >=
3664 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3667 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3668 sizeof(afs_int32), &tSize);
3669 tSize = (afs_uint32) ntohl(tSize);
3671 * As of AFS 3.5 we set the send window to match the receive window.
3673 if (tSize < call->twind) {
3674 call->twind = tSize;
3675 call->ssthresh = MIN(call->twind, call->ssthresh);
3676 } else if (tSize > call->twind) {
3677 call->twind = tSize;
3681 * As of AFS 3.5, a jumbogram is more than one fixed size
3682 * packet transmitted in a single UDP datagram. If the remote
3683 * MTU is smaller than our local MTU then never send a datagram
3684 * larger than the natural MTU.
3687 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
3688 sizeof(afs_int32), &tSize);
3689 maxDgramPackets = (afs_uint32) ntohl(tSize);
3690 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
3692 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
3693 maxDgramPackets = MIN(maxDgramPackets, tSize);
3694 if (maxDgramPackets > 1) {
3695 peer->maxDgramPackets = maxDgramPackets;
3696 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
3698 peer->maxDgramPackets = 1;
3699 call->MTU = peer->natMTU;
3701 } else if (peer->maxDgramPackets > 1) {
3702 /* Restarted with lower version of RX */
3703 peer->maxDgramPackets = 1;
3705 } else if (peer->maxDgramPackets > 1
3706 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
3707 /* Restarted with lower version of RX */
3708 peer->maxMTU = OLD_MAX_PACKET_SIZE;
3709 peer->natMTU = OLD_MAX_PACKET_SIZE;
3710 peer->MTU = OLD_MAX_PACKET_SIZE;
3711 peer->maxDgramPackets = 1;
3712 peer->nDgramPackets = 1;
3714 call->MTU = OLD_MAX_PACKET_SIZE;
3719 * Calculate how many datagrams were successfully received after
3720 * the first missing packet and adjust the negative ack counter
3725 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
3726 if (call->nNacks < nNacked) {
3727 call->nNacks = nNacked;
3736 if (call->flags & RX_CALL_FAST_RECOVER) {
3738 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
3740 call->flags &= ~RX_CALL_FAST_RECOVER;
3741 call->cwind = call->nextCwind;
3742 call->nextCwind = 0;
3745 call->nCwindAcks = 0;
3746 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
3747 /* Three negative acks in a row trigger congestion recovery */
3748 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3749 MUTEX_EXIT(&peer->peer_lock);
3750 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
3751 /* someone else is waiting to start recovery */
3754 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
3755 while (call->flags & RX_CALL_TQ_BUSY) {
3756 call->flags |= RX_CALL_TQ_WAIT;
3757 #ifdef RX_ENABLE_LOCKS
3758 CV_WAIT(&call->cv_tq, &call->lock);
3759 #else /* RX_ENABLE_LOCKS */
3760 osi_rxSleep(&call->tq);
3761 #endif /* RX_ENABLE_LOCKS */
3763 MUTEX_ENTER(&peer->peer_lock);
3764 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3765 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
3766 call->flags |= RX_CALL_FAST_RECOVER;
3767 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
3769 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
3770 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
3771 call->nextCwind = call->ssthresh;
3774 peer->MTU = call->MTU;
3775 peer->cwind = call->nextCwind;
3776 peer->nDgramPackets = call->nDgramPackets;
3778 call->congestSeq = peer->congestSeq;
3779 /* Reset the resend times on the packets that were nacked
3780 * so we will retransmit as soon as the window permits*/
3781 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
3783 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3784 clock_Zero(&tp->retryTime);
3786 } else if (tp->flags & RX_PKTFLAG_ACKED) {
3791 /* If cwind is smaller than ssthresh, then increase
3792 * the window one packet for each ack we receive (exponential
3794 * If cwind is greater than or equal to ssthresh then increase
3795 * the congestion window by one packet for each cwind acks we
3796 * receive (linear growth). */
3797 if (call->cwind < call->ssthresh) {
3799 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
3800 call->nCwindAcks = 0;
3802 call->nCwindAcks += newAckCount;
3803 if (call->nCwindAcks >= call->cwind) {
3804 call->nCwindAcks = 0;
3805 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
3809 * If we have received several acknowledgements in a row then
3810 * it is time to increase the size of our datagrams
3812 if ((int)call->nAcks > rx_nDgramThreshold) {
3813 if (peer->maxDgramPackets > 1) {
3814 if (call->nDgramPackets < peer->maxDgramPackets) {
3815 call->nDgramPackets++;
3817 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
3818 } else if (call->MTU < peer->maxMTU) {
3819 call->MTU += peer->natMTU;
3820 call->MTU = MIN(call->MTU, peer->maxMTU);
3826 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
3828 /* Servers need to hold the call until all response packets have
3829 * been acknowledged. Soft acks are good enough since clients
3830 * are not allowed to clear their receive queues. */
3831 if (call->state == RX_STATE_HOLD
3832 && call->tfirst + call->nSoftAcked >= call->tnext) {
3833 call->state = RX_STATE_DALLY;
3834 rxi_ClearTransmitQueue(call, 0);
3835 } else if (!queue_IsEmpty(&call->tq)) {
3836 rxi_Start(0, call, istack);
3841 /* Received a response to a challenge packet */
3843 rxi_ReceiveResponsePacket(register struct rx_connection *conn,
3844 register struct rx_packet *np, int istack)
3848 /* Ignore the packet if we're the client */
3849 if (conn->type == RX_CLIENT_CONNECTION)
3852 /* If already authenticated, ignore the packet (it's probably a retry) */
3853 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
3856 /* Otherwise, have the security object evaluate the response packet */
3857 error = RXS_CheckResponse(conn->securityObject, conn, np);
3859 /* If the response is invalid, reset the connection, sending
3860 * an abort to the peer */
3864 rxi_ConnectionError(conn, error);
3865 MUTEX_ENTER(&conn->conn_data_lock);
3866 np = rxi_SendConnectionAbort(conn, np, istack, 0);
3867 MUTEX_EXIT(&conn->conn_data_lock);
3870 /* If the response is valid, any calls waiting to attach
3871 * servers can now do so */
3874 for (i = 0; i < RX_MAXCALLS; i++) {
3875 struct rx_call *call = conn->call[i];
3877 MUTEX_ENTER(&call->lock);
3878 if (call->state == RX_STATE_PRECALL)
3879 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
3880 /* tnop can be null if newcallp is null */
3881 MUTEX_EXIT(&call->lock);
3885 /* Update the peer reachability information, just in case
3886 * some calls went into attach-wait while we were waiting
3887 * for authentication..
3889 rxi_UpdatePeerReach(conn, NULL);
3894 /* A client has received an authentication challenge: the security
3895 * object is asked to cough up a respectable response packet to send
3896 * back to the server. The server is responsible for retrying the
3897 * challenge if it fails to get a response. */
3900 rxi_ReceiveChallengePacket(register struct rx_connection *conn,
3901 register struct rx_packet *np, int istack)
3905 /* Ignore the challenge if we're the server */
3906 if (conn->type == RX_SERVER_CONNECTION)
3909 /* Ignore the challenge if the connection is otherwise idle; someone's
3910 * trying to use us as an oracle. */
3911 if (!rxi_HasActiveCalls(conn))
3914 /* Send the security object the challenge packet. It is expected to fill
3915 * in the response. */
3916 error = RXS_GetResponse(conn->securityObject, conn, np);
3918 /* If the security object is unable to return a valid response, reset the
3919 * connection and send an abort to the peer. Otherwise send the response
3920 * packet to the peer connection. */
3922 rxi_ConnectionError(conn, error);
3923 MUTEX_ENTER(&conn->conn_data_lock);
3924 np = rxi_SendConnectionAbort(conn, np, istack, 0);
3925 MUTEX_EXIT(&conn->conn_data_lock);
3927 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
3928 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
3934 /* Find an available server process to service the current request in
3935 * the given call structure. If one isn't available, queue up this
3936 * call so it eventually gets one */
3938 rxi_AttachServerProc(register struct rx_call *call,
3939 register osi_socket socket, register int *tnop,
3940 register struct rx_call **newcallp)
3942 register struct rx_serverQueueEntry *sq;
3943 register struct rx_service *service = call->conn->service;
3944 register int haveQuota = 0;
3946 /* May already be attached */
3947 if (call->state == RX_STATE_ACTIVE)
3950 MUTEX_ENTER(&rx_serverPool_lock);
3952 haveQuota = QuotaOK(service);
3953 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
3954 /* If there are no processes available to service this call,
3955 * put the call on the incoming call queue (unless it's
3956 * already on the queue).
3958 #ifdef RX_ENABLE_LOCKS
3960 ReturnToServerPool(service);
3961 #endif /* RX_ENABLE_LOCKS */
3963 if (!(call->flags & RX_CALL_WAIT_PROC)) {
3964 call->flags |= RX_CALL_WAIT_PROC;
3965 MUTEX_ENTER(&rx_stats_mutex);
3967 MUTEX_EXIT(&rx_stats_mutex);
3968 rxi_calltrace(RX_CALL_ARRIVAL, call);
3969 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
3970 queue_Append(&rx_incomingCallQueue, call);
3973 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
3975 /* If hot threads are enabled, and both newcallp and sq->socketp
3976 * are non-null, then this thread will process the call, and the
3977 * idle server thread will start listening on this threads socket.
3980 if (rx_enable_hot_thread && newcallp && sq->socketp) {
3983 *sq->socketp = socket;
3984 clock_GetTime(&call->startTime);
3985 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
3989 if (call->flags & RX_CALL_WAIT_PROC) {
3990 /* Conservative: I don't think this should happen */
3991 call->flags &= ~RX_CALL_WAIT_PROC;
3992 MUTEX_ENTER(&rx_stats_mutex);
3994 MUTEX_EXIT(&rx_stats_mutex);
3997 call->state = RX_STATE_ACTIVE;
3998 call->mode = RX_MODE_RECEIVING;
3999 #ifdef RX_KERNEL_TRACE
4001 int glockOwner = ISAFS_GLOCK();
4004 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4005 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4011 if (call->flags & RX_CALL_CLEARED) {
4012 /* send an ack now to start the packet flow up again */
4013 call->flags &= ~RX_CALL_CLEARED;
4014 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4016 #ifdef RX_ENABLE_LOCKS
4019 service->nRequestsRunning++;
4020 if (service->nRequestsRunning <= service->minProcs)
4026 MUTEX_EXIT(&rx_serverPool_lock);
4029 /* Delay the sending of an acknowledge event for a short while, while
4030 * a new call is being prepared (in the case of a client) or a reply
4031 * is being prepared (in the case of a server). Rather than sending
4032 * an ack packet, an ACKALL packet is sent. */
4034 rxi_AckAll(struct rxevent *event, register struct rx_call *call, char *dummy)
4036 #ifdef RX_ENABLE_LOCKS
4038 MUTEX_ENTER(&call->lock);
4039 call->delayedAckEvent = NULL;
4040 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4042 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4043 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4045 MUTEX_EXIT(&call->lock);
4046 #else /* RX_ENABLE_LOCKS */
4048 call->delayedAckEvent = NULL;
4049 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4050 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4051 #endif /* RX_ENABLE_LOCKS */
4055 rxi_SendDelayedAck(struct rxevent *event, register struct rx_call *call,
4058 #ifdef RX_ENABLE_LOCKS
4060 MUTEX_ENTER(&call->lock);
4061 if (event == call->delayedAckEvent)
4062 call->delayedAckEvent = NULL;
4063 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4065 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4067 MUTEX_EXIT(&call->lock);
4068 #else /* RX_ENABLE_LOCKS */
4070 call->delayedAckEvent = NULL;
4071 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4072 #endif /* RX_ENABLE_LOCKS */
4076 #ifdef RX_ENABLE_LOCKS
4077 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4078 * clearing them out.
4081 rxi_SetAcksInTransmitQueue(register struct rx_call *call)
4083 register struct rx_packet *p, *tp;
4086 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4089 p->flags |= RX_PKTFLAG_ACKED;
4093 call->flags |= RX_CALL_TQ_CLEARME;
4094 call->flags |= RX_CALL_TQ_SOME_ACKED;
4097 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4098 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4099 call->tfirst = call->tnext;
4100 call->nSoftAcked = 0;
4102 if (call->flags & RX_CALL_FAST_RECOVER) {
4103 call->flags &= ~RX_CALL_FAST_RECOVER;
4104 call->cwind = call->nextCwind;
4105 call->nextCwind = 0;
4108 CV_SIGNAL(&call->cv_twind);
4110 #endif /* RX_ENABLE_LOCKS */
4112 /* Clear out the transmit queue for the current call (all packets have
4113 * been received by peer) */
4115 rxi_ClearTransmitQueue(register struct rx_call *call, register int force)
4117 register struct rx_packet *p, *tp;
4119 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4120 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4122 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4125 p->flags |= RX_PKTFLAG_ACKED;
4129 call->flags |= RX_CALL_TQ_CLEARME;
4130 call->flags |= RX_CALL_TQ_SOME_ACKED;
4133 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4134 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4140 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4141 call->flags &= ~RX_CALL_TQ_CLEARME;
4143 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4145 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4146 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4147 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4148 call->nSoftAcked = 0;
4150 if (call->flags & RX_CALL_FAST_RECOVER) {
4151 call->flags &= ~RX_CALL_FAST_RECOVER;
4152 call->cwind = call->nextCwind;
4154 #ifdef RX_ENABLE_LOCKS
4155 CV_SIGNAL(&call->cv_twind);
4157 osi_rxWakeup(&call->twind);
4162 rxi_ClearReceiveQueue(register struct rx_call *call)
4164 register struct rx_packet *p, *tp;
4165 if (queue_IsNotEmpty(&call->rq)) {
4166 for (queue_Scan(&call->rq, p, tp, rx_packet)) {
4171 rx_packetReclaims++;
4173 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4175 if (call->state == RX_STATE_PRECALL) {
4176 call->flags |= RX_CALL_CLEARED;
4180 /* Send an abort packet for the specified call */
4182 rxi_SendCallAbort(register struct rx_call *call, struct rx_packet *packet,
4183 int istack, int force)
4191 /* Clients should never delay abort messages */
4192 if (rx_IsClientConn(call->conn))
4195 if (call->abortCode != call->error) {
4196 call->abortCode = call->error;
4197 call->abortCount = 0;
4200 if (force || rxi_callAbortThreshhold == 0
4201 || call->abortCount < rxi_callAbortThreshhold) {
4202 if (call->delayedAbortEvent) {
4203 rxevent_Cancel(call->delayedAbortEvent, call,
4204 RX_CALL_REFCOUNT_ABORT);
4206 error = htonl(call->error);
4209 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4210 (char *)&error, sizeof(error), istack);
4211 } else if (!call->delayedAbortEvent) {
4212 clock_GetTime(&when);
4213 clock_Addmsec(&when, rxi_callAbortDelay);
4214 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4215 call->delayedAbortEvent =
4216 rxevent_Post(&when, rxi_SendDelayedCallAbort, call, 0);
4221 /* Send an abort packet for the specified connection. Packet is an
4222 * optional pointer to a packet that can be used to send the abort.
4223 * Once the number of abort messages reaches the threshhold, an
4224 * event is scheduled to send the abort. Setting the force flag
4225 * overrides sending delayed abort messages.
4227 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4228 * to send the abort packet.
4231 rxi_SendConnectionAbort(register struct rx_connection *conn,
4232 struct rx_packet *packet, int istack, int force)
4240 /* Clients should never delay abort messages */
4241 if (rx_IsClientConn(conn))
4244 if (force || rxi_connAbortThreshhold == 0
4245 || conn->abortCount < rxi_connAbortThreshhold) {
4246 if (conn->delayedAbortEvent) {
4247 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4249 error = htonl(conn->error);
4251 MUTEX_EXIT(&conn->conn_data_lock);
4253 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4254 RX_PACKET_TYPE_ABORT, (char *)&error,
4255 sizeof(error), istack);
4256 MUTEX_ENTER(&conn->conn_data_lock);
4257 } else if (!conn->delayedAbortEvent) {
4258 clock_GetTime(&when);
4259 clock_Addmsec(&when, rxi_connAbortDelay);
4260 conn->delayedAbortEvent =
4261 rxevent_Post(&when, rxi_SendDelayedConnAbort, conn, 0);
4266 /* Associate an error all of the calls owned by a connection. Called
4267 * with error non-zero. This is only for really fatal things, like
4268 * bad authentication responses. The connection itself is set in
4269 * error at this point, so that future packets received will be
4272 rxi_ConnectionError(register struct rx_connection *conn,
4273 register afs_int32 error)
4277 MUTEX_ENTER(&conn->conn_data_lock);
4278 if (conn->challengeEvent)
4279 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4280 if (conn->checkReachEvent) {
4281 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4282 conn->checkReachEvent = 0;
4283 conn->flags &= ~RX_CONN_ATTACHWAIT;
4286 MUTEX_EXIT(&conn->conn_data_lock);
4287 for (i = 0; i < RX_MAXCALLS; i++) {
4288 struct rx_call *call = conn->call[i];
4290 MUTEX_ENTER(&call->lock);
4291 rxi_CallError(call, error);
4292 MUTEX_EXIT(&call->lock);
4295 conn->error = error;
4296 MUTEX_ENTER(&rx_stats_mutex);
4297 rx_stats.fatalErrors++;
4298 MUTEX_EXIT(&rx_stats_mutex);
4303 rxi_CallError(register struct rx_call *call, afs_int32 error)
4306 error = call->error;
4307 #ifdef RX_GLOBAL_RXLOCK_KERNEL
4308 if (!(call->flags & RX_CALL_TQ_BUSY)) {
4309 rxi_ResetCall(call, 0);
4312 rxi_ResetCall(call, 0);
4314 call->error = error;
4315 call->mode = RX_MODE_ERROR;
4318 /* Reset various fields in a call structure, and wakeup waiting
4319 * processes. Some fields aren't changed: state & mode are not
4320 * touched (these must be set by the caller), and bufptr, nLeft, and
4321 * nFree are not reset, since these fields are manipulated by
4322 * unprotected macros, and may only be reset by non-interrupting code.
4325 /* this code requires that call->conn be set properly as a pre-condition. */
4326 #endif /* ADAPT_WINDOW */
4329 rxi_ResetCall(register struct rx_call *call, register int newcall)
4332 register struct rx_peer *peer;
4333 struct rx_packet *packet;
4335 /* Notify anyone who is waiting for asynchronous packet arrival */
4336 if (call->arrivalProc) {
4337 (*call->arrivalProc) (call, call->arrivalProcHandle,
4338 (int)call->arrivalProcArg);
4339 call->arrivalProc = (VOID(*)())0;
4342 if (call->delayedAbortEvent) {
4343 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4344 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4346 rxi_SendCallAbort(call, packet, 0, 1);
4347 rxi_FreePacket(packet);
4352 * Update the peer with the congestion information in this call
4353 * so other calls on this connection can pick up where this call
4354 * left off. If the congestion sequence numbers don't match then
4355 * another call experienced a retransmission.
4357 peer = call->conn->peer;
4358 MUTEX_ENTER(&peer->peer_lock);
4360 if (call->congestSeq == peer->congestSeq) {
4361 peer->cwind = MAX(peer->cwind, call->cwind);
4362 peer->MTU = MAX(peer->MTU, call->MTU);
4363 peer->nDgramPackets =
4364 MAX(peer->nDgramPackets, call->nDgramPackets);
4367 call->abortCode = 0;
4368 call->abortCount = 0;
4370 if (peer->maxDgramPackets > 1) {
4371 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4373 call->MTU = peer->MTU;
4375 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4376 call->ssthresh = rx_maxSendWindow;
4377 call->nDgramPackets = peer->nDgramPackets;
4378 call->congestSeq = peer->congestSeq;
4379 MUTEX_EXIT(&peer->peer_lock);
4381 flags = call->flags;
4382 rxi_ClearReceiveQueue(call);
4383 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4384 if (call->flags & RX_CALL_TQ_BUSY) {
4385 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4386 call->flags |= (flags & RX_CALL_TQ_WAIT);
4388 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4390 rxi_ClearTransmitQueue(call, 0);
4391 queue_Init(&call->tq);
4394 queue_Init(&call->rq);
4396 call->rwind = rx_initReceiveWindow;
4397 call->twind = rx_initSendWindow;
4398 call->nSoftAcked = 0;
4399 call->nextCwind = 0;
4402 call->nCwindAcks = 0;
4403 call->nSoftAcks = 0;
4404 call->nHardAcks = 0;
4406 call->tfirst = call->rnext = call->tnext = 1;
4408 call->lastAcked = 0;
4409 call->localStatus = call->remoteStatus = 0;
4411 if (flags & RX_CALL_READER_WAIT) {
4412 #ifdef RX_ENABLE_LOCKS
4413 CV_BROADCAST(&call->cv_rq);
4415 osi_rxWakeup(&call->rq);
4418 if (flags & RX_CALL_WAIT_PACKETS) {
4419 MUTEX_ENTER(&rx_freePktQ_lock);
4420 rxi_PacketsUnWait(); /* XXX */
4421 MUTEX_EXIT(&rx_freePktQ_lock);
4423 #ifdef RX_ENABLE_LOCKS
4424 CV_SIGNAL(&call->cv_twind);
4426 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4427 osi_rxWakeup(&call->twind);
4430 #ifdef RX_ENABLE_LOCKS
4431 /* The following ensures that we don't mess with any queue while some
4432 * other thread might also be doing so. The call_queue_lock field is
4433 * is only modified under the call lock. If the call is in the process
4434 * of being removed from a queue, the call is not locked until the
4435 * the queue lock is dropped and only then is the call_queue_lock field
4436 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4437 * Note that any other routine which removes a call from a queue has to
4438 * obtain the queue lock before examing the queue and removing the call.
4440 if (call->call_queue_lock) {
4441 MUTEX_ENTER(call->call_queue_lock);
4442 if (queue_IsOnQueue(call)) {
4444 if (flags & RX_CALL_WAIT_PROC) {
4445 MUTEX_ENTER(&rx_stats_mutex);
4447 MUTEX_EXIT(&rx_stats_mutex);
4450 MUTEX_EXIT(call->call_queue_lock);
4451 CLEAR_CALL_QUEUE_LOCK(call);
4453 #else /* RX_ENABLE_LOCKS */
4454 if (queue_IsOnQueue(call)) {
4456 if (flags & RX_CALL_WAIT_PROC)
4459 #endif /* RX_ENABLE_LOCKS */
4461 rxi_KeepAliveOff(call);
4462 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4465 /* Send an acknowledge for the indicated packet (seq,serial) of the
4466 * indicated call, for the indicated reason (reason). This
4467 * acknowledge will specifically acknowledge receiving the packet, and
4468 * will also specify which other packets for this call have been
4469 * received. This routine returns the packet that was used to the
4470 * caller. The caller is responsible for freeing it or re-using it.
4471 * This acknowledgement also returns the highest sequence number
4472 * actually read out by the higher level to the sender; the sender
4473 * promises to keep around packets that have not been read by the
4474 * higher level yet (unless, of course, the sender decides to abort
4475 * the call altogether). Any of p, seq, serial, pflags, or reason may
4476 * be set to zero without ill effect. That is, if they are zero, they
4477 * will not convey any information.
4478 * NOW there is a trailer field, after the ack where it will safely be
4479 * ignored by mundanes, which indicates the maximum size packet this
4480 * host can swallow. */
4482 register struct rx_packet *optionalPacket; use to send ack (or null)
4483 int seq; Sequence number of the packet we are acking
4484 int serial; Serial number of the packet
4485 int pflags; Flags field from packet header
4486 int reason; Reason an acknowledge was prompted
4490 rxi_SendAck(register struct rx_call *call,
4491 register struct rx_packet *optionalPacket, int serial, int reason,
4494 struct rx_ackPacket *ap;
4495 register struct rx_packet *rqp;
4496 register struct rx_packet *nxp; /* For queue_Scan */
4497 register struct rx_packet *p;
4502 * Open the receive window once a thread starts reading packets
4504 if (call->rnext > 1) {
4505 call->rwind = rx_maxReceiveWindow;
4508 call->nHardAcks = 0;
4509 call->nSoftAcks = 0;
4510 if (call->rnext > call->lastAcked)
4511 call->lastAcked = call->rnext;
4515 rx_computelen(p, p->length); /* reset length, you never know */
4516 } /* where that's been... */
4517 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4518 /* We won't send the ack, but don't panic. */
4519 return optionalPacket;
4523 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4526 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL)) {
4527 if (!optionalPacket)
4529 return optionalPacket;
4531 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4532 if (rx_Contiguous(p) < templ) {
4533 if (!optionalPacket)
4535 return optionalPacket;
4540 /* MTUXXX failing to send an ack is very serious. We should */
4541 /* try as hard as possible to send even a partial ack; it's */
4542 /* better than nothing. */
4543 ap = (struct rx_ackPacket *)rx_DataOf(p);
4544 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4545 ap->reason = reason;
4547 /* The skew computation used to be bogus, I think it's better now. */
4548 /* We should start paying attention to skew. XXX */
4549 ap->serial = htonl(serial);
4550 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4552 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4553 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4555 /* No fear of running out of ack packet here because there can only be at most
4556 * one window full of unacknowledged packets. The window size must be constrained
4557 * to be less than the maximum ack size, of course. Also, an ack should always
4558 * fit into a single packet -- it should not ever be fragmented. */
4559 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4560 if (!rqp || !call->rq.next
4561 || (rqp->header.seq > (call->rnext + call->rwind))) {
4562 if (!optionalPacket)
4564 rxi_CallError(call, RX_CALL_DEAD);
4565 return optionalPacket;
4568 while (rqp->header.seq > call->rnext + offset)
4569 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4570 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4572 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4573 if (!optionalPacket)
4575 rxi_CallError(call, RX_CALL_DEAD);
4576 return optionalPacket;
4581 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4583 /* these are new for AFS 3.3 */
4584 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4585 templ = htonl(templ);
4586 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4587 templ = htonl(call->conn->peer->ifMTU);
4588 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4589 sizeof(afs_int32), &templ);
4591 /* new for AFS 3.4 */
4592 templ = htonl(call->rwind);
4593 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4594 sizeof(afs_int32), &templ);
4596 /* new for AFS 3.5 */
4597 templ = htonl(call->conn->peer->ifDgramPackets);
4598 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4599 sizeof(afs_int32), &templ);
4601 p->header.serviceId = call->conn->serviceId;
4602 p->header.cid = (call->conn->cid | call->channel);
4603 p->header.callNumber = *call->callNumber;
4605 p->header.securityIndex = call->conn->securityIndex;
4606 p->header.epoch = call->conn->epoch;
4607 p->header.type = RX_PACKET_TYPE_ACK;
4608 p->header.flags = RX_SLOW_START_OK;
4609 if (reason == RX_ACK_PING) {
4610 p->header.flags |= RX_REQUEST_ACK;
4612 clock_GetTime(&call->pingRequestTime);
4615 if (call->conn->type == RX_CLIENT_CONNECTION)
4616 p->header.flags |= RX_CLIENT_INITIATED;
4620 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u",
4621 ap->reason, ntohl(ap->previousPacket),
4622 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
4624 for (offset = 0; offset < ap->nAcks; offset++)
4625 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4633 register int i, nbytes = p->length;
4635 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
4636 if (nbytes <= p->wirevec[i].iov_len) {
4637 register int savelen, saven;
4639 savelen = p->wirevec[i].iov_len;
4641 p->wirevec[i].iov_len = nbytes;
4643 rxi_Send(call, p, istack);
4644 p->wirevec[i].iov_len = savelen;
4648 nbytes -= p->wirevec[i].iov_len;
4651 MUTEX_ENTER(&rx_stats_mutex);
4652 rx_stats.ackPacketsSent++;
4653 MUTEX_EXIT(&rx_stats_mutex);
4654 if (!optionalPacket)
4656 return optionalPacket; /* Return packet for re-use by caller */
4659 /* Send all of the packets in the list in single datagram */
4661 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
4662 int istack, int moreFlag, struct clock *now,
4663 struct clock *retryTime, int resending)
4668 struct rx_connection *conn = call->conn;
4669 struct rx_peer *peer = conn->peer;
4671 MUTEX_ENTER(&peer->peer_lock);
4674 peer->reSends += len;
4675 MUTEX_ENTER(&rx_stats_mutex);
4676 rx_stats.dataPacketsSent += len;
4677 MUTEX_EXIT(&rx_stats_mutex);
4678 MUTEX_EXIT(&peer->peer_lock);
4680 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
4684 /* Set the packet flags and schedule the resend events */
4685 /* Only request an ack for the last packet in the list */
4686 for (i = 0; i < len; i++) {
4687 list[i]->retryTime = *retryTime;
4688 if (list[i]->header.serial) {
4689 /* Exponentially backoff retry times */
4690 if (list[i]->backoff < MAXBACKOFF) {
4691 /* so it can't stay == 0 */
4692 list[i]->backoff = (list[i]->backoff << 1) + 1;
4695 clock_Addmsec(&(list[i]->retryTime),
4696 ((afs_uint32) list[i]->backoff) << 8);
4699 /* Wait a little extra for the ack on the last packet */
4700 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
4701 clock_Addmsec(&(list[i]->retryTime), 400);
4704 /* Record the time sent */
4705 list[i]->timeSent = *now;
4707 /* Ask for an ack on retransmitted packets, on every other packet
4708 * if the peer doesn't support slow start. Ask for an ack on every
4709 * packet until the congestion window reaches the ack rate. */
4710 if (list[i]->header.serial) {
4712 MUTEX_ENTER(&rx_stats_mutex);
4713 rx_stats.dataPacketsReSent++;
4714 MUTEX_EXIT(&rx_stats_mutex);
4716 /* improved RTO calculation- not Karn */
4717 list[i]->firstSent = *now;
4718 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
4719 || (!(call->flags & RX_CALL_SLOW_START_OK)
4720 && (list[i]->header.seq & 1)))) {
4725 MUTEX_ENTER(&peer->peer_lock);
4729 MUTEX_ENTER(&rx_stats_mutex);
4730 rx_stats.dataPacketsSent++;
4731 MUTEX_EXIT(&rx_stats_mutex);
4732 MUTEX_EXIT(&peer->peer_lock);
4734 /* Tag this packet as not being the last in this group,
4735 * for the receiver's benefit */
4736 if (i < len - 1 || moreFlag) {
4737 list[i]->header.flags |= RX_MORE_PACKETS;
4740 /* Install the new retransmit time for the packet, and
4741 * record the time sent */
4742 list[i]->timeSent = *now;
4746 list[len - 1]->header.flags |= RX_REQUEST_ACK;
4749 /* Since we're about to send a data packet to the peer, it's
4750 * safe to nuke any scheduled end-of-packets ack */
4751 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4753 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
4754 MUTEX_EXIT(&call->lock);
4756 rxi_SendPacketList(call, conn, list, len, istack);
4758 rxi_SendPacket(call, conn, list[0], istack);
4760 MUTEX_ENTER(&call->lock);
4761 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
4763 /* Update last send time for this call (for keep-alive
4764 * processing), and for the connection (so that we can discover
4765 * idle connections) */
4766 conn->lastSendTime = call->lastSendTime = clock_Sec();
4769 /* When sending packets we need to follow these rules:
4770 * 1. Never send more than maxDgramPackets in a jumbogram.
4771 * 2. Never send a packet with more than two iovecs in a jumbogram.
4772 * 3. Never send a retransmitted packet in a jumbogram.
4773 * 4. Never send more than cwind/4 packets in a jumbogram
4774 * We always keep the last list we should have sent so we
4775 * can set the RX_MORE_PACKETS flags correctly.
4778 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
4779 int istack, struct clock *now, struct clock *retryTime,
4782 int i, cnt, lastCnt = 0;
4783 struct rx_packet **listP, **lastP = 0;
4784 struct rx_peer *peer = call->conn->peer;
4785 int morePackets = 0;
4787 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
4788 /* Does the current packet force us to flush the current list? */
4790 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
4791 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
4793 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
4795 /* If the call enters an error state stop sending, or if
4796 * we entered congestion recovery mode, stop sending */
4797 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
4805 /* Add the current packet to the list if it hasn't been acked.
4806 * Otherwise adjust the list pointer to skip the current packet. */
4807 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
4809 /* Do we need to flush the list? */
4810 if (cnt >= (int)peer->maxDgramPackets
4811 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
4812 || list[i]->header.serial
4813 || list[i]->length != RX_JUMBOBUFFERSIZE) {
4815 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
4816 retryTime, resending);
4817 /* If the call enters an error state stop sending, or if
4818 * we entered congestion recovery mode, stop sending */
4820 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
4825 listP = &list[i + 1];
4830 osi_Panic("rxi_SendList error");
4832 listP = &list[i + 1];
4836 /* Send the whole list when the call is in receive mode, when
4837 * the call is in eof mode, when we are in fast recovery mode,
4838 * and when we have the last packet */
4839 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
4840 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
4841 || (call->flags & RX_CALL_FAST_RECOVER)) {
4842 /* Check for the case where the current list contains
4843 * an acked packet. Since we always send retransmissions
4844 * in a separate packet, we only need to check the first
4845 * packet in the list */
4846 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
4850 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
4851 retryTime, resending);
4852 /* If the call enters an error state stop sending, or if
4853 * we entered congestion recovery mode, stop sending */
4854 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
4858 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
4861 } else if (lastCnt > 0) {
4862 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
4867 #ifdef RX_ENABLE_LOCKS
4868 /* Call rxi_Start, below, but with the call lock held. */
4870 rxi_StartUnlocked(struct rxevent *event, register struct rx_call *call,
4873 MUTEX_ENTER(&call->lock);
4874 rxi_Start(event, call, istack);
4875 MUTEX_EXIT(&call->lock);
4877 #endif /* RX_ENABLE_LOCKS */
4879 /* This routine is called when new packets are readied for
4880 * transmission and when retransmission may be necessary, or when the
4881 * transmission window or burst count are favourable. This should be
4882 * better optimized for new packets, the usual case, now that we've
4883 * got rid of queues of send packets. XXXXXXXXXXX */
4885 rxi_Start(struct rxevent *event, register struct rx_call *call, int istack)
4887 struct rx_packet *p;
4888 register struct rx_packet *nxp; /* Next pointer for queue_Scan */
4889 struct rx_peer *peer = call->conn->peer;
4890 struct clock now, retryTime;
4894 struct rx_packet **xmitList;
4897 /* If rxi_Start is being called as a result of a resend event,
4898 * then make sure that the event pointer is removed from the call
4899 * structure, since there is no longer a per-call retransmission
4901 if (event && event == call->resendEvent) {
4902 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
4903 call->resendEvent = NULL;
4905 if (queue_IsEmpty(&call->tq)) {
4909 /* Timeouts trigger congestion recovery */
4910 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4911 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4912 /* someone else is waiting to start recovery */
4915 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4916 while (call->flags & RX_CALL_TQ_BUSY) {
4917 call->flags |= RX_CALL_TQ_WAIT;
4918 #ifdef RX_ENABLE_LOCKS
4919 CV_WAIT(&call->cv_tq, &call->lock);
4920 #else /* RX_ENABLE_LOCKS */
4921 osi_rxSleep(&call->tq);
4922 #endif /* RX_ENABLE_LOCKS */
4924 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4925 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4926 call->flags |= RX_CALL_FAST_RECOVER;
4927 if (peer->maxDgramPackets > 1) {
4928 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4930 call->MTU = MIN(peer->natMTU, peer->maxMTU);
4932 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4933 call->nDgramPackets = 1;
4935 call->nextCwind = 1;
4938 MUTEX_ENTER(&peer->peer_lock);
4939 peer->MTU = call->MTU;
4940 peer->cwind = call->cwind;
4941 peer->nDgramPackets = 1;
4943 call->congestSeq = peer->congestSeq;
4944 MUTEX_EXIT(&peer->peer_lock);
4945 /* Clear retry times on packets. Otherwise, it's possible for
4946 * some packets in the queue to force resends at rates faster
4947 * than recovery rates.
4949 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
4950 if (!(p->flags & RX_PKTFLAG_ACKED)) {
4951 clock_Zero(&p->retryTime);
4956 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4957 MUTEX_ENTER(&rx_stats_mutex);
4958 rx_tq_debug.rxi_start_in_error++;
4959 MUTEX_EXIT(&rx_stats_mutex);
4964 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
4965 /* Get clock to compute the re-transmit time for any packets
4966 * in this burst. Note, if we back off, it's reasonable to
4967 * back off all of the packets in the same manner, even if
4968 * some of them have been retransmitted more times than more
4969 * recent additions */
4970 clock_GetTime(&now);
4971 retryTime = now; /* initialize before use */
4972 MUTEX_ENTER(&peer->peer_lock);
4973 clock_Add(&retryTime, &peer->timeout);
4974 MUTEX_EXIT(&peer->peer_lock);
4976 /* Send (or resend) any packets that need it, subject to
4977 * window restrictions and congestion burst control
4978 * restrictions. Ask for an ack on the last packet sent in
4979 * this burst. For now, we're relying upon the window being
4980 * considerably bigger than the largest number of packets that
4981 * are typically sent at once by one initial call to
4982 * rxi_Start. This is probably bogus (perhaps we should ask
4983 * for an ack when we're half way through the current
4984 * window?). Also, for non file transfer applications, this
4985 * may end up asking for an ack for every packet. Bogus. XXXX
4988 * But check whether we're here recursively, and let the other guy
4991 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4992 if (!(call->flags & RX_CALL_TQ_BUSY)) {
4993 call->flags |= RX_CALL_TQ_BUSY;
4995 call->flags &= ~RX_CALL_NEED_START;
4996 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4998 maxXmitPackets = MIN(call->twind, call->cwind);
4999 xmitList = (struct rx_packet **)
5000 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5001 if (xmitList == NULL)
5002 osi_Panic("rxi_Start, failed to allocate xmit list");
5003 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5004 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5005 /* We shouldn't be sending packets if a thread is waiting
5006 * to initiate congestion recovery */
5010 && (call->flags & RX_CALL_FAST_RECOVER)) {
5011 /* Only send one packet during fast recovery */
5014 if ((p->flags & RX_PKTFLAG_FREE)
5015 || (!queue_IsEnd(&call->tq, nxp)
5016 && (nxp->flags & RX_PKTFLAG_FREE))
5017 || (p == (struct rx_packet *)&rx_freePacketQueue)
5018 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5019 osi_Panic("rxi_Start: xmit queue clobbered");
5021 if (p->flags & RX_PKTFLAG_ACKED) {
5022 MUTEX_ENTER(&rx_stats_mutex);
5023 rx_stats.ignoreAckedPacket++;
5024 MUTEX_EXIT(&rx_stats_mutex);
5025 continue; /* Ignore this packet if it has been acknowledged */
5028 /* Turn off all flags except these ones, which are the same
5029 * on each transmission */
5030 p->header.flags &= RX_PRESET_FLAGS;
5032 if (p->header.seq >=
5033 call->tfirst + MIN((int)call->twind,
5034 (int)(call->nSoftAcked +
5036 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5037 /* Note: if we're waiting for more window space, we can
5038 * still send retransmits; hence we don't return here, but
5039 * break out to schedule a retransmit event */
5040 dpf(("call %d waiting for window",
5041 *(call->callNumber)));
5045 /* Transmit the packet if it needs to be sent. */
5046 if (!clock_Lt(&now, &p->retryTime)) {
5047 if (nXmitPackets == maxXmitPackets) {
5048 osi_Panic("rxi_Start: xmit list overflowed");
5050 xmitList[nXmitPackets++] = p;
5054 /* xmitList now hold pointers to all of the packets that are
5055 * ready to send. Now we loop to send the packets */
5056 if (nXmitPackets > 0) {
5057 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5058 &now, &retryTime, resending);
5061 maxXmitPackets * sizeof(struct rx_packet *));
5063 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5065 * TQ references no longer protected by this flag; they must remain
5066 * protected by the global lock.
5068 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5069 call->flags &= ~RX_CALL_TQ_BUSY;
5070 if (call->flags & RX_CALL_TQ_WAIT) {
5071 call->flags &= ~RX_CALL_TQ_WAIT;
5072 #ifdef RX_ENABLE_LOCKS
5073 CV_BROADCAST(&call->cv_tq);
5074 #else /* RX_ENABLE_LOCKS */
5075 osi_rxWakeup(&call->tq);
5076 #endif /* RX_ENABLE_LOCKS */
5081 /* We went into the error state while sending packets. Now is
5082 * the time to reset the call. This will also inform the using
5083 * process that the call is in an error state.
5085 MUTEX_ENTER(&rx_stats_mutex);
5086 rx_tq_debug.rxi_start_aborted++;
5087 MUTEX_EXIT(&rx_stats_mutex);
5088 call->flags &= ~RX_CALL_TQ_BUSY;
5089 if (call->flags & RX_CALL_TQ_WAIT) {
5090 call->flags &= ~RX_CALL_TQ_WAIT;
5091 #ifdef RX_ENABLE_LOCKS
5092 CV_BROADCAST(&call->cv_tq);
5093 #else /* RX_ENABLE_LOCKS */
5094 osi_rxWakeup(&call->tq);
5095 #endif /* RX_ENABLE_LOCKS */
5097 rxi_CallError(call, call->error);
5100 #ifdef RX_ENABLE_LOCKS
5101 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5102 register int missing;
5103 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5104 /* Some packets have received acks. If they all have, we can clear
5105 * the transmit queue.
5108 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5109 if (p->header.seq < call->tfirst
5110 && (p->flags & RX_PKTFLAG_ACKED)) {
5117 call->flags |= RX_CALL_TQ_CLEARME;
5119 #endif /* RX_ENABLE_LOCKS */
5120 /* Don't bother doing retransmits if the TQ is cleared. */
5121 if (call->flags & RX_CALL_TQ_CLEARME) {
5122 rxi_ClearTransmitQueue(call, 1);
5124 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5127 /* Always post a resend event, if there is anything in the
5128 * queue, and resend is possible. There should be at least
5129 * one unacknowledged packet in the queue ... otherwise none
5130 * of these packets should be on the queue in the first place.
5132 if (call->resendEvent) {
5133 /* Cancel the existing event and post a new one */
5134 rxevent_Cancel(call->resendEvent, call,
5135 RX_CALL_REFCOUNT_RESEND);
5138 /* The retry time is the retry time on the first unacknowledged
5139 * packet inside the current window */
5141 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5142 /* Don't set timers for packets outside the window */
5143 if (p->header.seq >= call->tfirst + call->twind) {
5147 if (!(p->flags & RX_PKTFLAG_ACKED)
5148 && !clock_IsZero(&p->retryTime)) {
5150 retryTime = p->retryTime;
5155 /* Post a new event to re-run rxi_Start when retries may be needed */
5156 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5157 #ifdef RX_ENABLE_LOCKS
5158 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5160 rxevent_Post(&retryTime, rxi_StartUnlocked,
5161 (void *)call, (void *)istack);
5162 #else /* RX_ENABLE_LOCKS */
5164 rxevent_Post(&retryTime, rxi_Start, (void *)call,
5166 #endif /* RX_ENABLE_LOCKS */
5169 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5170 } while (call->flags & RX_CALL_NEED_START);
5172 * TQ references no longer protected by this flag; they must remain
5173 * protected by the global lock.
5175 call->flags &= ~RX_CALL_TQ_BUSY;
5176 if (call->flags & RX_CALL_TQ_WAIT) {
5177 call->flags &= ~RX_CALL_TQ_WAIT;
5178 #ifdef RX_ENABLE_LOCKS
5179 CV_BROADCAST(&call->cv_tq);
5180 #else /* RX_ENABLE_LOCKS */
5181 osi_rxWakeup(&call->tq);
5182 #endif /* RX_ENABLE_LOCKS */
5185 call->flags |= RX_CALL_NEED_START;
5187 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5189 if (call->resendEvent) {
5190 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5195 /* Also adjusts the keep alive parameters for the call, to reflect
5196 * that we have just sent a packet (so keep alives aren't sent
5199 rxi_Send(register struct rx_call *call, register struct rx_packet *p,
5202 register struct rx_connection *conn = call->conn;
5204 /* Stamp each packet with the user supplied status */
5205 p->header.userStatus = call->localStatus;
5207 /* Allow the security object controlling this call's security to
5208 * make any last-minute changes to the packet */
5209 RXS_SendPacket(conn->securityObject, call, p);
5211 /* Since we're about to send SOME sort of packet to the peer, it's
5212 * safe to nuke any scheduled end-of-packets ack */
5213 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5215 /* Actually send the packet, filling in more connection-specific fields */
5216 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5217 MUTEX_EXIT(&call->lock);
5218 rxi_SendPacket(call, conn, p, istack);
5219 MUTEX_ENTER(&call->lock);
5220 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5222 /* Update last send time for this call (for keep-alive
5223 * processing), and for the connection (so that we can discover
5224 * idle connections) */
5225 conn->lastSendTime = call->lastSendTime = clock_Sec();
5229 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5230 * that things are fine. Also called periodically to guarantee that nothing
5231 * falls through the cracks (e.g. (error + dally) connections have keepalive
5232 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5234 * haveCTLock Set if calling from rxi_ReapConnections
5236 #ifdef RX_ENABLE_LOCKS
5238 rxi_CheckCall(register struct rx_call *call, int haveCTLock)
5239 #else /* RX_ENABLE_LOCKS */
5241 rxi_CheckCall(register struct rx_call *call)
5242 #endif /* RX_ENABLE_LOCKS */
5244 register struct rx_connection *conn = call->conn;
5246 afs_uint32 deadTime;
5248 #ifdef RX_GLOBAL_RXLOCK_KERNEL
5249 if (call->flags & RX_CALL_TQ_BUSY) {
5250 /* Call is active and will be reset by rxi_Start if it's
5251 * in an error state.
5256 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5258 (((afs_uint32) conn->secondsUntilDead << 10) +
5259 ((afs_uint32) conn->peer->rtt >> 3) +
5260 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5262 /* These are computed to the second (+- 1 second). But that's
5263 * good enough for these values, which should be a significant
5264 * number of seconds. */
5265 if (now > (call->lastReceiveTime + deadTime)) {
5266 if (call->state == RX_STATE_ACTIVE) {
5267 rxi_CallError(call, RX_CALL_DEAD);
5270 #ifdef RX_ENABLE_LOCKS
5271 /* Cancel pending events */
5272 rxevent_Cancel(call->delayedAckEvent, call,
5273 RX_CALL_REFCOUNT_DELAY);
5274 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5275 rxevent_Cancel(call->keepAliveEvent, call,
5276 RX_CALL_REFCOUNT_ALIVE);
5277 if (call->refCount == 0) {
5278 rxi_FreeCall(call, haveCTLock);
5282 #else /* RX_ENABLE_LOCKS */
5285 #endif /* RX_ENABLE_LOCKS */
5287 /* Non-active calls are destroyed if they are not responding
5288 * to pings; active calls are simply flagged in error, so the
5289 * attached process can die reasonably gracefully. */
5291 /* see if we have a non-activity timeout */
5292 if (call->startWait && conn->idleDeadTime
5293 && ((call->startWait + conn->idleDeadTime) < now)) {
5294 if (call->state == RX_STATE_ACTIVE) {
5295 rxi_CallError(call, RX_CALL_TIMEOUT);
5299 /* see if we have a hard timeout */
5300 if (conn->hardDeadTime
5301 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5302 if (call->state == RX_STATE_ACTIVE)
5303 rxi_CallError(call, RX_CALL_TIMEOUT);
5310 /* When a call is in progress, this routine is called occasionally to
5311 * make sure that some traffic has arrived (or been sent to) the peer.
5312 * If nothing has arrived in a reasonable amount of time, the call is
5313 * declared dead; if nothing has been sent for a while, we send a
5314 * keep-alive packet (if we're actually trying to keep the call alive)
5317 rxi_KeepAliveEvent(struct rxevent *event, register struct rx_call *call,
5320 struct rx_connection *conn;
5323 MUTEX_ENTER(&call->lock);
5324 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5325 if (event == call->keepAliveEvent)
5326 call->keepAliveEvent = NULL;
5329 #ifdef RX_ENABLE_LOCKS
5330 if (rxi_CheckCall(call, 0)) {
5331 MUTEX_EXIT(&call->lock);
5334 #else /* RX_ENABLE_LOCKS */
5335 if (rxi_CheckCall(call))
5337 #endif /* RX_ENABLE_LOCKS */
5339 /* Don't try to keep alive dallying calls */
5340 if (call->state == RX_STATE_DALLY) {
5341 MUTEX_EXIT(&call->lock);
5346 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
5347 /* Don't try to send keepalives if there is unacknowledged data */
5348 /* the rexmit code should be good enough, this little hack
5349 * doesn't quite work XXX */
5350 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5352 rxi_ScheduleKeepAliveEvent(call);
5353 MUTEX_EXIT(&call->lock);
5358 rxi_ScheduleKeepAliveEvent(register struct rx_call *call)
5360 if (!call->keepAliveEvent) {
5362 clock_GetTime(&when);
5363 when.sec += call->conn->secondsUntilPing;
5364 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5365 call->keepAliveEvent =
5366 rxevent_Post(&when, rxi_KeepAliveEvent, call, 0);
5370 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5372 rxi_KeepAliveOn(register struct rx_call *call)
5374 /* Pretend last packet received was received now--i.e. if another
5375 * packet isn't received within the keep alive time, then the call
5376 * will die; Initialize last send time to the current time--even
5377 * if a packet hasn't been sent yet. This will guarantee that a
5378 * keep-alive is sent within the ping time */
5379 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5380 rxi_ScheduleKeepAliveEvent(call);
5383 /* This routine is called to send connection abort messages
5384 * that have been delayed to throttle looping clients. */
5386 rxi_SendDelayedConnAbort(struct rxevent *event,
5387 register struct rx_connection *conn, char *dummy)
5390 struct rx_packet *packet;
5392 MUTEX_ENTER(&conn->conn_data_lock);
5393 conn->delayedAbortEvent = NULL;
5394 error = htonl(conn->error);
5396 MUTEX_EXIT(&conn->conn_data_lock);
5397 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5400 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5401 RX_PACKET_TYPE_ABORT, (char *)&error,
5403 rxi_FreePacket(packet);
5407 /* This routine is called to send call abort messages
5408 * that have been delayed to throttle looping clients. */
5410 rxi_SendDelayedCallAbort(struct rxevent *event, register struct rx_call *call,
5414 struct rx_packet *packet;
5416 MUTEX_ENTER(&call->lock);
5417 call->delayedAbortEvent = NULL;
5418 error = htonl(call->error);
5420 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5423 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5424 (char *)&error, sizeof(error), 0);
5425 rxi_FreePacket(packet);
5427 MUTEX_EXIT(&call->lock);
5430 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5431 * seconds) to ask the client to authenticate itself. The routine
5432 * issues a challenge to the client, which is obtained from the
5433 * security object associated with the connection */
5435 rxi_ChallengeEvent(struct rxevent *event, register struct rx_connection *conn,
5438 int tries = (int)atries;
5439 conn->challengeEvent = NULL;
5440 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5441 register struct rx_packet *packet;
5445 /* We've failed to authenticate for too long.
5446 * Reset any calls waiting for authentication;
5447 * they are all in RX_STATE_PRECALL.
5451 MUTEX_ENTER(&conn->conn_call_lock);
5452 for (i = 0; i < RX_MAXCALLS; i++) {
5453 struct rx_call *call = conn->call[i];
5455 MUTEX_ENTER(&call->lock);
5456 if (call->state == RX_STATE_PRECALL) {
5457 rxi_CallError(call, RX_CALL_DEAD);
5458 rxi_SendCallAbort(call, NULL, 0, 0);
5460 MUTEX_EXIT(&call->lock);
5463 MUTEX_EXIT(&conn->conn_call_lock);
5467 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5469 /* If there's no packet available, do this later. */
5470 RXS_GetChallenge(conn->securityObject, conn, packet);
5471 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5472 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5473 rxi_FreePacket(packet);
5475 clock_GetTime(&when);
5476 when.sec += RX_CHALLENGE_TIMEOUT;
5477 conn->challengeEvent =
5478 rxevent_Post(&when, rxi_ChallengeEvent, conn,
5479 (void *)(tries - 1));
5483 /* Call this routine to start requesting the client to authenticate
5484 * itself. This will continue until authentication is established,
5485 * the call times out, or an invalid response is returned. The
5486 * security object associated with the connection is asked to create
5487 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5488 * defined earlier. */
5490 rxi_ChallengeOn(register struct rx_connection *conn)
5492 if (!conn->challengeEvent) {
5493 RXS_CreateChallenge(conn->securityObject, conn);
5494 rxi_ChallengeEvent(NULL, conn, (void *)RX_CHALLENGE_MAXTRIES);
5499 /* Compute round trip time of the packet provided, in *rttp.
5502 /* rxi_ComputeRoundTripTime is called with peer locked. */
5503 /* sentp and/or peer may be null */
5505 rxi_ComputeRoundTripTime(register struct rx_packet *p,
5506 register struct clock *sentp,
5507 register struct rx_peer *peer)
5509 struct clock thisRtt, *rttp = &thisRtt;
5511 #if defined(AFS_ALPHA_LINUX22_ENV) && defined(AFS_PTHREAD_ENV) && !defined(KERNEL)
5512 /* making year 2038 bugs to get this running now - stroucki */
5513 struct timeval temptime;
5515 register int rtt_timeout;
5517 #if defined(AFS_ALPHA_LINUX20_ENV) && defined(AFS_PTHREAD_ENV) && !defined(KERNEL)
5518 /* yet again. This was the worst Heisenbug of the port - stroucki */
5519 clock_GetTime(&temptime);
5520 rttp->sec = (afs_int32) temptime.tv_sec;
5521 rttp->usec = (afs_int32) temptime.tv_usec;
5523 clock_GetTime(rttp);
5525 if (clock_Lt(rttp, sentp)) {
5527 return; /* somebody set the clock back, don't count this time. */
5529 clock_Sub(rttp, sentp);
5530 MUTEX_ENTER(&rx_stats_mutex);
5531 if (clock_Lt(rttp, &rx_stats.minRtt))
5532 rx_stats.minRtt = *rttp;
5533 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5534 if (rttp->sec > 60) {
5535 MUTEX_EXIT(&rx_stats_mutex);
5536 return; /* somebody set the clock ahead */
5538 rx_stats.maxRtt = *rttp;
5540 clock_Add(&rx_stats.totalRtt, rttp);
5541 rx_stats.nRttSamples++;
5542 MUTEX_EXIT(&rx_stats_mutex);
5544 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
5546 /* Apply VanJacobson round-trip estimations */
5551 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
5552 * srtt is stored as fixed point with 3 bits after the binary
5553 * point (i.e., scaled by 8). The following magic is
5554 * equivalent to the smoothing algorithm in rfc793 with an
5555 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
5556 * srtt*8 = srtt*8 + rtt - srtt
5557 * srtt = srtt + rtt/8 - srtt/8
5560 delta = MSEC(rttp) - (peer->rtt >> 3);
5564 * We accumulate a smoothed rtt variance (actually, a smoothed
5565 * mean difference), then set the retransmit timer to smoothed
5566 * rtt + 4 times the smoothed variance (was 2x in van's original
5567 * paper, but 4x works better for me, and apparently for him as
5569 * rttvar is stored as
5570 * fixed point with 2 bits after the binary point (scaled by
5571 * 4). The following is equivalent to rfc793 smoothing with
5572 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
5573 * replaces rfc793's wired-in beta.
5574 * dev*4 = dev*4 + (|actual - expected| - dev)
5580 delta -= (peer->rtt_dev >> 2);
5581 peer->rtt_dev += delta;
5583 /* I don't have a stored RTT so I start with this value. Since I'm
5584 * probably just starting a call, and will be pushing more data down
5585 * this, I expect congestion to increase rapidly. So I fudge a
5586 * little, and I set deviance to half the rtt. In practice,
5587 * deviance tends to approach something a little less than
5588 * half the smoothed rtt. */
5589 peer->rtt = (MSEC(rttp) << 3) + 8;
5590 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
5592 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
5593 * the other of these connections is usually in a user process, and can
5594 * be switched and/or swapped out. So on fast, reliable networks, the
5595 * timeout would otherwise be too short.
5597 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
5598 clock_Zero(&(peer->timeout));
5599 clock_Addmsec(&(peer->timeout), rtt_timeout);
5601 dpf(("rxi_ComputeRoundTripTime(rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%0.3d sec)\n", MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
5605 /* Find all server connections that have not been active for a long time, and
5608 rxi_ReapConnections(void)
5611 clock_GetTime(&now);
5613 /* Find server connection structures that haven't been used for
5614 * greater than rx_idleConnectionTime */
5616 struct rx_connection **conn_ptr, **conn_end;
5617 int i, havecalls = 0;
5618 MUTEX_ENTER(&rx_connHashTable_lock);
5619 for (conn_ptr = &rx_connHashTable[0], conn_end =
5620 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
5622 struct rx_connection *conn, *next;
5623 struct rx_call *call;
5627 for (conn = *conn_ptr; conn; conn = next) {
5628 /* XXX -- Shouldn't the connection be locked? */
5631 for (i = 0; i < RX_MAXCALLS; i++) {
5632 call = conn->call[i];
5635 MUTEX_ENTER(&call->lock);
5636 #ifdef RX_ENABLE_LOCKS
5637 result = rxi_CheckCall(call, 1);
5638 #else /* RX_ENABLE_LOCKS */
5639 result = rxi_CheckCall(call);
5640 #endif /* RX_ENABLE_LOCKS */
5641 MUTEX_EXIT(&call->lock);
5643 /* If CheckCall freed the call, it might
5644 * have destroyed the connection as well,
5645 * which screws up the linked lists.
5651 if (conn->type == RX_SERVER_CONNECTION) {
5652 /* This only actually destroys the connection if
5653 * there are no outstanding calls */
5654 MUTEX_ENTER(&conn->conn_data_lock);
5655 if (!havecalls && !conn->refCount
5656 && ((conn->lastSendTime + rx_idleConnectionTime) <
5658 conn->refCount++; /* it will be decr in rx_DestroyConn */
5659 MUTEX_EXIT(&conn->conn_data_lock);
5660 #ifdef RX_ENABLE_LOCKS
5661 rxi_DestroyConnectionNoLock(conn);
5662 #else /* RX_ENABLE_LOCKS */
5663 rxi_DestroyConnection(conn);
5664 #endif /* RX_ENABLE_LOCKS */
5666 #ifdef RX_ENABLE_LOCKS
5668 MUTEX_EXIT(&conn->conn_data_lock);
5670 #endif /* RX_ENABLE_LOCKS */
5674 #ifdef RX_ENABLE_LOCKS
5675 while (rx_connCleanup_list) {
5676 struct rx_connection *conn;
5677 conn = rx_connCleanup_list;
5678 rx_connCleanup_list = rx_connCleanup_list->next;
5679 MUTEX_EXIT(&rx_connHashTable_lock);
5680 rxi_CleanupConnection(conn);
5681 MUTEX_ENTER(&rx_connHashTable_lock);
5683 MUTEX_EXIT(&rx_connHashTable_lock);
5684 #endif /* RX_ENABLE_LOCKS */
5687 /* Find any peer structures that haven't been used (haven't had an
5688 * associated connection) for greater than rx_idlePeerTime */
5690 struct rx_peer **peer_ptr, **peer_end;
5692 MUTEX_ENTER(&rx_rpc_stats);
5693 MUTEX_ENTER(&rx_peerHashTable_lock);
5694 for (peer_ptr = &rx_peerHashTable[0], peer_end =
5695 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
5697 struct rx_peer *peer, *next, *prev;
5698 for (prev = peer = *peer_ptr; peer; peer = next) {
5700 code = MUTEX_TRYENTER(&peer->peer_lock);
5701 if ((code) && (peer->refCount == 0)
5702 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
5703 rx_interface_stat_p rpc_stat, nrpc_stat;
5705 MUTEX_EXIT(&peer->peer_lock);
5706 MUTEX_DESTROY(&peer->peer_lock);
5708 (&peer->rpcStats, rpc_stat, nrpc_stat,
5709 rx_interface_stat)) {
5710 unsigned int num_funcs;
5713 queue_Remove(&rpc_stat->queue_header);
5714 queue_Remove(&rpc_stat->all_peers);
5715 num_funcs = rpc_stat->stats[0].func_total;
5717 sizeof(rx_interface_stat_t) +
5718 rpc_stat->stats[0].func_total *
5719 sizeof(rx_function_entry_v1_t);
5721 rxi_Free(rpc_stat, space);
5722 rxi_rpc_peer_stat_cnt -= num_funcs;
5725 MUTEX_ENTER(&rx_stats_mutex);
5726 rx_stats.nPeerStructs--;
5727 MUTEX_EXIT(&rx_stats_mutex);
5728 if (prev == *peer_ptr) {
5735 MUTEX_EXIT(&peer->peer_lock);
5741 MUTEX_EXIT(&rx_peerHashTable_lock);
5742 MUTEX_EXIT(&rx_rpc_stats);
5745 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
5746 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
5747 * GC, just below. Really, we shouldn't have to keep moving packets from
5748 * one place to another, but instead ought to always know if we can
5749 * afford to hold onto a packet in its particular use. */
5750 MUTEX_ENTER(&rx_freePktQ_lock);
5751 if (rx_waitingForPackets) {
5752 rx_waitingForPackets = 0;
5753 #ifdef RX_ENABLE_LOCKS
5754 CV_BROADCAST(&rx_waitingForPackets_cv);
5756 osi_rxWakeup(&rx_waitingForPackets);
5759 MUTEX_EXIT(&rx_freePktQ_lock);
5761 now.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
5762 rxevent_Post(&now, rxi_ReapConnections, 0, 0);
5766 /* rxs_Release - This isn't strictly necessary but, since the macro name from
5767 * rx.h is sort of strange this is better. This is called with a security
5768 * object before it is discarded. Each connection using a security object has
5769 * its own refcount to the object so it won't actually be freed until the last
5770 * connection is destroyed.
5772 * This is the only rxs module call. A hold could also be written but no one
5776 rxs_Release(struct rx_securityClass *aobj)
5778 return RXS_Close(aobj);
5782 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
5783 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
5784 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
5785 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
5787 /* Adjust our estimate of the transmission rate to this peer, given
5788 * that the packet p was just acked. We can adjust peer->timeout and
5789 * call->twind. Pragmatically, this is called
5790 * only with packets of maximal length.
5791 * Called with peer and call locked.
5795 rxi_ComputeRate(register struct rx_peer *peer, register struct rx_call *call,
5796 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
5798 afs_int32 xferSize, xferMs;
5799 register afs_int32 minTime;
5802 /* Count down packets */
5803 if (peer->rateFlag > 0)
5805 /* Do nothing until we're enabled */
5806 if (peer->rateFlag != 0)
5811 /* Count only when the ack seems legitimate */
5812 switch (ackReason) {
5813 case RX_ACK_REQUESTED:
5815 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
5819 case RX_ACK_PING_RESPONSE:
5820 if (p) /* want the response to ping-request, not data send */
5822 clock_GetTime(&newTO);
5823 if (clock_Gt(&newTO, &call->pingRequestTime)) {
5824 clock_Sub(&newTO, &call->pingRequestTime);
5825 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
5829 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
5836 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %lu.%06lu, rtt %u, ps %u)", ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"), xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
5838 /* Track only packets that are big enough. */
5839 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
5843 /* absorb RTT data (in milliseconds) for these big packets */
5844 if (peer->smRtt == 0) {
5845 peer->smRtt = xferMs;
5847 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
5852 if (peer->countDown) {
5856 peer->countDown = 10; /* recalculate only every so often */
5858 /* In practice, we can measure only the RTT for full packets,
5859 * because of the way Rx acks the data that it receives. (If it's
5860 * smaller than a full packet, it often gets implicitly acked
5861 * either by the call response (from a server) or by the next call
5862 * (from a client), and either case confuses transmission times
5863 * with processing times.) Therefore, replace the above
5864 * more-sophisticated processing with a simpler version, where the
5865 * smoothed RTT is kept for full-size packets, and the time to
5866 * transmit a windowful of full-size packets is simply RTT *
5867 * windowSize. Again, we take two steps:
5868 - ensure the timeout is large enough for a single packet's RTT;
5869 - ensure that the window is small enough to fit in the desired timeout.*/
5871 /* First, the timeout check. */
5872 minTime = peer->smRtt;
5873 /* Get a reasonable estimate for a timeout period */
5875 newTO.sec = minTime / 1000;
5876 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
5878 /* Increase the timeout period so that we can always do at least
5879 * one packet exchange */
5880 if (clock_Gt(&newTO, &peer->timeout)) {
5882 dpf(("CONG peer %lx/%u: timeout %lu.%06lu ==> %lu.%06lu (rtt %u, ps %u)", ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec, newTO.sec, newTO.usec, peer->smRtt, peer->packetSize));
5884 peer->timeout = newTO;
5887 /* Now, get an estimate for the transmit window size. */
5888 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
5889 /* Now, convert to the number of full packets that could fit in a
5890 * reasonable fraction of that interval */
5891 minTime /= (peer->smRtt << 1);
5892 xferSize = minTime; /* (make a copy) */
5894 /* Now clamp the size to reasonable bounds. */
5897 else if (minTime > rx_Window)
5898 minTime = rx_Window;
5899 /* if (minTime != peer->maxWindow) {
5900 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
5901 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
5902 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
5904 peer->maxWindow = minTime;
5905 elide... call->twind = minTime;
5909 /* Cut back on the peer timeout if it had earlier grown unreasonably.
5910 * Discern this by calculating the timeout necessary for rx_Window
5912 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
5913 /* calculate estimate for transmission interval in milliseconds */
5914 minTime = rx_Window * peer->smRtt;
5915 if (minTime < 1000) {
5916 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
5917 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
5918 peer->timeout.usec, peer->smRtt, peer->packetSize));
5920 newTO.sec = 0; /* cut back on timeout by half a second */
5921 newTO.usec = 500000;
5922 clock_Sub(&peer->timeout, &newTO);
5927 } /* end of rxi_ComputeRate */
5928 #endif /* ADAPT_WINDOW */
5936 /* Don't call this debugging routine directly; use dpf */
5938 rxi_DebugPrint(char *format, int a1, int a2, int a3, int a4, int a5, int a6,
5939 int a7, int a8, int a9, int a10, int a11, int a12, int a13,
5943 clock_GetTime(&now);
5944 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
5945 (unsigned int)now.usec / 1000);
5946 fprintf(rx_Log, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12,
5954 * This function is used to process the rx_stats structure that is local
5955 * to a process as well as an rx_stats structure received from a remote
5956 * process (via rxdebug). Therefore, it needs to do minimal version
5960 rx_PrintTheseStats(FILE * file, struct rx_stats *s, int size,
5961 afs_int32 freePackets, char version)
5965 if (size != sizeof(struct rx_stats)) {
5967 "Unexpected size of stats structure: was %d, expected %d\n",
5968 size, sizeof(struct rx_stats));
5971 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
5974 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
5975 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
5976 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
5977 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
5978 s->specialPktAllocFailures);
5980 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
5981 s->receivePktAllocFailures, s->sendPktAllocFailures,
5982 s->specialPktAllocFailures);
5986 " greedy %d, " "bogusReads %d (last from host %x), "
5987 "noPackets %d, " "noBuffers %d, " "selects %d, "
5988 "sendSelects %d\n", s->socketGreedy, s->bogusPacketOnRead,
5989 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
5990 s->selects, s->sendSelects);
5992 fprintf(file, " packets read: ");
5993 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
5994 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsRead[i]);
5996 fprintf(file, "\n");
5999 " other read counters: data %d, " "ack %d, " "dup %d "
6000 "spurious %d " "dally %d\n", s->dataPacketsRead,
6001 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6002 s->ignorePacketDally);
6004 fprintf(file, " packets sent: ");
6005 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6006 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsSent[i]);
6008 fprintf(file, "\n");
6011 " other send counters: ack %d, " "data %d (not resends), "
6012 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6013 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6014 s->dataPacketsPushed, s->ignoreAckedPacket);
6017 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6018 s->netSendFailures, (int)s->fatalErrors);
6020 if (s->nRttSamples) {
6021 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6022 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6024 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6025 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6029 " %d server connections, " "%d client connections, "
6030 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6031 s->nServerConns, s->nClientConns, s->nPeerStructs,
6032 s->nCallStructs, s->nFreeCallStructs);
6034 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6035 fprintf(file, " %d clock updates\n", clock_nUpdates);
6040 /* for backward compatibility */
6042 rx_PrintStats(FILE * file)
6044 MUTEX_ENTER(&rx_stats_mutex);
6045 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6047 MUTEX_EXIT(&rx_stats_mutex);
6051 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6053 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6054 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6055 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6058 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6059 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6060 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6063 " Packet size %d, " "max in packet skew %d, "
6064 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6065 (int)peer->outPacketSkew);
6068 #ifdef AFS_PTHREAD_ENV
6070 * This mutex protects the following static variables:
6074 #define LOCK_RX_DEBUG assert(pthread_mutex_lock(&rx_debug_mutex)==0);
6075 #define UNLOCK_RX_DEBUG assert(pthread_mutex_unlock(&rx_debug_mutex)==0);
6077 #define LOCK_RX_DEBUG
6078 #define UNLOCK_RX_DEBUG
6079 #endif /* AFS_PTHREAD_ENV */
6082 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6083 u_char type, void *inputData, size_t inputLength,
6084 void *outputData, size_t outputLength)
6086 static afs_int32 counter = 100;
6088 struct rx_header theader;
6090 register afs_int32 code;
6092 struct sockaddr_in taddr, faddr;
6097 endTime = time(0) + 20; /* try for 20 seconds */
6098 LOCK_RX_DEBUG counter++;
6099 UNLOCK_RX_DEBUG tp = &tbuffer[sizeof(struct rx_header)];
6100 taddr.sin_family = AF_INET;
6101 taddr.sin_port = remotePort;
6102 taddr.sin_addr.s_addr = remoteAddr;
6103 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6104 taddr.sin_len = sizeof(struct sockaddr_in);
6107 memset(&theader, 0, sizeof(theader));
6108 theader.epoch = htonl(999);
6110 theader.callNumber = htonl(counter);
6113 theader.type = type;
6114 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6115 theader.serviceId = 0;
6117 memcpy(tbuffer, &theader, sizeof(theader));
6118 memcpy(tp, inputData, inputLength);
6120 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6121 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6123 /* see if there's a packet available */
6125 FD_SET(socket, &imask);
6128 code = select(socket + 1, &imask, 0, 0, &tv);
6130 /* now receive a packet */
6131 faddrLen = sizeof(struct sockaddr_in);
6133 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6134 (struct sockaddr *)&faddr, &faddrLen);
6136 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6137 if (counter == ntohl(theader.callNumber))
6141 /* see if we've timed out */
6142 if (endTime < time(0))
6145 code -= sizeof(struct rx_header);
6146 if (code > outputLength)
6147 code = outputLength;
6148 memcpy(outputData, tp, code);
6153 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6154 afs_uint16 remotePort, struct rx_debugStats * stat,
6155 afs_uint32 * supportedValues)
6157 struct rx_debugIn in;
6160 *supportedValues = 0;
6161 in.type = htonl(RX_DEBUGI_GETSTATS);
6164 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6165 &in, sizeof(in), stat, sizeof(*stat));
6168 * If the call was successful, fixup the version and indicate
6169 * what contents of the stat structure are valid.
6170 * Also do net to host conversion of fields here.
6174 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6175 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6177 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6178 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6180 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6181 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6183 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6184 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6186 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6187 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6189 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6190 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6192 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6193 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6196 stat->nFreePackets = ntohl(stat->nFreePackets);
6197 stat->packetReclaims = ntohl(stat->packetReclaims);
6198 stat->callsExecuted = ntohl(stat->callsExecuted);
6199 stat->nWaiting = ntohl(stat->nWaiting);
6200 stat->idleThreads = ntohl(stat->idleThreads);
6207 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6208 afs_uint16 remotePort, struct rx_stats * stat,
6209 afs_uint32 * supportedValues)
6211 struct rx_debugIn in;
6212 afs_int32 *lp = (afs_int32 *) stat;
6217 * supportedValues is currently unused, but added to allow future
6218 * versioning of this function.
6221 *supportedValues = 0;
6222 in.type = htonl(RX_DEBUGI_RXSTATS);
6224 memset(stat, 0, sizeof(*stat));
6226 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6227 &in, sizeof(in), stat, sizeof(*stat));
6232 * Do net to host conversion here
6235 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6244 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6245 afs_uint16 remotePort, size_t version_length,
6249 return MakeDebugCall(socket, remoteAddr, remotePort,
6250 RX_PACKET_TYPE_VERSION, a, 1, version,
6255 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6256 afs_uint16 remotePort, afs_int32 * nextConnection,
6257 int allConnections, afs_uint32 debugSupportedValues,
6258 struct rx_debugConn * conn,
6259 afs_uint32 * supportedValues)
6261 struct rx_debugIn in;
6266 * supportedValues is currently unused, but added to allow future
6267 * versioning of this function.
6270 *supportedValues = 0;
6271 if (allConnections) {
6272 in.type = htonl(RX_DEBUGI_GETALLCONN);
6274 in.type = htonl(RX_DEBUGI_GETCONN);
6276 in.index = htonl(*nextConnection);
6277 memset(conn, 0, sizeof(*conn));
6279 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6280 &in, sizeof(in), conn, sizeof(*conn));
6283 *nextConnection += 1;
6286 * Convert old connection format to new structure.
6289 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6290 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6291 #define MOVEvL(a) (conn->a = vL->a)
6293 /* any old or unrecognized version... */
6294 for (i = 0; i < RX_MAXCALLS; i++) {
6295 MOVEvL(callState[i]);
6296 MOVEvL(callMode[i]);
6297 MOVEvL(callFlags[i]);
6298 MOVEvL(callOther[i]);
6300 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6301 MOVEvL(secStats.type);
6302 MOVEvL(secStats.level);
6303 MOVEvL(secStats.flags);
6304 MOVEvL(secStats.expires);
6305 MOVEvL(secStats.packetsReceived);
6306 MOVEvL(secStats.packetsSent);
6307 MOVEvL(secStats.bytesReceived);
6308 MOVEvL(secStats.bytesSent);
6313 * Do net to host conversion here
6315 * I don't convert host or port since we are most likely
6316 * going to want these in NBO.
6318 conn->cid = ntohl(conn->cid);
6319 conn->serial = ntohl(conn->serial);
6320 for (i = 0; i < RX_MAXCALLS; i++) {
6321 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6323 conn->error = ntohl(conn->error);
6324 conn->secStats.flags = ntohl(conn->secStats.flags);
6325 conn->secStats.expires = ntohl(conn->secStats.expires);
6326 conn->secStats.packetsReceived =
6327 ntohl(conn->secStats.packetsReceived);
6328 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6329 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6330 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6331 conn->epoch = ntohl(conn->epoch);
6332 conn->natMTU = ntohl(conn->natMTU);
6339 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6340 afs_uint16 remotePort, afs_int32 * nextPeer,
6341 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6342 afs_uint32 * supportedValues)
6344 struct rx_debugIn in;
6348 * supportedValues is currently unused, but added to allow future
6349 * versioning of this function.
6352 *supportedValues = 0;
6353 in.type = htonl(RX_DEBUGI_GETPEER);
6354 in.index = htonl(*nextPeer);
6355 memset(peer, 0, sizeof(*peer));
6357 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6358 &in, sizeof(in), peer, sizeof(*peer));
6364 * Do net to host conversion here
6366 * I don't convert host or port since we are most likely
6367 * going to want these in NBO.
6369 peer->ifMTU = ntohs(peer->ifMTU);
6370 peer->idleWhen = ntohl(peer->idleWhen);
6371 peer->refCount = ntohs(peer->refCount);
6372 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6373 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6374 peer->rtt = ntohl(peer->rtt);
6375 peer->rtt_dev = ntohl(peer->rtt_dev);
6376 peer->timeout.sec = ntohl(peer->timeout.sec);
6377 peer->timeout.usec = ntohl(peer->timeout.usec);
6378 peer->nSent = ntohl(peer->nSent);
6379 peer->reSends = ntohl(peer->reSends);
6380 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6381 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6382 peer->rateFlag = ntohl(peer->rateFlag);
6383 peer->natMTU = ntohs(peer->natMTU);
6384 peer->maxMTU = ntohs(peer->maxMTU);
6385 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6386 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
6387 peer->MTU = ntohs(peer->MTU);
6388 peer->cwind = ntohs(peer->cwind);
6389 peer->nDgramPackets = ntohs(peer->nDgramPackets);
6390 peer->congestSeq = ntohs(peer->congestSeq);
6391 peer->bytesSent.high = ntohl(peer->bytesSent.high);
6392 peer->bytesSent.low = ntohl(peer->bytesSent.low);
6393 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
6394 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
6399 #endif /* RXDEBUG */
6404 struct rx_serverQueueEntry *np;
6407 register struct rx_call *call;
6408 register struct rx_serverQueueEntry *sq;
6411 LOCK_RX_INIT if (rxinit_status == 1) {
6412 UNLOCK_RX_INIT return; /* Already shutdown. */
6416 #ifndef AFS_PTHREAD_ENV
6417 FD_ZERO(&rx_selectMask);
6418 #endif /* AFS_PTHREAD_ENV */
6419 rxi_dataQuota = RX_MAX_QUOTA;
6420 #ifndef AFS_PTHREAD_ENV
6422 #endif /* AFS_PTHREAD_ENV */
6425 #ifndef AFS_PTHREAD_ENV
6426 #ifndef AFS_USE_GETTIMEOFDAY
6428 #endif /* AFS_USE_GETTIMEOFDAY */
6429 #endif /* AFS_PTHREAD_ENV */
6431 while (!queue_IsEmpty(&rx_freeCallQueue)) {
6432 call = queue_First(&rx_freeCallQueue, rx_call);
6434 rxi_Free(call, sizeof(struct rx_call));
6437 while (!queue_IsEmpty(&rx_idleServerQueue)) {
6438 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
6444 struct rx_peer **peer_ptr, **peer_end;
6445 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6446 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6448 struct rx_peer *peer, *next;
6449 for (peer = *peer_ptr; peer; peer = next) {
6450 rx_interface_stat_p rpc_stat, nrpc_stat;
6453 (&peer->rpcStats, rpc_stat, nrpc_stat,
6454 rx_interface_stat)) {
6455 unsigned int num_funcs;
6458 queue_Remove(&rpc_stat->queue_header);
6459 queue_Remove(&rpc_stat->all_peers);
6460 num_funcs = rpc_stat->stats[0].func_total;
6462 sizeof(rx_interface_stat_t) +
6463 rpc_stat->stats[0].func_total *
6464 sizeof(rx_function_entry_v1_t);
6466 rxi_Free(rpc_stat, space);
6467 MUTEX_ENTER(&rx_rpc_stats);
6468 rxi_rpc_peer_stat_cnt -= num_funcs;
6469 MUTEX_EXIT(&rx_rpc_stats);
6473 MUTEX_ENTER(&rx_stats_mutex);
6474 rx_stats.nPeerStructs--;
6475 MUTEX_EXIT(&rx_stats_mutex);
6479 for (i = 0; i < RX_MAX_SERVICES; i++) {
6481 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
6483 for (i = 0; i < rx_hashTableSize; i++) {
6484 register struct rx_connection *tc, *ntc;
6485 MUTEX_ENTER(&rx_connHashTable_lock);
6486 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
6488 for (j = 0; j < RX_MAXCALLS; j++) {
6490 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
6493 rxi_Free(tc, sizeof(*tc));
6495 MUTEX_EXIT(&rx_connHashTable_lock);
6498 MUTEX_ENTER(&freeSQEList_lock);
6500 while ((np = rx_FreeSQEList)) {
6501 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
6502 MUTEX_DESTROY(&np->lock);
6503 rxi_Free(np, sizeof(*np));
6506 MUTEX_EXIT(&freeSQEList_lock);
6507 MUTEX_DESTROY(&freeSQEList_lock);
6508 MUTEX_DESTROY(&rx_freeCallQueue_lock);
6509 MUTEX_DESTROY(&rx_connHashTable_lock);
6510 MUTEX_DESTROY(&rx_peerHashTable_lock);
6511 MUTEX_DESTROY(&rx_serverPool_lock);
6513 osi_Free(rx_connHashTable,
6514 rx_hashTableSize * sizeof(struct rx_connection *));
6515 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
6517 UNPIN(rx_connHashTable,
6518 rx_hashTableSize * sizeof(struct rx_connection *));
6519 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
6521 rxi_FreeAllPackets();
6523 MUTEX_ENTER(&rx_stats_mutex);
6524 rxi_dataQuota = RX_MAX_QUOTA;
6525 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
6526 MUTEX_EXIT(&rx_stats_mutex);
6531 #ifdef RX_ENABLE_LOCKS
6533 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
6535 if (!MUTEX_ISMINE(lockaddr))
6536 osi_Panic("Lock not held: %s", msg);
6538 #endif /* RX_ENABLE_LOCKS */
6543 * Routines to implement connection specific data.
6547 rx_KeyCreate(rx_destructor_t rtn)
6550 MUTEX_ENTER(&rxi_keyCreate_lock);
6551 key = rxi_keyCreate_counter++;
6552 rxi_keyCreate_destructor = (rx_destructor_t *)
6553 realloc((void *)rxi_keyCreate_destructor,
6554 (key + 1) * sizeof(rx_destructor_t));
6555 rxi_keyCreate_destructor[key] = rtn;
6556 MUTEX_EXIT(&rxi_keyCreate_lock);
6561 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
6564 MUTEX_ENTER(&conn->conn_data_lock);
6565 if (!conn->specific) {
6566 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
6567 for (i = 0; i < key; i++)
6568 conn->specific[i] = NULL;
6569 conn->nSpecific = key + 1;
6570 conn->specific[key] = ptr;
6571 } else if (key >= conn->nSpecific) {
6572 conn->specific = (void **)
6573 realloc(conn->specific, (key + 1) * sizeof(void *));
6574 for (i = conn->nSpecific; i < key; i++)
6575 conn->specific[i] = NULL;
6576 conn->nSpecific = key + 1;
6577 conn->specific[key] = ptr;
6579 if (conn->specific[key] && rxi_keyCreate_destructor[key])
6580 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
6581 conn->specific[key] = ptr;
6583 MUTEX_EXIT(&conn->conn_data_lock);
6587 rx_GetSpecific(struct rx_connection *conn, int key)
6590 MUTEX_ENTER(&conn->conn_data_lock);
6591 if (key >= conn->nSpecific)
6594 ptr = conn->specific[key];
6595 MUTEX_EXIT(&conn->conn_data_lock);
6599 #endif /* !KERNEL */
6602 * processStats is a queue used to store the statistics for the local
6603 * process. Its contents are similar to the contents of the rpcStats
6604 * queue on a rx_peer structure, but the actual data stored within
6605 * this queue contains totals across the lifetime of the process (assuming
6606 * the stats have not been reset) - unlike the per peer structures
6607 * which can come and go based upon the peer lifetime.
6610 static struct rx_queue processStats = { &processStats, &processStats };
6613 * peerStats is a queue used to store the statistics for all peer structs.
6614 * Its contents are the union of all the peer rpcStats queues.
6617 static struct rx_queue peerStats = { &peerStats, &peerStats };
6620 * rxi_monitor_processStats is used to turn process wide stat collection
6624 static int rxi_monitor_processStats = 0;
6627 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
6630 static int rxi_monitor_peerStats = 0;
6633 * rxi_AddRpcStat - given all of the information for a particular rpc
6634 * call, create (if needed) and update the stat totals for the rpc.
6638 * IN stats - the queue of stats that will be updated with the new value
6640 * IN rxInterface - a unique number that identifies the rpc interface
6642 * IN currentFunc - the index of the function being invoked
6644 * IN totalFunc - the total number of functions in this interface
6646 * IN queueTime - the amount of time this function waited for a thread
6648 * IN execTime - the amount of time this function invocation took to execute
6650 * IN bytesSent - the number bytes sent by this invocation
6652 * IN bytesRcvd - the number bytes received by this invocation
6654 * IN isServer - if true, this invocation was made to a server
6656 * IN remoteHost - the ip address of the remote host
6658 * IN remotePort - the port of the remote host
6660 * IN addToPeerList - if != 0, add newly created stat to the global peer list
6662 * INOUT counter - if a new stats structure is allocated, the counter will
6663 * be updated with the new number of allocated stat structures
6671 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
6672 afs_uint32 currentFunc, afs_uint32 totalFunc,
6673 struct clock *queueTime, struct clock *execTime,
6674 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
6675 afs_uint32 remoteHost, afs_uint32 remotePort,
6676 int addToPeerList, unsigned int *counter)
6679 rx_interface_stat_p rpc_stat, nrpc_stat;
6682 * See if there's already a structure for this interface
6685 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
6686 if ((rpc_stat->stats[0].interfaceId == rxInterface)
6687 && (rpc_stat->stats[0].remote_is_server == isServer))
6692 * Didn't find a match so allocate a new structure and add it to the
6696 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
6697 || (rpc_stat->stats[0].interfaceId != rxInterface)
6698 || (rpc_stat->stats[0].remote_is_server != isServer)) {
6703 sizeof(rx_interface_stat_t) +
6704 totalFunc * sizeof(rx_function_entry_v1_t);
6706 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
6707 if (rpc_stat == NULL) {
6711 *counter += totalFunc;
6712 for (i = 0; i < totalFunc; i++) {
6713 rpc_stat->stats[i].remote_peer = remoteHost;
6714 rpc_stat->stats[i].remote_port = remotePort;
6715 rpc_stat->stats[i].remote_is_server = isServer;
6716 rpc_stat->stats[i].interfaceId = rxInterface;
6717 rpc_stat->stats[i].func_total = totalFunc;
6718 rpc_stat->stats[i].func_index = i;
6719 hzero(rpc_stat->stats[i].invocations);
6720 hzero(rpc_stat->stats[i].bytes_sent);
6721 hzero(rpc_stat->stats[i].bytes_rcvd);
6722 rpc_stat->stats[i].queue_time_sum.sec = 0;
6723 rpc_stat->stats[i].queue_time_sum.usec = 0;
6724 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
6725 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
6726 rpc_stat->stats[i].queue_time_min.sec = 9999999;
6727 rpc_stat->stats[i].queue_time_min.usec = 9999999;
6728 rpc_stat->stats[i].queue_time_max.sec = 0;
6729 rpc_stat->stats[i].queue_time_max.usec = 0;
6730 rpc_stat->stats[i].execution_time_sum.sec = 0;
6731 rpc_stat->stats[i].execution_time_sum.usec = 0;
6732 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
6733 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
6734 rpc_stat->stats[i].execution_time_min.sec = 9999999;
6735 rpc_stat->stats[i].execution_time_min.usec = 9999999;
6736 rpc_stat->stats[i].execution_time_max.sec = 0;
6737 rpc_stat->stats[i].execution_time_max.usec = 0;
6739 queue_Prepend(stats, rpc_stat);
6740 if (addToPeerList) {
6741 queue_Prepend(&peerStats, &rpc_stat->all_peers);
6746 * Increment the stats for this function
6749 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
6750 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
6751 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
6752 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
6753 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
6754 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
6755 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
6757 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
6758 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
6760 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
6761 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
6763 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
6764 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
6766 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
6767 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
6775 * rx_IncrementTimeAndCount - increment the times and count for a particular
6780 * IN peer - the peer who invoked the rpc
6782 * IN rxInterface - a unique number that identifies the rpc interface
6784 * IN currentFunc - the index of the function being invoked
6786 * IN totalFunc - the total number of functions in this interface
6788 * IN queueTime - the amount of time this function waited for a thread
6790 * IN execTime - the amount of time this function invocation took to execute
6792 * IN bytesSent - the number bytes sent by this invocation
6794 * IN bytesRcvd - the number bytes received by this invocation
6796 * IN isServer - if true, this invocation was made to a server
6804 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
6805 afs_uint32 currentFunc, afs_uint32 totalFunc,
6806 struct clock *queueTime, struct clock *execTime,
6807 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
6811 MUTEX_ENTER(&rx_rpc_stats);
6812 MUTEX_ENTER(&peer->peer_lock);
6814 if (rxi_monitor_peerStats) {
6815 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
6816 queueTime, execTime, bytesSent, bytesRcvd, isServer,
6817 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
6820 if (rxi_monitor_processStats) {
6821 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
6822 queueTime, execTime, bytesSent, bytesRcvd, isServer,
6823 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
6826 MUTEX_EXIT(&peer->peer_lock);
6827 MUTEX_EXIT(&rx_rpc_stats);
6832 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
6836 * IN callerVersion - the rpc stat version of the caller.
6838 * IN count - the number of entries to marshall.
6840 * IN stats - pointer to stats to be marshalled.
6842 * OUT ptr - Where to store the marshalled data.
6849 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
6850 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
6856 * We only support the first version
6858 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
6859 *(ptr++) = stats->remote_peer;
6860 *(ptr++) = stats->remote_port;
6861 *(ptr++) = stats->remote_is_server;
6862 *(ptr++) = stats->interfaceId;
6863 *(ptr++) = stats->func_total;
6864 *(ptr++) = stats->func_index;
6865 *(ptr++) = hgethi(stats->invocations);
6866 *(ptr++) = hgetlo(stats->invocations);
6867 *(ptr++) = hgethi(stats->bytes_sent);
6868 *(ptr++) = hgetlo(stats->bytes_sent);
6869 *(ptr++) = hgethi(stats->bytes_rcvd);
6870 *(ptr++) = hgetlo(stats->bytes_rcvd);
6871 *(ptr++) = stats->queue_time_sum.sec;
6872 *(ptr++) = stats->queue_time_sum.usec;
6873 *(ptr++) = stats->queue_time_sum_sqr.sec;
6874 *(ptr++) = stats->queue_time_sum_sqr.usec;
6875 *(ptr++) = stats->queue_time_min.sec;
6876 *(ptr++) = stats->queue_time_min.usec;
6877 *(ptr++) = stats->queue_time_max.sec;
6878 *(ptr++) = stats->queue_time_max.usec;
6879 *(ptr++) = stats->execution_time_sum.sec;
6880 *(ptr++) = stats->execution_time_sum.usec;
6881 *(ptr++) = stats->execution_time_sum_sqr.sec;
6882 *(ptr++) = stats->execution_time_sum_sqr.usec;
6883 *(ptr++) = stats->execution_time_min.sec;
6884 *(ptr++) = stats->execution_time_min.usec;
6885 *(ptr++) = stats->execution_time_max.sec;
6886 *(ptr++) = stats->execution_time_max.usec;
6892 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
6897 * IN callerVersion - the rpc stat version of the caller
6899 * OUT myVersion - the rpc stat version of this function
6901 * OUT clock_sec - local time seconds
6903 * OUT clock_usec - local time microseconds
6905 * OUT allocSize - the number of bytes allocated to contain stats
6907 * OUT statCount - the number stats retrieved from this process.
6909 * OUT stats - the actual stats retrieved from this process.
6913 * Returns void. If successful, stats will != NULL.
6917 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
6918 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
6919 size_t * allocSize, afs_uint32 * statCount,
6920 afs_uint32 ** stats)
6930 *myVersion = RX_STATS_RETRIEVAL_VERSION;
6933 * Check to see if stats are enabled
6936 MUTEX_ENTER(&rx_rpc_stats);
6937 if (!rxi_monitor_processStats) {
6938 MUTEX_EXIT(&rx_rpc_stats);
6942 clock_GetTime(&now);
6943 *clock_sec = now.sec;
6944 *clock_usec = now.usec;
6947 * Allocate the space based upon the caller version
6949 * If the client is at an older version than we are,
6950 * we return the statistic data in the older data format, but
6951 * we still return our version number so the client knows we
6952 * are maintaining more data than it can retrieve.
6955 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
6956 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
6957 *statCount = rxi_rpc_process_stat_cnt;
6960 * This can't happen yet, but in the future version changes
6961 * can be handled by adding additional code here
6965 if (space > (size_t) 0) {
6967 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
6970 rx_interface_stat_p rpc_stat, nrpc_stat;
6974 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
6976 * Copy the data based upon the caller version
6978 rx_MarshallProcessRPCStats(callerVersion,
6979 rpc_stat->stats[0].func_total,
6980 rpc_stat->stats, &ptr);
6986 MUTEX_EXIT(&rx_rpc_stats);
6991 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
6995 * IN callerVersion - the rpc stat version of the caller
6997 * OUT myVersion - the rpc stat version of this function
6999 * OUT clock_sec - local time seconds
7001 * OUT clock_usec - local time microseconds
7003 * OUT allocSize - the number of bytes allocated to contain stats
7005 * OUT statCount - the number of stats retrieved from the individual
7008 * OUT stats - the actual stats retrieved from the individual peer structures.
7012 * Returns void. If successful, stats will != NULL.
7016 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7017 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7018 size_t * allocSize, afs_uint32 * statCount,
7019 afs_uint32 ** stats)
7029 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7032 * Check to see if stats are enabled
7035 MUTEX_ENTER(&rx_rpc_stats);
7036 if (!rxi_monitor_peerStats) {
7037 MUTEX_EXIT(&rx_rpc_stats);
7041 clock_GetTime(&now);
7042 *clock_sec = now.sec;
7043 *clock_usec = now.usec;
7046 * Allocate the space based upon the caller version
7048 * If the client is at an older version than we are,
7049 * we return the statistic data in the older data format, but
7050 * we still return our version number so the client knows we
7051 * are maintaining more data than it can retrieve.
7054 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7055 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7056 *statCount = rxi_rpc_peer_stat_cnt;
7059 * This can't happen yet, but in the future version changes
7060 * can be handled by adding additional code here
7064 if (space > (size_t) 0) {
7066 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7069 rx_interface_stat_p rpc_stat, nrpc_stat;
7073 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7075 * We have to fix the offset of rpc_stat since we are
7076 * keeping this structure on two rx_queues. The rx_queue
7077 * package assumes that the rx_queue member is the first
7078 * member of the structure. That is, rx_queue assumes that
7079 * any one item is only on one queue at a time. We are
7080 * breaking that assumption and so we have to do a little
7081 * math to fix our pointers.
7084 fix_offset = (char *)rpc_stat;
7085 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7086 rpc_stat = (rx_interface_stat_p) fix_offset;
7089 * Copy the data based upon the caller version
7091 rx_MarshallProcessRPCStats(callerVersion,
7092 rpc_stat->stats[0].func_total,
7093 rpc_stat->stats, &ptr);
7099 MUTEX_EXIT(&rx_rpc_stats);
7104 * rx_FreeRPCStats - free memory allocated by
7105 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7109 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7110 * rx_RetrievePeerRPCStats
7112 * IN allocSize - the number of bytes in stats.
7120 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7122 rxi_Free(stats, allocSize);
7126 * rx_queryProcessRPCStats - see if process rpc stat collection is
7127 * currently enabled.
7133 * Returns 0 if stats are not enabled != 0 otherwise
7137 rx_queryProcessRPCStats(void)
7140 MUTEX_ENTER(&rx_rpc_stats);
7141 rc = rxi_monitor_processStats;
7142 MUTEX_EXIT(&rx_rpc_stats);
7147 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7153 * Returns 0 if stats are not enabled != 0 otherwise
7157 rx_queryPeerRPCStats(void)
7160 MUTEX_ENTER(&rx_rpc_stats);
7161 rc = rxi_monitor_peerStats;
7162 MUTEX_EXIT(&rx_rpc_stats);
7167 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7177 rx_enableProcessRPCStats(void)
7179 MUTEX_ENTER(&rx_rpc_stats);
7180 rx_enable_stats = 1;
7181 rxi_monitor_processStats = 1;
7182 MUTEX_EXIT(&rx_rpc_stats);
7186 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7196 rx_enablePeerRPCStats(void)
7198 MUTEX_ENTER(&rx_rpc_stats);
7199 rx_enable_stats = 1;
7200 rxi_monitor_peerStats = 1;
7201 MUTEX_EXIT(&rx_rpc_stats);
7205 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7215 rx_disableProcessRPCStats(void)
7217 rx_interface_stat_p rpc_stat, nrpc_stat;
7220 MUTEX_ENTER(&rx_rpc_stats);
7223 * Turn off process statistics and if peer stats is also off, turn
7227 rxi_monitor_processStats = 0;
7228 if (rxi_monitor_peerStats == 0) {
7229 rx_enable_stats = 0;
7232 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7233 unsigned int num_funcs = 0;
7236 queue_Remove(rpc_stat);
7237 num_funcs = rpc_stat->stats[0].func_total;
7239 sizeof(rx_interface_stat_t) +
7240 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7242 rxi_Free(rpc_stat, space);
7243 rxi_rpc_process_stat_cnt -= num_funcs;
7245 MUTEX_EXIT(&rx_rpc_stats);
7249 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7259 rx_disablePeerRPCStats(void)
7261 struct rx_peer **peer_ptr, **peer_end;
7264 MUTEX_ENTER(&rx_rpc_stats);
7267 * Turn off peer statistics and if process stats is also off, turn
7271 rxi_monitor_peerStats = 0;
7272 if (rxi_monitor_processStats == 0) {
7273 rx_enable_stats = 0;
7276 MUTEX_ENTER(&rx_peerHashTable_lock);
7277 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7278 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7280 struct rx_peer *peer, *next, *prev;
7281 for (prev = peer = *peer_ptr; peer; peer = next) {
7283 code = MUTEX_TRYENTER(&peer->peer_lock);
7285 rx_interface_stat_p rpc_stat, nrpc_stat;
7288 (&peer->rpcStats, rpc_stat, nrpc_stat,
7289 rx_interface_stat)) {
7290 unsigned int num_funcs = 0;
7293 queue_Remove(&rpc_stat->queue_header);
7294 queue_Remove(&rpc_stat->all_peers);
7295 num_funcs = rpc_stat->stats[0].func_total;
7297 sizeof(rx_interface_stat_t) +
7298 rpc_stat->stats[0].func_total *
7299 sizeof(rx_function_entry_v1_t);
7301 rxi_Free(rpc_stat, space);
7302 rxi_rpc_peer_stat_cnt -= num_funcs;
7304 MUTEX_EXIT(&peer->peer_lock);
7305 if (prev == *peer_ptr) {
7315 MUTEX_EXIT(&rx_peerHashTable_lock);
7316 MUTEX_EXIT(&rx_rpc_stats);
7320 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7325 * IN clearFlag - flag indicating which stats to clear
7333 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7335 rx_interface_stat_p rpc_stat, nrpc_stat;
7337 MUTEX_ENTER(&rx_rpc_stats);
7339 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7340 unsigned int num_funcs = 0, i;
7341 num_funcs = rpc_stat->stats[0].func_total;
7342 for (i = 0; i < num_funcs; i++) {
7343 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7344 hzero(rpc_stat->stats[i].invocations);
7346 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7347 hzero(rpc_stat->stats[i].bytes_sent);
7349 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7350 hzero(rpc_stat->stats[i].bytes_rcvd);
7352 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7353 rpc_stat->stats[i].queue_time_sum.sec = 0;
7354 rpc_stat->stats[i].queue_time_sum.usec = 0;
7356 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7357 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7358 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7360 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7361 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7362 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7364 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7365 rpc_stat->stats[i].queue_time_max.sec = 0;
7366 rpc_stat->stats[i].queue_time_max.usec = 0;
7368 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7369 rpc_stat->stats[i].execution_time_sum.sec = 0;
7370 rpc_stat->stats[i].execution_time_sum.usec = 0;
7372 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7373 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7374 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7376 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7377 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7378 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7380 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7381 rpc_stat->stats[i].execution_time_max.sec = 0;
7382 rpc_stat->stats[i].execution_time_max.usec = 0;
7387 MUTEX_EXIT(&rx_rpc_stats);
7391 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
7396 * IN clearFlag - flag indicating which stats to clear
7404 rx_clearPeerRPCStats(afs_uint32 clearFlag)
7406 rx_interface_stat_p rpc_stat, nrpc_stat;
7408 MUTEX_ENTER(&rx_rpc_stats);
7410 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7411 unsigned int num_funcs = 0, i;
7414 * We have to fix the offset of rpc_stat since we are
7415 * keeping this structure on two rx_queues. The rx_queue
7416 * package assumes that the rx_queue member is the first
7417 * member of the structure. That is, rx_queue assumes that
7418 * any one item is only on one queue at a time. We are
7419 * breaking that assumption and so we have to do a little
7420 * math to fix our pointers.
7423 fix_offset = (char *)rpc_stat;
7424 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7425 rpc_stat = (rx_interface_stat_p) fix_offset;
7427 num_funcs = rpc_stat->stats[0].func_total;
7428 for (i = 0; i < num_funcs; i++) {
7429 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7430 hzero(rpc_stat->stats[i].invocations);
7432 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7433 hzero(rpc_stat->stats[i].bytes_sent);
7435 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7436 hzero(rpc_stat->stats[i].bytes_rcvd);
7438 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7439 rpc_stat->stats[i].queue_time_sum.sec = 0;
7440 rpc_stat->stats[i].queue_time_sum.usec = 0;
7442 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7443 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7444 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7446 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7447 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7448 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7450 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7451 rpc_stat->stats[i].queue_time_max.sec = 0;
7452 rpc_stat->stats[i].queue_time_max.usec = 0;
7454 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7455 rpc_stat->stats[i].execution_time_sum.sec = 0;
7456 rpc_stat->stats[i].execution_time_sum.usec = 0;
7458 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7459 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7460 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7462 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7463 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7464 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7466 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7467 rpc_stat->stats[i].execution_time_max.sec = 0;
7468 rpc_stat->stats[i].execution_time_max.usec = 0;
7473 MUTEX_EXIT(&rx_rpc_stats);
7477 * rxi_rxstat_userok points to a routine that returns 1 if the caller
7478 * is authorized to enable/disable/clear RX statistics.
7480 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
7483 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
7485 rxi_rxstat_userok = proc;
7489 rx_RxStatUserOk(struct rx_call *call)
7491 if (!rxi_rxstat_userok)
7493 return rxi_rxstat_userok(call);