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_OSF_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);
220 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
223 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
224 #define INIT_PTHREAD_LOCKS \
225 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
227 * The rx_stats_mutex mutex protects the following global variables:
232 * rxi_lowConnRefCount
233 * rxi_lowPeerRefCount
242 #define INIT_PTHREAD_LOCKS
246 /* Variables for handling the minProcs implementation. availProcs gives the
247 * number of threads available in the pool at this moment (not counting dudes
248 * executing right now). totalMin gives the total number of procs required
249 * for handling all minProcs requests. minDeficit is a dynamic variable
250 * tracking the # of procs required to satisfy all of the remaining minProcs
252 * For fine grain locking to work, the quota check and the reservation of
253 * a server thread has to come while rxi_availProcs and rxi_minDeficit
254 * are locked. To this end, the code has been modified under #ifdef
255 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
256 * same time. A new function, ReturnToServerPool() returns the allocation.
258 * A call can be on several queue's (but only one at a time). When
259 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
260 * that no one else is touching the queue. To this end, we store the address
261 * of the queue lock in the call structure (under the call lock) when we
262 * put the call on a queue, and we clear the call_queue_lock when the
263 * call is removed from a queue (once the call lock has been obtained).
264 * This allows rxi_ResetCall to safely synchronize with others wishing
265 * to manipulate the queue.
268 #ifdef RX_ENABLE_LOCKS
269 static afs_kmutex_t rx_rpc_stats;
270 void rxi_StartUnlocked();
273 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
274 ** pretty good that the next packet coming in is from the same connection
275 ** as the last packet, since we're send multiple packets in a transmit window.
277 struct rx_connection *rxLastConn = 0;
279 #ifdef RX_ENABLE_LOCKS
280 /* The locking hierarchy for rx fine grain locking is composed of these
283 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
284 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
285 * call->lock - locks call data fields.
286 * These are independent of each other:
287 * rx_freeCallQueue_lock
292 * serverQueueEntry->lock
294 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
295 * peer->lock - locks peer data fields.
296 * conn_data_lock - that more than one thread is not updating a conn data
297 * field at the same time.
305 * Do we need a lock to protect the peer field in the conn structure?
306 * conn->peer was previously a constant for all intents and so has no
307 * lock protecting this field. The multihomed client delta introduced
308 * a RX code change : change the peer field in the connection structure
309 * to that remote inetrface from which the last packet for this
310 * connection was sent out. This may become an issue if further changes
313 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
314 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
316 /* rxdb_fileID is used to identify the lock location, along with line#. */
317 static int rxdb_fileID = RXDB_FILE_RX;
318 #endif /* RX_LOCKS_DB */
319 #else /* RX_ENABLE_LOCKS */
320 #define SET_CALL_QUEUE_LOCK(C, L)
321 #define CLEAR_CALL_QUEUE_LOCK(C)
322 #endif /* RX_ENABLE_LOCKS */
323 struct rx_serverQueueEntry *rx_waitForPacket = 0;
324 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
326 /* ------------Exported Interfaces------------- */
328 /* This function allows rxkad to set the epoch to a suitably random number
329 * which rx_NewConnection will use in the future. The principle purpose is to
330 * get rxnull connections to use the same epoch as the rxkad connections do, at
331 * least once the first rxkad connection is established. This is important now
332 * that the host/port addresses aren't used in FindConnection: the uniqueness
333 * of epoch/cid matters and the start time won't do. */
335 #ifdef AFS_PTHREAD_ENV
337 * This mutex protects the following global variables:
341 #define LOCK_EPOCH assert(pthread_mutex_lock(&epoch_mutex)==0)
342 #define UNLOCK_EPOCH assert(pthread_mutex_unlock(&epoch_mutex)==0)
346 #endif /* AFS_PTHREAD_ENV */
349 rx_SetEpoch(afs_uint32 epoch)
356 /* Initialize rx. A port number may be mentioned, in which case this
357 * becomes the default port number for any service installed later.
358 * If 0 is provided for the port number, a random port will be chosen
359 * by the kernel. Whether this will ever overlap anything in
360 * /etc/services is anybody's guess... Returns 0 on success, -1 on
362 static int rxinit_status = 1;
363 #ifdef AFS_PTHREAD_ENV
365 * This mutex protects the following global variables:
369 #define LOCK_RX_INIT assert(pthread_mutex_lock(&rx_init_mutex)==0)
370 #define UNLOCK_RX_INIT assert(pthread_mutex_unlock(&rx_init_mutex)==0)
373 #define UNLOCK_RX_INIT
377 rx_InitHost(u_int host, u_int port)
384 char *htable, *ptable;
387 #if defined(AFS_DJGPP_ENV) && !defined(DEBUG)
388 __djgpp_set_quiet_socket(1);
395 if (rxinit_status == 0) {
396 tmp_status = rxinit_status;
398 return tmp_status; /* Already started; return previous error code. */
401 if (afs_winsockInit() < 0)
407 * Initialize anything necessary to provide a non-premptive threading
410 rxi_InitializeThreadSupport();
413 /* Allocate and initialize a socket for client and perhaps server
416 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
417 if (rx_socket == OSI_NULLSOCKET) {
421 #ifdef RX_ENABLE_LOCKS
424 #endif /* RX_LOCKS_DB */
425 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
426 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
427 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
428 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
429 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
431 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
433 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
435 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
437 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
439 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
441 #if defined(KERNEL) && defined(AFS_HPUX110_ENV)
443 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
444 #endif /* KERNEL && AFS_HPUX110_ENV */
445 #else /* RX_ENABLE_LOCKS */
446 #if defined(KERNEL) && defined(AFS_GLOBAL_SUNLOCK) && !defined(AFS_HPUX_ENV) && !defined(AFS_OBSD_ENV)
447 mutex_init(&afs_rxglobal_lock, "afs_rxglobal_lock", MUTEX_DEFAULT, NULL);
448 #endif /* AFS_GLOBAL_SUNLOCK */
449 #endif /* RX_ENABLE_LOCKS */
452 rx_connDeadTime = 12;
453 rx_tranquil = 0; /* reset flag */
454 memset((char *)&rx_stats, 0, sizeof(struct rx_stats));
456 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
457 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
458 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
459 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
460 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
461 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
463 /* Malloc up a bunch of packets & buffers */
465 queue_Init(&rx_freePacketQueue);
466 rxi_NeedMorePackets = FALSE;
467 #ifdef RX_ENABLE_TSFPQ
468 rx_nPackets = 0; /* in TSFPQ version, rx_nPackets is managed by rxi_MorePackets* */
469 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
470 #else /* RX_ENABLE_TSFPQ */
471 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
472 rxi_MorePackets(rx_nPackets);
473 #endif /* RX_ENABLE_TSFPQ */
480 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
481 tv.tv_sec = clock_now.sec;
482 tv.tv_usec = clock_now.usec;
483 srand((unsigned int)tv.tv_usec);
490 #if defined(KERNEL) && !defined(UKERNEL)
491 /* Really, this should never happen in a real kernel */
494 struct sockaddr_in addr;
495 int addrlen = sizeof(addr);
496 if (getsockname((int)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
500 rx_port = addr.sin_port;
503 rx_stats.minRtt.sec = 9999999;
505 rx_SetEpoch(tv.tv_sec | 0x80000000);
507 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
508 * will provide a randomer value. */
510 MUTEX_ENTER(&rx_stats_mutex);
511 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
512 MUTEX_EXIT(&rx_stats_mutex);
513 /* *Slightly* random start time for the cid. This is just to help
514 * out with the hashing function at the peer */
515 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
516 rx_connHashTable = (struct rx_connection **)htable;
517 rx_peerHashTable = (struct rx_peer **)ptable;
519 rx_lastAckDelay.sec = 0;
520 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
521 rx_hardAckDelay.sec = 0;
522 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
523 rx_softAckDelay.sec = 0;
524 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
526 rxevent_Init(20, rxi_ReScheduleEvents);
528 /* Initialize various global queues */
529 queue_Init(&rx_idleServerQueue);
530 queue_Init(&rx_incomingCallQueue);
531 queue_Init(&rx_freeCallQueue);
533 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
534 /* Initialize our list of usable IP addresses. */
538 /* Start listener process (exact function is dependent on the
539 * implementation environment--kernel or user space) */
543 tmp_status = rxinit_status = 0;
551 return rx_InitHost(htonl(INADDR_ANY), port);
554 /* called with unincremented nRequestsRunning to see if it is OK to start
555 * a new thread in this service. Could be "no" for two reasons: over the
556 * max quota, or would prevent others from reaching their min quota.
558 #ifdef RX_ENABLE_LOCKS
559 /* This verion of QuotaOK reserves quota if it's ok while the
560 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
563 QuotaOK(register struct rx_service *aservice)
565 /* check if over max quota */
566 if (aservice->nRequestsRunning >= aservice->maxProcs) {
570 /* under min quota, we're OK */
571 /* otherwise, can use only if there are enough to allow everyone
572 * to go to their min quota after this guy starts.
574 MUTEX_ENTER(&rx_stats_mutex);
575 if ((aservice->nRequestsRunning < aservice->minProcs)
576 || (rxi_availProcs > rxi_minDeficit)) {
577 aservice->nRequestsRunning++;
578 /* just started call in minProcs pool, need fewer to maintain
580 if (aservice->nRequestsRunning <= aservice->minProcs)
583 MUTEX_EXIT(&rx_stats_mutex);
586 MUTEX_EXIT(&rx_stats_mutex);
592 ReturnToServerPool(register struct rx_service *aservice)
594 aservice->nRequestsRunning--;
595 MUTEX_ENTER(&rx_stats_mutex);
596 if (aservice->nRequestsRunning < aservice->minProcs)
599 MUTEX_EXIT(&rx_stats_mutex);
602 #else /* RX_ENABLE_LOCKS */
604 QuotaOK(register struct rx_service *aservice)
607 /* under min quota, we're OK */
608 if (aservice->nRequestsRunning < aservice->minProcs)
611 /* check if over max quota */
612 if (aservice->nRequestsRunning >= aservice->maxProcs)
615 /* otherwise, can use only if there are enough to allow everyone
616 * to go to their min quota after this guy starts.
618 if (rxi_availProcs > rxi_minDeficit)
622 #endif /* RX_ENABLE_LOCKS */
625 /* Called by rx_StartServer to start up lwp's to service calls.
626 NExistingProcs gives the number of procs already existing, and which
627 therefore needn't be created. */
629 rxi_StartServerProcs(int nExistingProcs)
631 register struct rx_service *service;
636 /* For each service, reserve N processes, where N is the "minimum"
637 * number of processes that MUST be able to execute a request in parallel,
638 * at any time, for that process. Also compute the maximum difference
639 * between any service's maximum number of processes that can run
640 * (i.e. the maximum number that ever will be run, and a guarantee
641 * that this number will run if other services aren't running), and its
642 * minimum number. The result is the extra number of processes that
643 * we need in order to provide the latter guarantee */
644 for (i = 0; i < RX_MAX_SERVICES; i++) {
646 service = rx_services[i];
647 if (service == (struct rx_service *)0)
649 nProcs += service->minProcs;
650 diff = service->maxProcs - service->minProcs;
654 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
655 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
656 for (i = 0; i < nProcs; i++) {
657 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
663 /* This routine is only required on Windows */
665 rx_StartClientThread(void)
667 #ifdef AFS_PTHREAD_ENV
669 pid = (int) pthread_self();
670 #endif /* AFS_PTHREAD_ENV */
672 #endif /* AFS_NT40_ENV */
674 /* This routine must be called if any services are exported. If the
675 * donateMe flag is set, the calling process is donated to the server
678 rx_StartServer(int donateMe)
680 register struct rx_service *service;
686 /* Start server processes, if necessary (exact function is dependent
687 * on the implementation environment--kernel or user space). DonateMe
688 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
689 * case, one less new proc will be created rx_StartServerProcs.
691 rxi_StartServerProcs(donateMe);
693 /* count up the # of threads in minProcs, and add set the min deficit to
694 * be that value, too.
696 for (i = 0; i < RX_MAX_SERVICES; i++) {
697 service = rx_services[i];
698 if (service == (struct rx_service *)0)
700 MUTEX_ENTER(&rx_stats_mutex);
701 rxi_totalMin += service->minProcs;
702 /* below works even if a thread is running, since minDeficit would
703 * still have been decremented and later re-incremented.
705 rxi_minDeficit += service->minProcs;
706 MUTEX_EXIT(&rx_stats_mutex);
709 /* Turn on reaping of idle server connections */
710 rxi_ReapConnections();
719 #ifdef AFS_PTHREAD_ENV
721 pid = (pid_t) pthread_self();
722 #else /* AFS_PTHREAD_ENV */
724 LWP_CurrentProcess(&pid);
725 #endif /* AFS_PTHREAD_ENV */
727 sprintf(name, "srv_%d", ++nProcs);
729 (*registerProgram) (pid, name);
731 #endif /* AFS_NT40_ENV */
732 rx_ServerProc(); /* Never returns */
734 #ifdef RX_ENABLE_TSFPQ
735 /* no use leaving packets around in this thread's local queue if
736 * it isn't getting donated to the server thread pool.
738 rxi_FlushLocalPacketsTSFPQ();
739 #endif /* RX_ENABLE_TSFPQ */
743 /* Create a new client connection to the specified service, using the
744 * specified security object to implement the security model for this
746 struct rx_connection *
747 rx_NewConnection(register afs_uint32 shost, u_short sport, u_short sservice,
748 register struct rx_securityClass *securityObject,
749 int serviceSecurityIndex)
753 register struct rx_connection *conn;
758 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n", shost, sport, sservice, securityObject, serviceSecurityIndex));
760 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
761 * the case of kmem_alloc? */
762 conn = rxi_AllocConnection();
763 #ifdef RX_ENABLE_LOCKS
764 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
765 MUTEX_INIT(&conn->conn_data_lock, "conn call lock", MUTEX_DEFAULT, 0);
766 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
769 MUTEX_ENTER(&rx_connHashTable_lock);
770 cid = (rx_nextCid += RX_MAXCALLS);
771 conn->type = RX_CLIENT_CONNECTION;
773 conn->epoch = rx_epoch;
774 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
775 conn->serviceId = sservice;
776 conn->securityObject = securityObject;
777 /* This doesn't work in all compilers with void (they're buggy), so fake it
779 conn->securityData = (VOID *) 0;
780 conn->securityIndex = serviceSecurityIndex;
781 rx_SetConnDeadTime(conn, rx_connDeadTime);
782 conn->ackRate = RX_FAST_ACK_RATE;
784 conn->specific = NULL;
785 conn->challengeEvent = NULL;
786 conn->delayedAbortEvent = NULL;
787 conn->abortCount = 0;
790 RXS_NewConnection(securityObject, conn);
792 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
794 conn->refCount++; /* no lock required since only this thread knows... */
795 conn->next = rx_connHashTable[hashindex];
796 rx_connHashTable[hashindex] = conn;
797 MUTEX_ENTER(&rx_stats_mutex);
798 rx_stats.nClientConns++;
799 MUTEX_EXIT(&rx_stats_mutex);
801 MUTEX_EXIT(&rx_connHashTable_lock);
807 rx_SetConnDeadTime(register struct rx_connection *conn, register int seconds)
809 /* The idea is to set the dead time to a value that allows several
810 * keepalives to be dropped without timing out the connection. */
811 conn->secondsUntilDead = MAX(seconds, 6);
812 conn->secondsUntilPing = conn->secondsUntilDead / 6;
815 int rxi_lowPeerRefCount = 0;
816 int rxi_lowConnRefCount = 0;
819 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
820 * NOTE: must not be called with rx_connHashTable_lock held.
823 rxi_CleanupConnection(struct rx_connection *conn)
825 /* Notify the service exporter, if requested, that this connection
826 * is being destroyed */
827 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
828 (*conn->service->destroyConnProc) (conn);
830 /* Notify the security module that this connection is being destroyed */
831 RXS_DestroyConnection(conn->securityObject, conn);
833 /* If this is the last connection using the rx_peer struct, set its
834 * idle time to now. rxi_ReapConnections will reap it if it's still
835 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
837 MUTEX_ENTER(&rx_peerHashTable_lock);
838 if (conn->peer->refCount < 2) {
839 conn->peer->idleWhen = clock_Sec();
840 if (conn->peer->refCount < 1) {
841 conn->peer->refCount = 1;
842 MUTEX_ENTER(&rx_stats_mutex);
843 rxi_lowPeerRefCount++;
844 MUTEX_EXIT(&rx_stats_mutex);
847 conn->peer->refCount--;
848 MUTEX_EXIT(&rx_peerHashTable_lock);
850 MUTEX_ENTER(&rx_stats_mutex);
851 if (conn->type == RX_SERVER_CONNECTION)
852 rx_stats.nServerConns--;
854 rx_stats.nClientConns--;
855 MUTEX_EXIT(&rx_stats_mutex);
858 if (conn->specific) {
860 for (i = 0; i < conn->nSpecific; i++) {
861 if (conn->specific[i] && rxi_keyCreate_destructor[i])
862 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
863 conn->specific[i] = NULL;
865 free(conn->specific);
867 conn->specific = NULL;
871 MUTEX_DESTROY(&conn->conn_call_lock);
872 MUTEX_DESTROY(&conn->conn_data_lock);
873 CV_DESTROY(&conn->conn_call_cv);
875 rxi_FreeConnection(conn);
878 /* Destroy the specified connection */
880 rxi_DestroyConnection(register struct rx_connection *conn)
882 MUTEX_ENTER(&rx_connHashTable_lock);
883 rxi_DestroyConnectionNoLock(conn);
884 /* conn should be at the head of the cleanup list */
885 if (conn == rx_connCleanup_list) {
886 rx_connCleanup_list = rx_connCleanup_list->next;
887 MUTEX_EXIT(&rx_connHashTable_lock);
888 rxi_CleanupConnection(conn);
890 #ifdef RX_ENABLE_LOCKS
892 MUTEX_EXIT(&rx_connHashTable_lock);
894 #endif /* RX_ENABLE_LOCKS */
898 rxi_DestroyConnectionNoLock(register struct rx_connection *conn)
900 register struct rx_connection **conn_ptr;
901 register int havecalls = 0;
902 struct rx_packet *packet;
909 MUTEX_ENTER(&conn->conn_data_lock);
910 if (conn->refCount > 0)
913 MUTEX_ENTER(&rx_stats_mutex);
914 rxi_lowConnRefCount++;
915 MUTEX_EXIT(&rx_stats_mutex);
918 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
919 /* Busy; wait till the last guy before proceeding */
920 MUTEX_EXIT(&conn->conn_data_lock);
925 /* If the client previously called rx_NewCall, but it is still
926 * waiting, treat this as a running call, and wait to destroy the
927 * connection later when the call completes. */
928 if ((conn->type == RX_CLIENT_CONNECTION)
929 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
930 conn->flags |= RX_CONN_DESTROY_ME;
931 MUTEX_EXIT(&conn->conn_data_lock);
935 MUTEX_EXIT(&conn->conn_data_lock);
937 /* Check for extant references to this connection */
938 for (i = 0; i < RX_MAXCALLS; i++) {
939 register struct rx_call *call = conn->call[i];
942 if (conn->type == RX_CLIENT_CONNECTION) {
943 MUTEX_ENTER(&call->lock);
944 if (call->delayedAckEvent) {
945 /* Push the final acknowledgment out now--there
946 * won't be a subsequent call to acknowledge the
947 * last reply packets */
948 rxevent_Cancel(call->delayedAckEvent, call,
949 RX_CALL_REFCOUNT_DELAY);
950 if (call->state == RX_STATE_PRECALL
951 || call->state == RX_STATE_ACTIVE) {
952 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
954 rxi_AckAll(NULL, call, 0);
957 MUTEX_EXIT(&call->lock);
961 #ifdef RX_ENABLE_LOCKS
963 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
964 MUTEX_EXIT(&conn->conn_data_lock);
966 /* Someone is accessing a packet right now. */
970 #endif /* RX_ENABLE_LOCKS */
973 /* Don't destroy the connection if there are any call
974 * structures still in use */
975 MUTEX_ENTER(&conn->conn_data_lock);
976 conn->flags |= RX_CONN_DESTROY_ME;
977 MUTEX_EXIT(&conn->conn_data_lock);
982 if (conn->delayedAbortEvent) {
983 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
984 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
986 MUTEX_ENTER(&conn->conn_data_lock);
987 rxi_SendConnectionAbort(conn, packet, 0, 1);
988 MUTEX_EXIT(&conn->conn_data_lock);
989 rxi_FreePacket(packet);
993 /* Remove from connection hash table before proceeding */
995 &rx_connHashTable[CONN_HASH
996 (peer->host, peer->port, conn->cid, conn->epoch,
998 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
999 if (*conn_ptr == conn) {
1000 *conn_ptr = conn->next;
1004 /* if the conn that we are destroying was the last connection, then we
1005 * clear rxLastConn as well */
1006 if (rxLastConn == conn)
1009 /* Make sure the connection is completely reset before deleting it. */
1010 /* get rid of pending events that could zap us later */
1011 if (conn->challengeEvent)
1012 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1013 if (conn->checkReachEvent)
1014 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1016 /* Add the connection to the list of destroyed connections that
1017 * need to be cleaned up. This is necessary to avoid deadlocks
1018 * in the routines we call to inform others that this connection is
1019 * being destroyed. */
1020 conn->next = rx_connCleanup_list;
1021 rx_connCleanup_list = conn;
1024 /* Externally available version */
1026 rx_DestroyConnection(register struct rx_connection *conn)
1031 rxi_DestroyConnection(conn);
1036 rx_GetConnection(register struct rx_connection *conn)
1041 MUTEX_ENTER(&conn->conn_data_lock);
1043 MUTEX_EXIT(&conn->conn_data_lock);
1047 /* Start a new rx remote procedure call, on the specified connection.
1048 * If wait is set to 1, wait for a free call channel; otherwise return
1049 * 0. Maxtime gives the maximum number of seconds this call may take,
1050 * after rx_MakeCall returns. After this time interval, a call to any
1051 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1052 * For fine grain locking, we hold the conn_call_lock in order to
1053 * to ensure that we don't get signalle after we found a call in an active
1054 * state and before we go to sleep.
1057 rx_NewCall(register struct rx_connection *conn)
1060 register struct rx_call *call;
1061 struct clock queueTime;
1065 dpf(("rx_MakeCall(conn %x)\n", conn));
1068 clock_GetTime(&queueTime);
1069 MUTEX_ENTER(&conn->conn_call_lock);
1072 * Check if there are others waiting for a new call.
1073 * If so, let them go first to avoid starving them.
1074 * This is a fairly simple scheme, and might not be
1075 * a complete solution for large numbers of waiters.
1077 * makeCallWaiters keeps track of the number of
1078 * threads waiting to make calls and the
1079 * RX_CONN_MAKECALL_WAITING flag bit is used to
1080 * indicate that there are indeed calls waiting.
1081 * The flag is set when the waiter is incremented.
1082 * It is only cleared in rx_EndCall when
1083 * makeCallWaiters is 0. This prevents us from
1084 * accidently destroying the connection while it
1085 * is potentially about to be used.
1087 MUTEX_ENTER(&conn->conn_data_lock);
1088 if (conn->makeCallWaiters) {
1089 conn->flags |= RX_CONN_MAKECALL_WAITING;
1090 conn->makeCallWaiters++;
1091 MUTEX_EXIT(&conn->conn_data_lock);
1093 #ifdef RX_ENABLE_LOCKS
1094 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1098 MUTEX_ENTER(&conn->conn_data_lock);
1099 conn->makeCallWaiters--;
1101 MUTEX_EXIT(&conn->conn_data_lock);
1104 for (i = 0; i < RX_MAXCALLS; i++) {
1105 call = conn->call[i];
1107 MUTEX_ENTER(&call->lock);
1108 if (call->state == RX_STATE_DALLY) {
1109 rxi_ResetCall(call, 0);
1110 (*call->callNumber)++;
1113 MUTEX_EXIT(&call->lock);
1115 call = rxi_NewCall(conn, i);
1119 if (i < RX_MAXCALLS) {
1122 MUTEX_ENTER(&conn->conn_data_lock);
1123 conn->flags |= RX_CONN_MAKECALL_WAITING;
1124 conn->makeCallWaiters++;
1125 MUTEX_EXIT(&conn->conn_data_lock);
1127 #ifdef RX_ENABLE_LOCKS
1128 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1132 MUTEX_ENTER(&conn->conn_data_lock);
1133 conn->makeCallWaiters--;
1134 MUTEX_EXIT(&conn->conn_data_lock);
1137 * Wake up anyone else who might be giving us a chance to
1138 * run (see code above that avoids resource starvation).
1140 #ifdef RX_ENABLE_LOCKS
1141 CV_BROADCAST(&conn->conn_call_cv);
1146 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1148 /* Client is initially in send mode */
1149 call->state = RX_STATE_ACTIVE;
1150 call->mode = RX_MODE_SENDING;
1152 /* remember start time for call in case we have hard dead time limit */
1153 call->queueTime = queueTime;
1154 clock_GetTime(&call->startTime);
1155 hzero(call->bytesSent);
1156 hzero(call->bytesRcvd);
1158 /* Turn on busy protocol. */
1159 rxi_KeepAliveOn(call);
1161 MUTEX_EXIT(&call->lock);
1162 MUTEX_EXIT(&conn->conn_call_lock);
1165 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1166 /* Now, if TQ wasn't cleared earlier, do it now. */
1167 MUTEX_ENTER(&call->lock);
1168 while (call->flags & RX_CALL_TQ_BUSY) {
1169 call->flags |= RX_CALL_TQ_WAIT;
1170 #ifdef RX_ENABLE_LOCKS
1171 CV_WAIT(&call->cv_tq, &call->lock);
1172 #else /* RX_ENABLE_LOCKS */
1173 osi_rxSleep(&call->tq);
1174 #endif /* RX_ENABLE_LOCKS */
1176 if (call->flags & RX_CALL_TQ_CLEARME) {
1177 rxi_ClearTransmitQueue(call, 0);
1178 queue_Init(&call->tq);
1180 MUTEX_EXIT(&call->lock);
1181 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1187 rxi_HasActiveCalls(register struct rx_connection *aconn)
1190 register struct rx_call *tcall;
1194 for (i = 0; i < RX_MAXCALLS; i++) {
1195 if ((tcall = aconn->call[i])) {
1196 if ((tcall->state == RX_STATE_ACTIVE)
1197 || (tcall->state == RX_STATE_PRECALL)) {
1208 rxi_GetCallNumberVector(register struct rx_connection *aconn,
1209 register afs_int32 * aint32s)
1212 register struct rx_call *tcall;
1216 for (i = 0; i < RX_MAXCALLS; i++) {
1217 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1218 aint32s[i] = aconn->callNumber[i] + 1;
1220 aint32s[i] = aconn->callNumber[i];
1227 rxi_SetCallNumberVector(register struct rx_connection *aconn,
1228 register afs_int32 * aint32s)
1231 register struct rx_call *tcall;
1235 for (i = 0; i < RX_MAXCALLS; i++) {
1236 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1237 aconn->callNumber[i] = aint32s[i] - 1;
1239 aconn->callNumber[i] = aint32s[i];
1245 /* Advertise a new service. A service is named locally by a UDP port
1246 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1249 char *serviceName; Name for identification purposes (e.g. the
1250 service name might be used for probing for
1253 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1254 struct rx_securityClass **securityObjects, int nSecurityObjects,
1255 afs_int32(*serviceProc) (struct rx_call * acall))
1257 osi_socket socket = OSI_NULLSOCKET;
1258 register struct rx_service *tservice;
1264 if (serviceId == 0) {
1266 "rx_NewService: service id for service %s is not non-zero.\n",
1273 "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",
1281 tservice = rxi_AllocService();
1283 for (i = 0; i < RX_MAX_SERVICES; i++) {
1284 register struct rx_service *service = rx_services[i];
1286 if (port == service->servicePort) {
1287 if (service->serviceId == serviceId) {
1288 /* The identical service has already been
1289 * installed; if the caller was intending to
1290 * change the security classes used by this
1291 * service, he/she loses. */
1293 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1294 serviceName, serviceId, service->serviceName);
1296 rxi_FreeService(tservice);
1299 /* Different service, same port: re-use the socket
1300 * which is bound to the same port */
1301 socket = service->socket;
1304 if (socket == OSI_NULLSOCKET) {
1305 /* If we don't already have a socket (from another
1306 * service on same port) get a new one */
1307 socket = rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
1308 if (socket == OSI_NULLSOCKET) {
1310 rxi_FreeService(tservice);
1315 service->socket = socket;
1316 service->servicePort = port;
1317 service->serviceId = serviceId;
1318 service->serviceName = serviceName;
1319 service->nSecurityObjects = nSecurityObjects;
1320 service->securityObjects = securityObjects;
1321 service->minProcs = 0;
1322 service->maxProcs = 1;
1323 service->idleDeadTime = 60;
1324 service->connDeadTime = rx_connDeadTime;
1325 service->executeRequestProc = serviceProc;
1326 service->checkReach = 0;
1327 rx_services[i] = service; /* not visible until now */
1333 rxi_FreeService(tservice);
1334 (osi_Msg "rx_NewService: cannot support > %d services\n",
1339 /* Generic request processing loop. This routine should be called
1340 * by the implementation dependent rx_ServerProc. If socketp is
1341 * non-null, it will be set to the file descriptor that this thread
1342 * is now listening on. If socketp is null, this routine will never
1345 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1347 register struct rx_call *call;
1348 register afs_int32 code;
1349 register struct rx_service *tservice = NULL;
1356 call = rx_GetCall(threadID, tservice, socketp);
1357 if (socketp && *socketp != OSI_NULLSOCKET) {
1358 /* We are now a listener thread */
1363 /* if server is restarting( typically smooth shutdown) then do not
1364 * allow any new calls.
1367 if (rx_tranquil && (call != NULL)) {
1371 MUTEX_ENTER(&call->lock);
1373 rxi_CallError(call, RX_RESTARTING);
1374 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1376 MUTEX_EXIT(&call->lock);
1380 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1381 #ifdef RX_ENABLE_LOCKS
1383 #endif /* RX_ENABLE_LOCKS */
1384 afs_termState = AFSOP_STOP_AFS;
1385 afs_osi_Wakeup(&afs_termState);
1386 #ifdef RX_ENABLE_LOCKS
1388 #endif /* RX_ENABLE_LOCKS */
1393 tservice = call->conn->service;
1395 if (tservice->beforeProc)
1396 (*tservice->beforeProc) (call);
1398 code = call->conn->service->executeRequestProc(call);
1400 if (tservice->afterProc)
1401 (*tservice->afterProc) (call, code);
1403 rx_EndCall(call, code);
1404 MUTEX_ENTER(&rx_stats_mutex);
1406 MUTEX_EXIT(&rx_stats_mutex);
1412 rx_WakeupServerProcs(void)
1414 struct rx_serverQueueEntry *np, *tqp;
1418 MUTEX_ENTER(&rx_serverPool_lock);
1420 #ifdef RX_ENABLE_LOCKS
1421 if (rx_waitForPacket)
1422 CV_BROADCAST(&rx_waitForPacket->cv);
1423 #else /* RX_ENABLE_LOCKS */
1424 if (rx_waitForPacket)
1425 osi_rxWakeup(rx_waitForPacket);
1426 #endif /* RX_ENABLE_LOCKS */
1427 MUTEX_ENTER(&freeSQEList_lock);
1428 for (np = rx_FreeSQEList; np; np = tqp) {
1429 tqp = *(struct rx_serverQueueEntry **)np;
1430 #ifdef RX_ENABLE_LOCKS
1431 CV_BROADCAST(&np->cv);
1432 #else /* RX_ENABLE_LOCKS */
1434 #endif /* RX_ENABLE_LOCKS */
1436 MUTEX_EXIT(&freeSQEList_lock);
1437 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1438 #ifdef RX_ENABLE_LOCKS
1439 CV_BROADCAST(&np->cv);
1440 #else /* RX_ENABLE_LOCKS */
1442 #endif /* RX_ENABLE_LOCKS */
1444 MUTEX_EXIT(&rx_serverPool_lock);
1449 * One thing that seems to happen is that all the server threads get
1450 * tied up on some empty or slow call, and then a whole bunch of calls
1451 * arrive at once, using up the packet pool, so now there are more
1452 * empty calls. The most critical resources here are server threads
1453 * and the free packet pool. The "doreclaim" code seems to help in
1454 * general. I think that eventually we arrive in this state: there
1455 * are lots of pending calls which do have all their packets present,
1456 * so they won't be reclaimed, are multi-packet calls, so they won't
1457 * be scheduled until later, and thus are tying up most of the free
1458 * packet pool for a very long time.
1460 * 1. schedule multi-packet calls if all the packets are present.
1461 * Probably CPU-bound operation, useful to return packets to pool.
1462 * Do what if there is a full window, but the last packet isn't here?
1463 * 3. preserve one thread which *only* runs "best" calls, otherwise
1464 * it sleeps and waits for that type of call.
1465 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1466 * the current dataquota business is badly broken. The quota isn't adjusted
1467 * to reflect how many packets are presently queued for a running call.
1468 * So, when we schedule a queued call with a full window of packets queued
1469 * up for it, that *should* free up a window full of packets for other 2d-class
1470 * calls to be able to use from the packet pool. But it doesn't.
1472 * NB. Most of the time, this code doesn't run -- since idle server threads
1473 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1474 * as a new call arrives.
1476 /* Sleep until a call arrives. Returns a pointer to the call, ready
1477 * for an rx_Read. */
1478 #ifdef RX_ENABLE_LOCKS
1480 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1482 struct rx_serverQueueEntry *sq;
1483 register struct rx_call *call = (struct rx_call *)0;
1484 struct rx_service *service = NULL;
1487 MUTEX_ENTER(&freeSQEList_lock);
1489 if ((sq = rx_FreeSQEList)) {
1490 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1491 MUTEX_EXIT(&freeSQEList_lock);
1492 } else { /* otherwise allocate a new one and return that */
1493 MUTEX_EXIT(&freeSQEList_lock);
1494 sq = (struct rx_serverQueueEntry *)
1495 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1496 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1497 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1500 MUTEX_ENTER(&rx_serverPool_lock);
1501 if (cur_service != NULL) {
1502 ReturnToServerPool(cur_service);
1505 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1506 register struct rx_call *tcall, *ncall, *choice2 = NULL;
1508 /* Scan for eligible incoming calls. A call is not eligible
1509 * if the maximum number of calls for its service type are
1510 * already executing */
1511 /* One thread will process calls FCFS (to prevent starvation),
1512 * while the other threads may run ahead looking for calls which
1513 * have all their input data available immediately. This helps
1514 * keep threads from blocking, waiting for data from the client. */
1515 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1516 service = tcall->conn->service;
1517 if (!QuotaOK(service)) {
1520 if (tno == rxi_fcfs_thread_num
1521 || !tcall->queue_item_header.next) {
1522 /* If we're the fcfs thread , then we'll just use
1523 * this call. If we haven't been able to find an optimal
1524 * choice, and we're at the end of the list, then use a
1525 * 2d choice if one has been identified. Otherwise... */
1526 call = (choice2 ? choice2 : tcall);
1527 service = call->conn->service;
1528 } else if (!queue_IsEmpty(&tcall->rq)) {
1529 struct rx_packet *rp;
1530 rp = queue_First(&tcall->rq, rx_packet);
1531 if (rp->header.seq == 1) {
1533 || (rp->header.flags & RX_LAST_PACKET)) {
1535 } else if (rxi_2dchoice && !choice2
1536 && !(tcall->flags & RX_CALL_CLEARED)
1537 && (tcall->rprev > rxi_HardAckRate)) {
1546 ReturnToServerPool(service);
1553 MUTEX_EXIT(&rx_serverPool_lock);
1554 MUTEX_ENTER(&call->lock);
1556 if (call->flags & RX_CALL_WAIT_PROC) {
1557 call->flags &= ~RX_CALL_WAIT_PROC;
1558 MUTEX_ENTER(&rx_stats_mutex);
1560 MUTEX_EXIT(&rx_stats_mutex);
1563 if (call->state != RX_STATE_PRECALL || call->error) {
1564 MUTEX_EXIT(&call->lock);
1565 MUTEX_ENTER(&rx_serverPool_lock);
1566 ReturnToServerPool(service);
1571 if (queue_IsEmpty(&call->rq)
1572 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1573 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1575 CLEAR_CALL_QUEUE_LOCK(call);
1578 /* If there are no eligible incoming calls, add this process
1579 * to the idle server queue, to wait for one */
1583 *socketp = OSI_NULLSOCKET;
1585 sq->socketp = socketp;
1586 queue_Append(&rx_idleServerQueue, sq);
1587 #ifndef AFS_AIX41_ENV
1588 rx_waitForPacket = sq;
1590 rx_waitingForPacket = sq;
1591 #endif /* AFS_AIX41_ENV */
1593 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1595 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1596 MUTEX_EXIT(&rx_serverPool_lock);
1597 return (struct rx_call *)0;
1600 } while (!(call = sq->newcall)
1601 && !(socketp && *socketp != OSI_NULLSOCKET));
1602 MUTEX_EXIT(&rx_serverPool_lock);
1604 MUTEX_ENTER(&call->lock);
1610 MUTEX_ENTER(&freeSQEList_lock);
1611 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1612 rx_FreeSQEList = sq;
1613 MUTEX_EXIT(&freeSQEList_lock);
1616 clock_GetTime(&call->startTime);
1617 call->state = RX_STATE_ACTIVE;
1618 call->mode = RX_MODE_RECEIVING;
1619 #ifdef RX_KERNEL_TRACE
1620 if (ICL_SETACTIVE(afs_iclSetp)) {
1621 int glockOwner = ISAFS_GLOCK();
1624 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1625 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1632 rxi_calltrace(RX_CALL_START, call);
1633 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1634 call->conn->service->servicePort, call->conn->service->serviceId,
1637 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1638 MUTEX_EXIT(&call->lock);
1640 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1645 #else /* RX_ENABLE_LOCKS */
1647 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1649 struct rx_serverQueueEntry *sq;
1650 register struct rx_call *call = (struct rx_call *)0, *choice2;
1651 struct rx_service *service = NULL;
1655 MUTEX_ENTER(&freeSQEList_lock);
1657 if ((sq = rx_FreeSQEList)) {
1658 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1659 MUTEX_EXIT(&freeSQEList_lock);
1660 } else { /* otherwise allocate a new one and return that */
1661 MUTEX_EXIT(&freeSQEList_lock);
1662 sq = (struct rx_serverQueueEntry *)
1663 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1664 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1665 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1667 MUTEX_ENTER(&sq->lock);
1669 if (cur_service != NULL) {
1670 cur_service->nRequestsRunning--;
1671 if (cur_service->nRequestsRunning < cur_service->minProcs)
1675 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1676 register struct rx_call *tcall, *ncall;
1677 /* Scan for eligible incoming calls. A call is not eligible
1678 * if the maximum number of calls for its service type are
1679 * already executing */
1680 /* One thread will process calls FCFS (to prevent starvation),
1681 * while the other threads may run ahead looking for calls which
1682 * have all their input data available immediately. This helps
1683 * keep threads from blocking, waiting for data from the client. */
1684 choice2 = (struct rx_call *)0;
1685 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1686 service = tcall->conn->service;
1687 if (QuotaOK(service)) {
1688 if (tno == rxi_fcfs_thread_num
1689 || !tcall->queue_item_header.next) {
1690 /* If we're the fcfs thread, then we'll just use
1691 * this call. If we haven't been able to find an optimal
1692 * choice, and we're at the end of the list, then use a
1693 * 2d choice if one has been identified. Otherwise... */
1694 call = (choice2 ? choice2 : tcall);
1695 service = call->conn->service;
1696 } else if (!queue_IsEmpty(&tcall->rq)) {
1697 struct rx_packet *rp;
1698 rp = queue_First(&tcall->rq, rx_packet);
1699 if (rp->header.seq == 1
1701 || (rp->header.flags & RX_LAST_PACKET))) {
1703 } else if (rxi_2dchoice && !choice2
1704 && !(tcall->flags & RX_CALL_CLEARED)
1705 && (tcall->rprev > rxi_HardAckRate)) {
1718 /* we can't schedule a call if there's no data!!! */
1719 /* send an ack if there's no data, if we're missing the
1720 * first packet, or we're missing something between first
1721 * and last -- there's a "hole" in the incoming data. */
1722 if (queue_IsEmpty(&call->rq)
1723 || queue_First(&call->rq, rx_packet)->header.seq != 1
1724 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1725 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1727 call->flags &= (~RX_CALL_WAIT_PROC);
1728 service->nRequestsRunning++;
1729 /* just started call in minProcs pool, need fewer to maintain
1731 if (service->nRequestsRunning <= service->minProcs)
1735 /* MUTEX_EXIT(&call->lock); */
1737 /* If there are no eligible incoming calls, add this process
1738 * to the idle server queue, to wait for one */
1741 *socketp = OSI_NULLSOCKET;
1743 sq->socketp = socketp;
1744 queue_Append(&rx_idleServerQueue, sq);
1748 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1750 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1751 return (struct rx_call *)0;
1754 } while (!(call = sq->newcall)
1755 && !(socketp && *socketp != OSI_NULLSOCKET));
1757 MUTEX_EXIT(&sq->lock);
1759 MUTEX_ENTER(&freeSQEList_lock);
1760 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1761 rx_FreeSQEList = sq;
1762 MUTEX_EXIT(&freeSQEList_lock);
1765 clock_GetTime(&call->startTime);
1766 call->state = RX_STATE_ACTIVE;
1767 call->mode = RX_MODE_RECEIVING;
1768 #ifdef RX_KERNEL_TRACE
1769 if (ICL_SETACTIVE(afs_iclSetp)) {
1770 int glockOwner = ISAFS_GLOCK();
1773 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1774 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1781 rxi_calltrace(RX_CALL_START, call);
1782 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1783 call->conn->service->servicePort, call->conn->service->serviceId,
1786 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1793 #endif /* RX_ENABLE_LOCKS */
1797 /* Establish a procedure to be called when a packet arrives for a
1798 * call. This routine will be called at most once after each call,
1799 * and will also be called if there is an error condition on the or
1800 * the call is complete. Used by multi rx to build a selection
1801 * function which determines which of several calls is likely to be a
1802 * good one to read from.
1803 * NOTE: the way this is currently implemented it is probably only a
1804 * good idea to (1) use it immediately after a newcall (clients only)
1805 * and (2) only use it once. Other uses currently void your warranty
1808 rx_SetArrivalProc(register struct rx_call *call,
1809 register void (*proc) (register struct rx_call * call,
1811 register int index),
1812 register VOID * handle, register int arg)
1814 call->arrivalProc = proc;
1815 call->arrivalProcHandle = handle;
1816 call->arrivalProcArg = arg;
1819 /* Call is finished (possibly prematurely). Return rc to the peer, if
1820 * appropriate, and return the final error code from the conversation
1824 rx_EndCall(register struct rx_call *call, afs_int32 rc)
1826 register struct rx_connection *conn = call->conn;
1827 register struct rx_service *service;
1828 register struct rx_packet *tp; /* Temporary packet pointer */
1829 register struct rx_packet *nxp; /* Next packet pointer, for queue_Scan */
1833 dpf(("rx_EndCall(call %x)\n", call));
1836 MUTEX_ENTER(&call->lock);
1838 if (rc == 0 && call->error == 0) {
1839 call->abortCode = 0;
1840 call->abortCount = 0;
1843 call->arrivalProc = (void (*)())0;
1844 if (rc && call->error == 0) {
1845 rxi_CallError(call, rc);
1846 /* Send an abort message to the peer if this error code has
1847 * only just been set. If it was set previously, assume the
1848 * peer has already been sent the error code or will request it
1850 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1852 if (conn->type == RX_SERVER_CONNECTION) {
1853 /* Make sure reply or at least dummy reply is sent */
1854 if (call->mode == RX_MODE_RECEIVING) {
1855 rxi_WriteProc(call, 0, 0);
1857 if (call->mode == RX_MODE_SENDING) {
1858 rxi_FlushWrite(call);
1860 service = conn->service;
1861 rxi_calltrace(RX_CALL_END, call);
1862 /* Call goes to hold state until reply packets are acknowledged */
1863 if (call->tfirst + call->nSoftAcked < call->tnext) {
1864 call->state = RX_STATE_HOLD;
1866 call->state = RX_STATE_DALLY;
1867 rxi_ClearTransmitQueue(call, 0);
1868 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
1869 rxevent_Cancel(call->keepAliveEvent, call,
1870 RX_CALL_REFCOUNT_ALIVE);
1872 } else { /* Client connection */
1874 /* Make sure server receives input packets, in the case where
1875 * no reply arguments are expected */
1876 if ((call->mode == RX_MODE_SENDING)
1877 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
1878 (void)rxi_ReadProc(call, &dummy, 1);
1881 /* If we had an outstanding delayed ack, be nice to the server
1882 * and force-send it now.
1884 if (call->delayedAckEvent) {
1885 rxevent_Cancel(call->delayedAckEvent, call,
1886 RX_CALL_REFCOUNT_DELAY);
1887 call->delayedAckEvent = NULL;
1888 rxi_SendDelayedAck(NULL, call, NULL);
1891 /* We need to release the call lock since it's lower than the
1892 * conn_call_lock and we don't want to hold the conn_call_lock
1893 * over the rx_ReadProc call. The conn_call_lock needs to be held
1894 * here for the case where rx_NewCall is perusing the calls on
1895 * the connection structure. We don't want to signal until
1896 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
1897 * have checked this call, found it active and by the time it
1898 * goes to sleep, will have missed the signal.
1900 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
1901 * there are threads waiting to use the conn object.
1903 MUTEX_EXIT(&call->lock);
1904 MUTEX_ENTER(&conn->conn_call_lock);
1905 MUTEX_ENTER(&call->lock);
1906 MUTEX_ENTER(&conn->conn_data_lock);
1907 conn->flags |= RX_CONN_BUSY;
1908 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
1909 if (conn->makeCallWaiters == 0)
1910 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
1911 MUTEX_EXIT(&conn->conn_data_lock);
1912 #ifdef RX_ENABLE_LOCKS
1913 CV_BROADCAST(&conn->conn_call_cv);
1918 #ifdef RX_ENABLE_LOCKS
1920 MUTEX_EXIT(&conn->conn_data_lock);
1922 #endif /* RX_ENABLE_LOCKS */
1923 call->state = RX_STATE_DALLY;
1925 error = call->error;
1927 /* currentPacket, nLeft, and NFree must be zeroed here, because
1928 * ResetCall cannot: ResetCall may be called at splnet(), in the
1929 * kernel version, and may interrupt the macros rx_Read or
1930 * rx_Write, which run at normal priority for efficiency. */
1931 if (call->currentPacket) {
1932 rxi_FreePacket(call->currentPacket);
1933 call->currentPacket = (struct rx_packet *)0;
1934 call->nLeft = call->nFree = call->curlen = 0;
1936 call->nLeft = call->nFree = call->curlen = 0;
1938 /* Free any packets from the last call to ReadvProc/WritevProc */
1939 for (queue_Scan(&call->iovq, tp, nxp, rx_packet)) {
1944 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1945 MUTEX_EXIT(&call->lock);
1946 if (conn->type == RX_CLIENT_CONNECTION) {
1947 MUTEX_EXIT(&conn->conn_call_lock);
1948 conn->flags &= ~RX_CONN_BUSY;
1952 * Map errors to the local host's errno.h format.
1954 error = ntoh_syserr_conv(error);
1958 #if !defined(KERNEL)
1960 /* Call this routine when shutting down a server or client (especially
1961 * clients). This will allow Rx to gracefully garbage collect server
1962 * connections, and reduce the number of retries that a server might
1963 * make to a dead client.
1964 * This is not quite right, since some calls may still be ongoing and
1965 * we can't lock them to destroy them. */
1969 register struct rx_connection **conn_ptr, **conn_end;
1973 if (rxinit_status == 1) {
1975 return; /* Already shutdown. */
1977 rxi_DeleteCachedConnections();
1978 if (rx_connHashTable) {
1979 MUTEX_ENTER(&rx_connHashTable_lock);
1980 for (conn_ptr = &rx_connHashTable[0], conn_end =
1981 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
1983 struct rx_connection *conn, *next;
1984 for (conn = *conn_ptr; conn; conn = next) {
1986 if (conn->type == RX_CLIENT_CONNECTION) {
1987 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
1989 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
1990 #ifdef RX_ENABLE_LOCKS
1991 rxi_DestroyConnectionNoLock(conn);
1992 #else /* RX_ENABLE_LOCKS */
1993 rxi_DestroyConnection(conn);
1994 #endif /* RX_ENABLE_LOCKS */
1998 #ifdef RX_ENABLE_LOCKS
1999 while (rx_connCleanup_list) {
2000 struct rx_connection *conn;
2001 conn = rx_connCleanup_list;
2002 rx_connCleanup_list = rx_connCleanup_list->next;
2003 MUTEX_EXIT(&rx_connHashTable_lock);
2004 rxi_CleanupConnection(conn);
2005 MUTEX_ENTER(&rx_connHashTable_lock);
2007 MUTEX_EXIT(&rx_connHashTable_lock);
2008 #endif /* RX_ENABLE_LOCKS */
2017 /* if we wakeup packet waiter too often, can get in loop with two
2018 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2020 rxi_PacketsUnWait(void)
2022 if (!rx_waitingForPackets) {
2026 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2027 return; /* still over quota */
2030 rx_waitingForPackets = 0;
2031 #ifdef RX_ENABLE_LOCKS
2032 CV_BROADCAST(&rx_waitingForPackets_cv);
2034 osi_rxWakeup(&rx_waitingForPackets);
2040 /* ------------------Internal interfaces------------------------- */
2042 /* Return this process's service structure for the
2043 * specified socket and service */
2045 rxi_FindService(register osi_socket socket, register u_short serviceId)
2047 register struct rx_service **sp;
2048 for (sp = &rx_services[0]; *sp; sp++) {
2049 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2055 /* Allocate a call structure, for the indicated channel of the
2056 * supplied connection. The mode and state of the call must be set by
2057 * the caller. Returns the call with mutex locked. */
2059 rxi_NewCall(register struct rx_connection *conn, register int channel)
2061 register struct rx_call *call;
2062 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2063 register struct rx_call *cp; /* Call pointer temp */
2064 register struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2065 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2067 /* Grab an existing call structure, or allocate a new one.
2068 * Existing call structures are assumed to have been left reset by
2070 MUTEX_ENTER(&rx_freeCallQueue_lock);
2072 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2074 * EXCEPT that the TQ might not yet be cleared out.
2075 * Skip over those with in-use TQs.
2078 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2079 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2085 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2086 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2087 call = queue_First(&rx_freeCallQueue, rx_call);
2088 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2090 MUTEX_ENTER(&rx_stats_mutex);
2091 rx_stats.nFreeCallStructs--;
2092 MUTEX_EXIT(&rx_stats_mutex);
2093 MUTEX_EXIT(&rx_freeCallQueue_lock);
2094 MUTEX_ENTER(&call->lock);
2095 CLEAR_CALL_QUEUE_LOCK(call);
2096 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2097 /* Now, if TQ wasn't cleared earlier, do it now. */
2098 if (call->flags & RX_CALL_TQ_CLEARME) {
2099 rxi_ClearTransmitQueue(call, 0);
2100 queue_Init(&call->tq);
2102 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2103 /* Bind the call to its connection structure */
2105 rxi_ResetCall(call, 1);
2107 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2109 MUTEX_EXIT(&rx_freeCallQueue_lock);
2110 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2111 MUTEX_ENTER(&call->lock);
2112 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2113 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2114 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2116 MUTEX_ENTER(&rx_stats_mutex);
2117 rx_stats.nCallStructs++;
2118 MUTEX_EXIT(&rx_stats_mutex);
2119 /* Initialize once-only items */
2120 queue_Init(&call->tq);
2121 queue_Init(&call->rq);
2122 queue_Init(&call->iovq);
2123 /* Bind the call to its connection structure (prereq for reset) */
2125 rxi_ResetCall(call, 1);
2127 call->channel = channel;
2128 call->callNumber = &conn->callNumber[channel];
2129 /* Note that the next expected call number is retained (in
2130 * conn->callNumber[i]), even if we reallocate the call structure
2132 conn->call[channel] = call;
2133 /* if the channel's never been used (== 0), we should start at 1, otherwise
2134 * the call number is valid from the last time this channel was used */
2135 if (*call->callNumber == 0)
2136 *call->callNumber = 1;
2141 /* A call has been inactive long enough that so we can throw away
2142 * state, including the call structure, which is placed on the call
2144 * Call is locked upon entry.
2145 * haveCTLock set if called from rxi_ReapConnections
2147 #ifdef RX_ENABLE_LOCKS
2149 rxi_FreeCall(register struct rx_call *call, int haveCTLock)
2150 #else /* RX_ENABLE_LOCKS */
2152 rxi_FreeCall(register struct rx_call *call)
2153 #endif /* RX_ENABLE_LOCKS */
2155 register int channel = call->channel;
2156 register struct rx_connection *conn = call->conn;
2159 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2160 (*call->callNumber)++;
2161 rxi_ResetCall(call, 0);
2162 call->conn->call[channel] = (struct rx_call *)0;
2164 MUTEX_ENTER(&rx_freeCallQueue_lock);
2165 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2166 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2167 /* A call may be free even though its transmit queue is still in use.
2168 * Since we search the call list from head to tail, put busy calls at
2169 * the head of the list, and idle calls at the tail.
2171 if (call->flags & RX_CALL_TQ_BUSY)
2172 queue_Prepend(&rx_freeCallQueue, call);
2174 queue_Append(&rx_freeCallQueue, call);
2175 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2176 queue_Append(&rx_freeCallQueue, call);
2177 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2178 MUTEX_ENTER(&rx_stats_mutex);
2179 rx_stats.nFreeCallStructs++;
2180 MUTEX_EXIT(&rx_stats_mutex);
2182 MUTEX_EXIT(&rx_freeCallQueue_lock);
2184 /* Destroy the connection if it was previously slated for
2185 * destruction, i.e. the Rx client code previously called
2186 * rx_DestroyConnection (client connections), or
2187 * rxi_ReapConnections called the same routine (server
2188 * connections). Only do this, however, if there are no
2189 * outstanding calls. Note that for fine grain locking, there appears
2190 * to be a deadlock in that rxi_FreeCall has a call locked and
2191 * DestroyConnectionNoLock locks each call in the conn. But note a
2192 * few lines up where we have removed this call from the conn.
2193 * If someone else destroys a connection, they either have no
2194 * call lock held or are going through this section of code.
2196 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2197 MUTEX_ENTER(&conn->conn_data_lock);
2199 MUTEX_EXIT(&conn->conn_data_lock);
2200 #ifdef RX_ENABLE_LOCKS
2202 rxi_DestroyConnectionNoLock(conn);
2204 rxi_DestroyConnection(conn);
2205 #else /* RX_ENABLE_LOCKS */
2206 rxi_DestroyConnection(conn);
2207 #endif /* RX_ENABLE_LOCKS */
2211 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2213 rxi_Alloc(register size_t size)
2217 MUTEX_ENTER(&rx_stats_mutex);
2219 rxi_Allocsize += size;
2220 MUTEX_EXIT(&rx_stats_mutex);
2222 p = (char *)osi_Alloc(size);
2225 osi_Panic("rxi_Alloc error");
2231 rxi_Free(void *addr, register size_t size)
2233 MUTEX_ENTER(&rx_stats_mutex);
2235 rxi_Allocsize -= size;
2236 MUTEX_EXIT(&rx_stats_mutex);
2238 osi_Free(addr, size);
2241 /* Find the peer process represented by the supplied (host,port)
2242 * combination. If there is no appropriate active peer structure, a
2243 * new one will be allocated and initialized
2244 * The origPeer, if set, is a pointer to a peer structure on which the
2245 * refcount will be be decremented. This is used to replace the peer
2246 * structure hanging off a connection structure */
2248 rxi_FindPeer(register afs_uint32 host, register u_short port,
2249 struct rx_peer *origPeer, int create)
2251 register struct rx_peer *pp;
2253 hashIndex = PEER_HASH(host, port);
2254 MUTEX_ENTER(&rx_peerHashTable_lock);
2255 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2256 if ((pp->host == host) && (pp->port == port))
2261 pp = rxi_AllocPeer(); /* This bzero's *pp */
2262 pp->host = host; /* set here or in InitPeerParams is zero */
2264 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2265 queue_Init(&pp->congestionQueue);
2266 queue_Init(&pp->rpcStats);
2267 pp->next = rx_peerHashTable[hashIndex];
2268 rx_peerHashTable[hashIndex] = pp;
2269 rxi_InitPeerParams(pp);
2270 MUTEX_ENTER(&rx_stats_mutex);
2271 rx_stats.nPeerStructs++;
2272 MUTEX_EXIT(&rx_stats_mutex);
2279 origPeer->refCount--;
2280 MUTEX_EXIT(&rx_peerHashTable_lock);
2285 /* Find the connection at (host, port) started at epoch, and with the
2286 * given connection id. Creates the server connection if necessary.
2287 * The type specifies whether a client connection or a server
2288 * connection is desired. In both cases, (host, port) specify the
2289 * peer's (host, pair) pair. Client connections are not made
2290 * automatically by this routine. The parameter socket gives the
2291 * socket descriptor on which the packet was received. This is used,
2292 * in the case of server connections, to check that *new* connections
2293 * come via a valid (port, serviceId). Finally, the securityIndex
2294 * parameter must match the existing index for the connection. If a
2295 * server connection is created, it will be created using the supplied
2296 * index, if the index is valid for this service */
2297 struct rx_connection *
2298 rxi_FindConnection(osi_socket socket, register afs_int32 host,
2299 register u_short port, u_short serviceId, afs_uint32 cid,
2300 afs_uint32 epoch, int type, u_int securityIndex)
2302 int hashindex, flag;
2303 register struct rx_connection *conn;
2304 hashindex = CONN_HASH(host, port, cid, epoch, type);
2305 MUTEX_ENTER(&rx_connHashTable_lock);
2306 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2307 rx_connHashTable[hashindex],
2310 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2311 && (epoch == conn->epoch)) {
2312 register struct rx_peer *pp = conn->peer;
2313 if (securityIndex != conn->securityIndex) {
2314 /* this isn't supposed to happen, but someone could forge a packet
2315 * like this, and there seems to be some CM bug that makes this
2316 * happen from time to time -- in which case, the fileserver
2318 MUTEX_EXIT(&rx_connHashTable_lock);
2319 return (struct rx_connection *)0;
2321 if (pp->host == host && pp->port == port)
2323 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2325 /* So what happens when it's a callback connection? */
2326 if ( /*type == RX_CLIENT_CONNECTION && */
2327 (conn->epoch & 0x80000000))
2331 /* the connection rxLastConn that was used the last time is not the
2332 ** one we are looking for now. Hence, start searching in the hash */
2334 conn = rx_connHashTable[hashindex];
2339 struct rx_service *service;
2340 if (type == RX_CLIENT_CONNECTION) {
2341 MUTEX_EXIT(&rx_connHashTable_lock);
2342 return (struct rx_connection *)0;
2344 service = rxi_FindService(socket, serviceId);
2345 if (!service || (securityIndex >= service->nSecurityObjects)
2346 || (service->securityObjects[securityIndex] == 0)) {
2347 MUTEX_EXIT(&rx_connHashTable_lock);
2348 return (struct rx_connection *)0;
2350 conn = rxi_AllocConnection(); /* This bzero's the connection */
2351 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2352 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2353 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2354 conn->next = rx_connHashTable[hashindex];
2355 rx_connHashTable[hashindex] = conn;
2356 conn->peer = rxi_FindPeer(host, port, 0, 1);
2357 conn->type = RX_SERVER_CONNECTION;
2358 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2359 conn->epoch = epoch;
2360 conn->cid = cid & RX_CIDMASK;
2361 /* conn->serial = conn->lastSerial = 0; */
2362 /* conn->timeout = 0; */
2363 conn->ackRate = RX_FAST_ACK_RATE;
2364 conn->service = service;
2365 conn->serviceId = serviceId;
2366 conn->securityIndex = securityIndex;
2367 conn->securityObject = service->securityObjects[securityIndex];
2368 conn->nSpecific = 0;
2369 conn->specific = NULL;
2370 rx_SetConnDeadTime(conn, service->connDeadTime);
2371 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2372 /* Notify security object of the new connection */
2373 RXS_NewConnection(conn->securityObject, conn);
2374 /* XXXX Connection timeout? */
2375 if (service->newConnProc)
2376 (*service->newConnProc) (conn);
2377 MUTEX_ENTER(&rx_stats_mutex);
2378 rx_stats.nServerConns++;
2379 MUTEX_EXIT(&rx_stats_mutex);
2382 MUTEX_ENTER(&conn->conn_data_lock);
2384 MUTEX_EXIT(&conn->conn_data_lock);
2386 rxLastConn = conn; /* store this connection as the last conn used */
2387 MUTEX_EXIT(&rx_connHashTable_lock);
2391 /* There are two packet tracing routines available for testing and monitoring
2392 * Rx. One is called just after every packet is received and the other is
2393 * called just before every packet is sent. Received packets, have had their
2394 * headers decoded, and packets to be sent have not yet had their headers
2395 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2396 * containing the network address. Both can be modified. The return value, if
2397 * non-zero, indicates that the packet should be dropped. */
2399 int (*rx_justReceived) () = 0;
2400 int (*rx_almostSent) () = 0;
2402 /* A packet has been received off the interface. Np is the packet, socket is
2403 * the socket number it was received from (useful in determining which service
2404 * this packet corresponds to), and (host, port) reflect the host,port of the
2405 * sender. This call returns the packet to the caller if it is finished with
2406 * it, rather than de-allocating it, just as a small performance hack */
2409 rxi_ReceivePacket(register struct rx_packet *np, osi_socket socket,
2410 afs_uint32 host, u_short port, int *tnop,
2411 struct rx_call **newcallp)
2413 register struct rx_call *call;
2414 register struct rx_connection *conn;
2416 afs_uint32 currentCallNumber;
2422 struct rx_packet *tnp;
2425 /* We don't print out the packet until now because (1) the time may not be
2426 * accurate enough until now in the lwp implementation (rx_Listener only gets
2427 * the time after the packet is read) and (2) from a protocol point of view,
2428 * this is the first time the packet has been seen */
2429 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2430 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2431 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2432 np->header.serial, packetType, host, port, np->header.serviceId,
2433 np->header.epoch, np->header.cid, np->header.callNumber,
2434 np->header.seq, np->header.flags, np));
2437 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2438 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2441 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2442 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2445 /* If an input tracer function is defined, call it with the packet and
2446 * network address. Note this function may modify its arguments. */
2447 if (rx_justReceived) {
2448 struct sockaddr_in addr;
2450 addr.sin_family = AF_INET;
2451 addr.sin_port = port;
2452 addr.sin_addr.s_addr = host;
2453 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2454 addr.sin_len = sizeof(addr);
2455 #endif /* AFS_OSF_ENV */
2456 drop = (*rx_justReceived) (np, &addr);
2457 /* drop packet if return value is non-zero */
2460 port = addr.sin_port; /* in case fcn changed addr */
2461 host = addr.sin_addr.s_addr;
2465 /* If packet was not sent by the client, then *we* must be the client */
2466 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2467 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2469 /* Find the connection (or fabricate one, if we're the server & if
2470 * necessary) associated with this packet */
2472 rxi_FindConnection(socket, host, port, np->header.serviceId,
2473 np->header.cid, np->header.epoch, type,
2474 np->header.securityIndex);
2477 /* If no connection found or fabricated, just ignore the packet.
2478 * (An argument could be made for sending an abort packet for
2483 MUTEX_ENTER(&conn->conn_data_lock);
2484 if (conn->maxSerial < np->header.serial)
2485 conn->maxSerial = np->header.serial;
2486 MUTEX_EXIT(&conn->conn_data_lock);
2488 /* If the connection is in an error state, send an abort packet and ignore
2489 * the incoming packet */
2491 /* Don't respond to an abort packet--we don't want loops! */
2492 MUTEX_ENTER(&conn->conn_data_lock);
2493 if (np->header.type != RX_PACKET_TYPE_ABORT)
2494 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2496 MUTEX_EXIT(&conn->conn_data_lock);
2500 /* Check for connection-only requests (i.e. not call specific). */
2501 if (np->header.callNumber == 0) {
2502 switch (np->header.type) {
2503 case RX_PACKET_TYPE_ABORT:
2504 /* What if the supplied error is zero? */
2505 rxi_ConnectionError(conn, ntohl(rx_GetInt32(np, 0)));
2506 MUTEX_ENTER(&conn->conn_data_lock);
2508 MUTEX_EXIT(&conn->conn_data_lock);
2510 case RX_PACKET_TYPE_CHALLENGE:
2511 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2512 MUTEX_ENTER(&conn->conn_data_lock);
2514 MUTEX_EXIT(&conn->conn_data_lock);
2516 case RX_PACKET_TYPE_RESPONSE:
2517 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2518 MUTEX_ENTER(&conn->conn_data_lock);
2520 MUTEX_EXIT(&conn->conn_data_lock);
2522 case RX_PACKET_TYPE_PARAMS:
2523 case RX_PACKET_TYPE_PARAMS + 1:
2524 case RX_PACKET_TYPE_PARAMS + 2:
2525 /* ignore these packet types for now */
2526 MUTEX_ENTER(&conn->conn_data_lock);
2528 MUTEX_EXIT(&conn->conn_data_lock);
2533 /* Should not reach here, unless the peer is broken: send an
2535 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2536 MUTEX_ENTER(&conn->conn_data_lock);
2537 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2539 MUTEX_EXIT(&conn->conn_data_lock);
2544 channel = np->header.cid & RX_CHANNELMASK;
2545 call = conn->call[channel];
2546 #ifdef RX_ENABLE_LOCKS
2548 MUTEX_ENTER(&call->lock);
2549 /* Test to see if call struct is still attached to conn. */
2550 if (call != conn->call[channel]) {
2552 MUTEX_EXIT(&call->lock);
2553 if (type == RX_SERVER_CONNECTION) {
2554 call = conn->call[channel];
2555 /* If we started with no call attached and there is one now,
2556 * another thread is also running this routine and has gotten
2557 * the connection channel. We should drop this packet in the tests
2558 * below. If there was a call on this connection and it's now
2559 * gone, then we'll be making a new call below.
2560 * If there was previously a call and it's now different then
2561 * the old call was freed and another thread running this routine
2562 * has created a call on this channel. One of these two threads
2563 * has a packet for the old call and the code below handles those
2567 MUTEX_ENTER(&call->lock);
2569 /* This packet can't be for this call. If the new call address is
2570 * 0 then no call is running on this channel. If there is a call
2571 * then, since this is a client connection we're getting data for
2572 * it must be for the previous call.
2574 MUTEX_ENTER(&rx_stats_mutex);
2575 rx_stats.spuriousPacketsRead++;
2576 MUTEX_EXIT(&rx_stats_mutex);
2577 MUTEX_ENTER(&conn->conn_data_lock);
2579 MUTEX_EXIT(&conn->conn_data_lock);
2584 currentCallNumber = conn->callNumber[channel];
2586 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2587 if (np->header.callNumber < currentCallNumber) {
2588 MUTEX_ENTER(&rx_stats_mutex);
2589 rx_stats.spuriousPacketsRead++;
2590 MUTEX_EXIT(&rx_stats_mutex);
2591 #ifdef RX_ENABLE_LOCKS
2593 MUTEX_EXIT(&call->lock);
2595 MUTEX_ENTER(&conn->conn_data_lock);
2597 MUTEX_EXIT(&conn->conn_data_lock);
2601 MUTEX_ENTER(&conn->conn_call_lock);
2602 call = rxi_NewCall(conn, channel);
2603 MUTEX_EXIT(&conn->conn_call_lock);
2604 *call->callNumber = np->header.callNumber;
2605 call->state = RX_STATE_PRECALL;
2606 clock_GetTime(&call->queueTime);
2607 hzero(call->bytesSent);
2608 hzero(call->bytesRcvd);
2609 rxi_KeepAliveOn(call);
2610 } else if (np->header.callNumber != currentCallNumber) {
2611 /* Wait until the transmit queue is idle before deciding
2612 * whether to reset the current call. Chances are that the
2613 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2616 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2617 while ((call->state == RX_STATE_ACTIVE)
2618 && (call->flags & RX_CALL_TQ_BUSY)) {
2619 call->flags |= RX_CALL_TQ_WAIT;
2620 #ifdef RX_ENABLE_LOCKS
2621 CV_WAIT(&call->cv_tq, &call->lock);
2622 #else /* RX_ENABLE_LOCKS */
2623 osi_rxSleep(&call->tq);
2624 #endif /* RX_ENABLE_LOCKS */
2626 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2627 /* If the new call cannot be taken right now send a busy and set
2628 * the error condition in this call, so that it terminates as
2629 * quickly as possible */
2630 if (call->state == RX_STATE_ACTIVE) {
2631 struct rx_packet *tp;
2633 rxi_CallError(call, RX_CALL_DEAD);
2634 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2636 MUTEX_EXIT(&call->lock);
2637 MUTEX_ENTER(&conn->conn_data_lock);
2639 MUTEX_EXIT(&conn->conn_data_lock);
2642 rxi_ResetCall(call, 0);
2643 *call->callNumber = np->header.callNumber;
2644 call->state = RX_STATE_PRECALL;
2645 clock_GetTime(&call->queueTime);
2646 hzero(call->bytesSent);
2647 hzero(call->bytesRcvd);
2649 * If the number of queued calls exceeds the overload
2650 * threshold then abort this call.
2652 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2653 struct rx_packet *tp;
2655 rxi_CallError(call, rx_BusyError);
2656 tp = rxi_SendCallAbort(call, np, 1, 0);
2657 MUTEX_EXIT(&call->lock);
2658 MUTEX_ENTER(&conn->conn_data_lock);
2660 MUTEX_EXIT(&conn->conn_data_lock);
2661 MUTEX_ENTER(&rx_stats_mutex);
2663 MUTEX_EXIT(&rx_stats_mutex);
2666 rxi_KeepAliveOn(call);
2668 /* Continuing call; do nothing here. */
2670 } else { /* we're the client */
2671 /* Ignore all incoming acknowledgements for calls in DALLY state */
2672 if (call && (call->state == RX_STATE_DALLY)
2673 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2674 MUTEX_ENTER(&rx_stats_mutex);
2675 rx_stats.ignorePacketDally++;
2676 MUTEX_EXIT(&rx_stats_mutex);
2677 #ifdef RX_ENABLE_LOCKS
2679 MUTEX_EXIT(&call->lock);
2682 MUTEX_ENTER(&conn->conn_data_lock);
2684 MUTEX_EXIT(&conn->conn_data_lock);
2688 /* Ignore anything that's not relevant to the current call. If there
2689 * isn't a current call, then no packet is relevant. */
2690 if (!call || (np->header.callNumber != currentCallNumber)) {
2691 MUTEX_ENTER(&rx_stats_mutex);
2692 rx_stats.spuriousPacketsRead++;
2693 MUTEX_EXIT(&rx_stats_mutex);
2694 #ifdef RX_ENABLE_LOCKS
2696 MUTEX_EXIT(&call->lock);
2699 MUTEX_ENTER(&conn->conn_data_lock);
2701 MUTEX_EXIT(&conn->conn_data_lock);
2704 /* If the service security object index stamped in the packet does not
2705 * match the connection's security index, ignore the packet */
2706 if (np->header.securityIndex != conn->securityIndex) {
2707 #ifdef RX_ENABLE_LOCKS
2708 MUTEX_EXIT(&call->lock);
2710 MUTEX_ENTER(&conn->conn_data_lock);
2712 MUTEX_EXIT(&conn->conn_data_lock);
2716 /* If we're receiving the response, then all transmit packets are
2717 * implicitly acknowledged. Get rid of them. */
2718 if (np->header.type == RX_PACKET_TYPE_DATA) {
2719 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2720 /* XXX Hack. Because we must release the global rx lock when
2721 * sending packets (osi_NetSend) we drop all acks while we're
2722 * traversing the tq in rxi_Start sending packets out because
2723 * packets may move to the freePacketQueue as result of being here!
2724 * So we drop these packets until we're safely out of the
2725 * traversing. Really ugly!
2726 * For fine grain RX locking, we set the acked field in the
2727 * packets and let rxi_Start remove them from the transmit queue.
2729 if (call->flags & RX_CALL_TQ_BUSY) {
2730 #ifdef RX_ENABLE_LOCKS
2731 rxi_SetAcksInTransmitQueue(call);
2734 return np; /* xmitting; drop packet */
2737 rxi_ClearTransmitQueue(call, 0);
2739 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2740 rxi_ClearTransmitQueue(call, 0);
2741 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2743 if (np->header.type == RX_PACKET_TYPE_ACK) {
2744 /* now check to see if this is an ack packet acknowledging that the
2745 * server actually *lost* some hard-acked data. If this happens we
2746 * ignore this packet, as it may indicate that the server restarted in
2747 * the middle of a call. It is also possible that this is an old ack
2748 * packet. We don't abort the connection in this case, because this
2749 * *might* just be an old ack packet. The right way to detect a server
2750 * restart in the midst of a call is to notice that the server epoch
2752 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2753 * XXX unacknowledged. I think that this is off-by-one, but
2754 * XXX I don't dare change it just yet, since it will
2755 * XXX interact badly with the server-restart detection
2756 * XXX code in receiveackpacket. */
2757 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2758 MUTEX_ENTER(&rx_stats_mutex);
2759 rx_stats.spuriousPacketsRead++;
2760 MUTEX_EXIT(&rx_stats_mutex);
2761 MUTEX_EXIT(&call->lock);
2762 MUTEX_ENTER(&conn->conn_data_lock);
2764 MUTEX_EXIT(&conn->conn_data_lock);
2768 } /* else not a data packet */
2771 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2772 /* Set remote user defined status from packet */
2773 call->remoteStatus = np->header.userStatus;
2775 /* Note the gap between the expected next packet and the actual
2776 * packet that arrived, when the new packet has a smaller serial number
2777 * than expected. Rioses frequently reorder packets all by themselves,
2778 * so this will be quite important with very large window sizes.
2779 * Skew is checked against 0 here to avoid any dependence on the type of
2780 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2782 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2783 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2784 * I think using a beta of 1/8 is probably appropriate. 93.04.21
2786 MUTEX_ENTER(&conn->conn_data_lock);
2787 skew = conn->lastSerial - np->header.serial;
2788 conn->lastSerial = np->header.serial;
2789 MUTEX_EXIT(&conn->conn_data_lock);
2791 register struct rx_peer *peer;
2793 if (skew > peer->inPacketSkew) {
2794 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
2796 peer->inPacketSkew = skew;
2800 /* Now do packet type-specific processing */
2801 switch (np->header.type) {
2802 case RX_PACKET_TYPE_DATA:
2803 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
2806 case RX_PACKET_TYPE_ACK:
2807 /* Respond immediately to ack packets requesting acknowledgement
2809 if (np->header.flags & RX_REQUEST_ACK) {
2811 (void)rxi_SendCallAbort(call, 0, 1, 0);
2813 (void)rxi_SendAck(call, 0, np->header.serial,
2814 RX_ACK_PING_RESPONSE, 1);
2816 np = rxi_ReceiveAckPacket(call, np, 1);
2818 case RX_PACKET_TYPE_ABORT:
2819 /* An abort packet: reset the connection, passing the error up to
2821 /* What if error is zero? */
2822 rxi_CallError(call, ntohl(*(afs_int32 *) rx_DataOf(np)));
2824 case RX_PACKET_TYPE_BUSY:
2827 case RX_PACKET_TYPE_ACKALL:
2828 /* All packets acknowledged, so we can drop all packets previously
2829 * readied for sending */
2830 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2831 /* XXX Hack. We because we can't release the global rx lock when
2832 * sending packets (osi_NetSend) we drop all ack pkts while we're
2833 * traversing the tq in rxi_Start sending packets out because
2834 * packets may move to the freePacketQueue as result of being
2835 * here! So we drop these packets until we're safely out of the
2836 * traversing. Really ugly!
2837 * For fine grain RX locking, we set the acked field in the packets
2838 * and let rxi_Start remove the packets from the transmit queue.
2840 if (call->flags & RX_CALL_TQ_BUSY) {
2841 #ifdef RX_ENABLE_LOCKS
2842 rxi_SetAcksInTransmitQueue(call);
2844 #else /* RX_ENABLE_LOCKS */
2846 return np; /* xmitting; drop packet */
2847 #endif /* RX_ENABLE_LOCKS */
2849 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2850 rxi_ClearTransmitQueue(call, 0);
2853 /* Should not reach here, unless the peer is broken: send an abort
2855 rxi_CallError(call, RX_PROTOCOL_ERROR);
2856 np = rxi_SendCallAbort(call, np, 1, 0);
2859 /* Note when this last legitimate packet was received, for keep-alive
2860 * processing. Note, we delay getting the time until now in the hope that
2861 * the packet will be delivered to the user before any get time is required
2862 * (if not, then the time won't actually be re-evaluated here). */
2863 call->lastReceiveTime = clock_Sec();
2864 MUTEX_EXIT(&call->lock);
2865 MUTEX_ENTER(&conn->conn_data_lock);
2867 MUTEX_EXIT(&conn->conn_data_lock);
2871 /* return true if this is an "interesting" connection from the point of view
2872 of someone trying to debug the system */
2874 rxi_IsConnInteresting(struct rx_connection *aconn)
2877 register struct rx_call *tcall;
2879 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
2881 for (i = 0; i < RX_MAXCALLS; i++) {
2882 tcall = aconn->call[i];
2884 if ((tcall->state == RX_STATE_PRECALL)
2885 || (tcall->state == RX_STATE_ACTIVE))
2887 if ((tcall->mode == RX_MODE_SENDING)
2888 || (tcall->mode == RX_MODE_RECEIVING))
2896 /* if this is one of the last few packets AND it wouldn't be used by the
2897 receiving call to immediately satisfy a read request, then drop it on
2898 the floor, since accepting it might prevent a lock-holding thread from
2899 making progress in its reading. If a call has been cleared while in
2900 the precall state then ignore all subsequent packets until the call
2901 is assigned to a thread. */
2904 TooLow(struct rx_packet *ap, struct rx_call *acall)
2907 MUTEX_ENTER(&rx_stats_mutex);
2908 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
2909 && (acall->state == RX_STATE_PRECALL))
2910 || ((rx_nFreePackets < rxi_dataQuota + 2)
2911 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
2912 && (acall->flags & RX_CALL_READER_WAIT)))) {
2915 MUTEX_EXIT(&rx_stats_mutex);
2921 rxi_CheckReachEvent(struct rxevent *event, struct rx_connection *conn,
2922 struct rx_call *acall)
2924 struct rx_call *call = acall;
2928 MUTEX_ENTER(&conn->conn_data_lock);
2929 conn->checkReachEvent = NULL;
2930 waiting = conn->flags & RX_CONN_ATTACHWAIT;
2933 MUTEX_EXIT(&conn->conn_data_lock);
2937 MUTEX_ENTER(&conn->conn_call_lock);
2938 MUTEX_ENTER(&conn->conn_data_lock);
2939 for (i = 0; i < RX_MAXCALLS; i++) {
2940 struct rx_call *tc = conn->call[i];
2941 if (tc && tc->state == RX_STATE_PRECALL) {
2947 /* Indicate that rxi_CheckReachEvent is no longer running by
2948 * clearing the flag. Must be atomic under conn_data_lock to
2949 * avoid a new call slipping by: rxi_CheckConnReach holds
2950 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
2952 conn->flags &= ~RX_CONN_ATTACHWAIT;
2953 MUTEX_EXIT(&conn->conn_data_lock);
2954 MUTEX_EXIT(&conn->conn_call_lock);
2959 MUTEX_ENTER(&call->lock);
2960 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
2962 MUTEX_EXIT(&call->lock);
2964 clock_GetTime(&when);
2965 when.sec += RX_CHECKREACH_TIMEOUT;
2966 MUTEX_ENTER(&conn->conn_data_lock);
2967 if (!conn->checkReachEvent) {
2969 conn->checkReachEvent =
2970 rxevent_Post(&when, rxi_CheckReachEvent, conn, NULL);
2972 MUTEX_EXIT(&conn->conn_data_lock);
2978 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
2980 struct rx_service *service = conn->service;
2981 struct rx_peer *peer = conn->peer;
2982 afs_uint32 now, lastReach;
2984 if (service->checkReach == 0)
2988 MUTEX_ENTER(&peer->peer_lock);
2989 lastReach = peer->lastReachTime;
2990 MUTEX_EXIT(&peer->peer_lock);
2991 if (now - lastReach < RX_CHECKREACH_TTL)
2994 MUTEX_ENTER(&conn->conn_data_lock);
2995 if (conn->flags & RX_CONN_ATTACHWAIT) {
2996 MUTEX_EXIT(&conn->conn_data_lock);
2999 conn->flags |= RX_CONN_ATTACHWAIT;
3000 MUTEX_EXIT(&conn->conn_data_lock);
3001 if (!conn->checkReachEvent)
3002 rxi_CheckReachEvent(NULL, conn, call);
3007 /* try to attach call, if authentication is complete */
3009 TryAttach(register struct rx_call *acall, register osi_socket socket,
3010 register int *tnop, register struct rx_call **newcallp,
3013 struct rx_connection *conn = acall->conn;
3015 if (conn->type == RX_SERVER_CONNECTION
3016 && acall->state == RX_STATE_PRECALL) {
3017 /* Don't attach until we have any req'd. authentication. */
3018 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3019 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3020 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3021 /* Note: this does not necessarily succeed; there
3022 * may not any proc available
3025 rxi_ChallengeOn(acall->conn);
3030 /* A data packet has been received off the interface. This packet is
3031 * appropriate to the call (the call is in the right state, etc.). This
3032 * routine can return a packet to the caller, for re-use */
3035 rxi_ReceiveDataPacket(register struct rx_call *call,
3036 register struct rx_packet *np, int istack,
3037 osi_socket socket, afs_uint32 host, u_short port,
3038 int *tnop, struct rx_call **newcallp)
3040 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3044 afs_uint32 seq, serial, flags;
3046 struct rx_packet *tnp;
3048 MUTEX_ENTER(&rx_stats_mutex);
3049 rx_stats.dataPacketsRead++;
3050 MUTEX_EXIT(&rx_stats_mutex);
3053 /* If there are no packet buffers, drop this new packet, unless we can find
3054 * packet buffers from inactive calls */
3056 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3057 MUTEX_ENTER(&rx_freePktQ_lock);
3058 rxi_NeedMorePackets = TRUE;
3059 MUTEX_EXIT(&rx_freePktQ_lock);
3060 MUTEX_ENTER(&rx_stats_mutex);
3061 rx_stats.noPacketBuffersOnRead++;
3062 MUTEX_EXIT(&rx_stats_mutex);
3063 call->rprev = np->header.serial;
3064 rxi_calltrace(RX_TRACE_DROP, call);
3065 dpf(("packet %x dropped on receipt - quota problems", np));
3067 rxi_ClearReceiveQueue(call);
3068 clock_GetTime(&when);
3069 clock_Add(&when, &rx_softAckDelay);
3070 if (!call->delayedAckEvent
3071 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3072 rxevent_Cancel(call->delayedAckEvent, call,
3073 RX_CALL_REFCOUNT_DELAY);
3074 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3075 call->delayedAckEvent =
3076 rxevent_Post(&when, rxi_SendDelayedAck, call, 0);
3078 /* we've damaged this call already, might as well do it in. */
3084 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3085 * packet is one of several packets transmitted as a single
3086 * datagram. Do not send any soft or hard acks until all packets
3087 * in a jumbogram have been processed. Send negative acks right away.
3089 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3090 /* tnp is non-null when there are more packets in the
3091 * current jumbo gram */
3098 seq = np->header.seq;
3099 serial = np->header.serial;
3100 flags = np->header.flags;
3102 /* If the call is in an error state, send an abort message */
3104 return rxi_SendCallAbort(call, np, istack, 0);
3106 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3107 * AFS 3.5 jumbogram. */
3108 if (flags & RX_JUMBO_PACKET) {
3109 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3114 if (np->header.spare != 0) {
3115 MUTEX_ENTER(&call->conn->conn_data_lock);
3116 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3117 MUTEX_EXIT(&call->conn->conn_data_lock);
3120 /* The usual case is that this is the expected next packet */
3121 if (seq == call->rnext) {
3123 /* Check to make sure it is not a duplicate of one already queued */
3124 if (queue_IsNotEmpty(&call->rq)
3125 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3126 MUTEX_ENTER(&rx_stats_mutex);
3127 rx_stats.dupPacketsRead++;
3128 MUTEX_EXIT(&rx_stats_mutex);
3129 dpf(("packet %x dropped on receipt - duplicate", np));
3130 rxevent_Cancel(call->delayedAckEvent, call,
3131 RX_CALL_REFCOUNT_DELAY);
3132 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3138 /* It's the next packet. Stick it on the receive queue
3139 * for this call. Set newPackets to make sure we wake
3140 * the reader once all packets have been processed */
3141 queue_Prepend(&call->rq, np);
3143 np = NULL; /* We can't use this anymore */
3146 /* If an ack is requested then set a flag to make sure we
3147 * send an acknowledgement for this packet */
3148 if (flags & RX_REQUEST_ACK) {
3149 ackNeeded = RX_ACK_REQUESTED;
3152 /* Keep track of whether we have received the last packet */
3153 if (flags & RX_LAST_PACKET) {
3154 call->flags |= RX_CALL_HAVE_LAST;
3158 /* Check whether we have all of the packets for this call */
3159 if (call->flags & RX_CALL_HAVE_LAST) {
3160 afs_uint32 tseq; /* temporary sequence number */
3161 struct rx_packet *tp; /* Temporary packet pointer */
3162 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3164 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3165 if (tseq != tp->header.seq)
3167 if (tp->header.flags & RX_LAST_PACKET) {
3168 call->flags |= RX_CALL_RECEIVE_DONE;
3175 /* Provide asynchronous notification for those who want it
3176 * (e.g. multi rx) */
3177 if (call->arrivalProc) {
3178 (*call->arrivalProc) (call, call->arrivalProcHandle,
3179 call->arrivalProcArg);
3180 call->arrivalProc = (void (*)())0;
3183 /* Update last packet received */
3186 /* If there is no server process serving this call, grab
3187 * one, if available. We only need to do this once. If a
3188 * server thread is available, this thread becomes a server
3189 * thread and the server thread becomes a listener thread. */
3191 TryAttach(call, socket, tnop, newcallp, 0);
3194 /* This is not the expected next packet. */
3196 /* Determine whether this is a new or old packet, and if it's
3197 * a new one, whether it fits into the current receive window.
3198 * Also figure out whether the packet was delivered in sequence.
3199 * We use the prev variable to determine whether the new packet
3200 * is the successor of its immediate predecessor in the
3201 * receive queue, and the missing flag to determine whether
3202 * any of this packets predecessors are missing. */
3204 afs_uint32 prev; /* "Previous packet" sequence number */
3205 struct rx_packet *tp; /* Temporary packet pointer */
3206 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3207 int missing; /* Are any predecessors missing? */
3209 /* If the new packet's sequence number has been sent to the
3210 * application already, then this is a duplicate */
3211 if (seq < call->rnext) {
3212 MUTEX_ENTER(&rx_stats_mutex);
3213 rx_stats.dupPacketsRead++;
3214 MUTEX_EXIT(&rx_stats_mutex);
3215 rxevent_Cancel(call->delayedAckEvent, call,
3216 RX_CALL_REFCOUNT_DELAY);
3217 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3223 /* If the sequence number is greater than what can be
3224 * accomodated by the current window, then send a negative
3225 * acknowledge and drop the packet */
3226 if ((call->rnext + call->rwind) <= seq) {
3227 rxevent_Cancel(call->delayedAckEvent, call,
3228 RX_CALL_REFCOUNT_DELAY);
3229 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3236 /* Look for the packet in the queue of old received packets */
3237 for (prev = call->rnext - 1, missing =
3238 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3239 /*Check for duplicate packet */
3240 if (seq == tp->header.seq) {
3241 MUTEX_ENTER(&rx_stats_mutex);
3242 rx_stats.dupPacketsRead++;
3243 MUTEX_EXIT(&rx_stats_mutex);
3244 rxevent_Cancel(call->delayedAckEvent, call,
3245 RX_CALL_REFCOUNT_DELAY);
3246 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3252 /* If we find a higher sequence packet, break out and
3253 * insert the new packet here. */
3254 if (seq < tp->header.seq)
3256 /* Check for missing packet */
3257 if (tp->header.seq != prev + 1) {
3261 prev = tp->header.seq;
3264 /* Keep track of whether we have received the last packet. */
3265 if (flags & RX_LAST_PACKET) {
3266 call->flags |= RX_CALL_HAVE_LAST;
3269 /* It's within the window: add it to the the receive queue.
3270 * tp is left by the previous loop either pointing at the
3271 * packet before which to insert the new packet, or at the
3272 * queue head if the queue is empty or the packet should be
3274 queue_InsertBefore(tp, np);
3278 /* Check whether we have all of the packets for this call */
3279 if ((call->flags & RX_CALL_HAVE_LAST)
3280 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3281 afs_uint32 tseq; /* temporary sequence number */
3284 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3285 if (tseq != tp->header.seq)
3287 if (tp->header.flags & RX_LAST_PACKET) {
3288 call->flags |= RX_CALL_RECEIVE_DONE;
3295 /* We need to send an ack of the packet is out of sequence,
3296 * or if an ack was requested by the peer. */
3297 if (seq != prev + 1 || missing || (flags & RX_REQUEST_ACK)) {
3298 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3301 /* Acknowledge the last packet for each call */
3302 if (flags & RX_LAST_PACKET) {
3313 * If the receiver is waiting for an iovec, fill the iovec
3314 * using the data from the receive queue */
3315 if (call->flags & RX_CALL_IOVEC_WAIT) {
3316 didHardAck = rxi_FillReadVec(call, serial);
3317 /* the call may have been aborted */
3326 /* Wakeup the reader if any */
3327 if ((call->flags & RX_CALL_READER_WAIT)
3328 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3329 || (call->iovNext >= call->iovMax)
3330 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3331 call->flags &= ~RX_CALL_READER_WAIT;
3332 #ifdef RX_ENABLE_LOCKS
3333 CV_BROADCAST(&call->cv_rq);
3335 osi_rxWakeup(&call->rq);
3341 * Send an ack when requested by the peer, or once every
3342 * rxi_SoftAckRate packets until the last packet has been
3343 * received. Always send a soft ack for the last packet in
3344 * the server's reply. */
3346 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3347 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3348 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3349 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3350 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3351 } else if (call->nSoftAcks) {
3352 clock_GetTime(&when);
3353 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3354 clock_Add(&when, &rx_lastAckDelay);
3356 clock_Add(&when, &rx_softAckDelay);
3358 if (!call->delayedAckEvent
3359 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3360 rxevent_Cancel(call->delayedAckEvent, call,
3361 RX_CALL_REFCOUNT_DELAY);
3362 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3363 call->delayedAckEvent =
3364 rxevent_Post(&when, rxi_SendDelayedAck, call, 0);
3366 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3367 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3374 static void rxi_ComputeRate();
3378 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3380 struct rx_peer *peer = conn->peer;
3382 MUTEX_ENTER(&peer->peer_lock);
3383 peer->lastReachTime = clock_Sec();
3384 MUTEX_EXIT(&peer->peer_lock);
3386 MUTEX_ENTER(&conn->conn_data_lock);
3387 if (conn->flags & RX_CONN_ATTACHWAIT) {
3390 conn->flags &= ~RX_CONN_ATTACHWAIT;
3391 MUTEX_EXIT(&conn->conn_data_lock);
3393 for (i = 0; i < RX_MAXCALLS; i++) {
3394 struct rx_call *call = conn->call[i];
3397 MUTEX_ENTER(&call->lock);
3398 /* tnop can be null if newcallp is null */
3399 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3401 MUTEX_EXIT(&call->lock);
3405 MUTEX_EXIT(&conn->conn_data_lock);
3408 /* rxi_ComputePeerNetStats
3410 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3411 * estimates (like RTT and throughput) based on ack packets. Caller
3412 * must ensure that the packet in question is the right one (i.e.
3413 * serial number matches).
3416 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3417 struct rx_ackPacket *ap, struct rx_packet *np)
3419 struct rx_peer *peer = call->conn->peer;
3421 /* Use RTT if not delayed by client. */
3422 if (ap->reason != RX_ACK_DELAY)
3423 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3425 rxi_ComputeRate(peer, call, p, np, ap->reason);
3429 /* The real smarts of the whole thing. */
3431 rxi_ReceiveAckPacket(register struct rx_call *call, struct rx_packet *np,
3434 struct rx_ackPacket *ap;
3436 register struct rx_packet *tp;
3437 register struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3438 register struct rx_connection *conn = call->conn;
3439 struct rx_peer *peer = conn->peer;
3442 /* because there are CM's that are bogus, sending weird values for this. */
3443 afs_uint32 skew = 0;
3448 int newAckCount = 0;
3449 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3450 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3452 MUTEX_ENTER(&rx_stats_mutex);
3453 rx_stats.ackPacketsRead++;
3454 MUTEX_EXIT(&rx_stats_mutex);
3455 ap = (struct rx_ackPacket *)rx_DataOf(np);
3456 nbytes = rx_Contiguous(np) - ((ap->acks) - (u_char *) ap);
3458 return np; /* truncated ack packet */
3460 /* depends on ack packet struct */
3461 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3462 first = ntohl(ap->firstPacket);
3463 serial = ntohl(ap->serial);
3464 /* temporarily disabled -- needs to degrade over time
3465 * skew = ntohs(ap->maxSkew); */
3467 /* Ignore ack packets received out of order */
3468 if (first < call->tfirst) {
3472 if (np->header.flags & RX_SLOW_START_OK) {
3473 call->flags |= RX_CALL_SLOW_START_OK;
3476 if (ap->reason == RX_ACK_PING_RESPONSE)
3477 rxi_UpdatePeerReach(conn, call);
3482 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3483 ap->reason, ntohl(ap->previousPacket),
3484 (unsigned int)np->header.seq, (unsigned int)serial,
3485 (unsigned int)skew, ntohl(ap->firstPacket));
3488 for (offset = 0; offset < nAcks; offset++)
3489 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3496 /* Update the outgoing packet skew value to the latest value of
3497 * the peer's incoming packet skew value. The ack packet, of
3498 * course, could arrive out of order, but that won't affect things
3500 MUTEX_ENTER(&peer->peer_lock);
3501 peer->outPacketSkew = skew;
3503 /* Check for packets that no longer need to be transmitted, and
3504 * discard them. This only applies to packets positively
3505 * acknowledged as having been sent to the peer's upper level.
3506 * All other packets must be retained. So only packets with
3507 * sequence numbers < ap->firstPacket are candidates. */
3508 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3509 if (tp->header.seq >= first)
3511 call->tfirst = tp->header.seq + 1;
3513 && (tp->header.serial == serial || tp->firstSerial == serial))
3514 rxi_ComputePeerNetStats(call, tp, ap, np);
3515 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3516 /* XXX Hack. Because we have to release the global rx lock when sending
3517 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3518 * in rxi_Start sending packets out because packets may move to the
3519 * freePacketQueue as result of being here! So we drop these packets until
3520 * we're safely out of the traversing. Really ugly!
3521 * To make it even uglier, if we're using fine grain locking, we can
3522 * set the ack bits in the packets and have rxi_Start remove the packets
3523 * when it's done transmitting.
3525 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3528 if (call->flags & RX_CALL_TQ_BUSY) {
3529 #ifdef RX_ENABLE_LOCKS
3530 tp->flags |= RX_PKTFLAG_ACKED;
3531 call->flags |= RX_CALL_TQ_SOME_ACKED;
3532 #else /* RX_ENABLE_LOCKS */
3534 #endif /* RX_ENABLE_LOCKS */
3536 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3539 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3544 /* Give rate detector a chance to respond to ping requests */
3545 if (ap->reason == RX_ACK_PING_RESPONSE) {
3546 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3550 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3552 /* Now go through explicit acks/nacks and record the results in
3553 * the waiting packets. These are packets that can't be released
3554 * yet, even with a positive acknowledge. This positive
3555 * acknowledge only means the packet has been received by the
3556 * peer, not that it will be retained long enough to be sent to
3557 * the peer's upper level. In addition, reset the transmit timers
3558 * of any missing packets (those packets that must be missing
3559 * because this packet was out of sequence) */
3561 call->nSoftAcked = 0;
3562 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3563 /* Update round trip time if the ack was stimulated on receipt
3565 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3566 #ifdef RX_ENABLE_LOCKS
3567 if (tp->header.seq >= first)
3568 #endif /* RX_ENABLE_LOCKS */
3569 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3571 && (tp->header.serial == serial || tp->firstSerial == serial))
3572 rxi_ComputePeerNetStats(call, tp, ap, np);
3574 /* Set the acknowledge flag per packet based on the
3575 * information in the ack packet. An acknowlegded packet can
3576 * be downgraded when the server has discarded a packet it
3577 * soacked previously, or when an ack packet is received
3578 * out of sequence. */
3579 if (tp->header.seq < first) {
3580 /* Implicit ack information */
3581 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3584 tp->flags |= RX_PKTFLAG_ACKED;
3585 } else if (tp->header.seq < first + nAcks) {
3586 /* Explicit ack information: set it in the packet appropriately */
3587 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3588 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3590 tp->flags |= RX_PKTFLAG_ACKED;
3598 tp->flags &= ~RX_PKTFLAG_ACKED;
3602 tp->flags &= ~RX_PKTFLAG_ACKED;
3606 /* If packet isn't yet acked, and it has been transmitted at least
3607 * once, reset retransmit time using latest timeout
3608 * ie, this should readjust the retransmit timer for all outstanding
3609 * packets... So we don't just retransmit when we should know better*/
3611 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3612 tp->retryTime = tp->timeSent;
3613 clock_Add(&tp->retryTime, &peer->timeout);
3614 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3615 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3619 /* If the window has been extended by this acknowledge packet,
3620 * then wakeup a sender waiting in alloc for window space, or try
3621 * sending packets now, if he's been sitting on packets due to
3622 * lack of window space */
3623 if (call->tnext < (call->tfirst + call->twind)) {
3624 #ifdef RX_ENABLE_LOCKS
3625 CV_SIGNAL(&call->cv_twind);
3627 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3628 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3629 osi_rxWakeup(&call->twind);
3632 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3633 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3637 /* if the ack packet has a receivelen field hanging off it,
3638 * update our state */
3639 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3642 /* If the ack packet has a "recommended" size that is less than
3643 * what I am using now, reduce my size to match */
3644 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3645 sizeof(afs_int32), &tSize);
3646 tSize = (afs_uint32) ntohl(tSize);
3647 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3649 /* Get the maximum packet size to send to this peer */
3650 rx_packetread(np, rx_AckDataSize(ap->nAcks), sizeof(afs_int32),
3652 tSize = (afs_uint32) ntohl(tSize);
3653 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3654 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3656 /* sanity check - peer might have restarted with different params.
3657 * If peer says "send less", dammit, send less... Peer should never
3658 * be unable to accept packets of the size that prior AFS versions would
3659 * send without asking. */
3660 if (peer->maxMTU != tSize) {
3661 peer->maxMTU = tSize;
3662 peer->MTU = MIN(tSize, peer->MTU);
3663 call->MTU = MIN(call->MTU, tSize);
3667 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3670 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3671 sizeof(afs_int32), &tSize);
3672 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3673 if (tSize < call->twind) { /* smaller than our send */
3674 call->twind = tSize; /* window, we must send less... */
3675 call->ssthresh = MIN(call->twind, call->ssthresh);
3678 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3679 * network MTU confused with the loopback MTU. Calculate the
3680 * maximum MTU here for use in the slow start code below.
3682 maxMTU = peer->maxMTU;
3683 /* Did peer restart with older RX version? */
3684 if (peer->maxDgramPackets > 1) {
3685 peer->maxDgramPackets = 1;
3687 } else if (np->length >=
3688 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3691 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3692 sizeof(afs_int32), &tSize);
3693 tSize = (afs_uint32) ntohl(tSize);
3695 * As of AFS 3.5 we set the send window to match the receive window.
3697 if (tSize < call->twind) {
3698 call->twind = tSize;
3699 call->ssthresh = MIN(call->twind, call->ssthresh);
3700 } else if (tSize > call->twind) {
3701 call->twind = tSize;
3705 * As of AFS 3.5, a jumbogram is more than one fixed size
3706 * packet transmitted in a single UDP datagram. If the remote
3707 * MTU is smaller than our local MTU then never send a datagram
3708 * larger than the natural MTU.
3711 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
3712 sizeof(afs_int32), &tSize);
3713 maxDgramPackets = (afs_uint32) ntohl(tSize);
3714 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
3716 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
3717 maxDgramPackets = MIN(maxDgramPackets, tSize);
3718 if (maxDgramPackets > 1) {
3719 peer->maxDgramPackets = maxDgramPackets;
3720 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
3722 peer->maxDgramPackets = 1;
3723 call->MTU = peer->natMTU;
3725 } else if (peer->maxDgramPackets > 1) {
3726 /* Restarted with lower version of RX */
3727 peer->maxDgramPackets = 1;
3729 } else if (peer->maxDgramPackets > 1
3730 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
3731 /* Restarted with lower version of RX */
3732 peer->maxMTU = OLD_MAX_PACKET_SIZE;
3733 peer->natMTU = OLD_MAX_PACKET_SIZE;
3734 peer->MTU = OLD_MAX_PACKET_SIZE;
3735 peer->maxDgramPackets = 1;
3736 peer->nDgramPackets = 1;
3738 call->MTU = OLD_MAX_PACKET_SIZE;
3743 * Calculate how many datagrams were successfully received after
3744 * the first missing packet and adjust the negative ack counter
3749 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
3750 if (call->nNacks < nNacked) {
3751 call->nNacks = nNacked;
3760 if (call->flags & RX_CALL_FAST_RECOVER) {
3762 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
3764 call->flags &= ~RX_CALL_FAST_RECOVER;
3765 call->cwind = call->nextCwind;
3766 call->nextCwind = 0;
3769 call->nCwindAcks = 0;
3770 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
3771 /* Three negative acks in a row trigger congestion recovery */
3772 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3773 MUTEX_EXIT(&peer->peer_lock);
3774 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
3775 /* someone else is waiting to start recovery */
3778 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
3779 while (call->flags & RX_CALL_TQ_BUSY) {
3780 call->flags |= RX_CALL_TQ_WAIT;
3781 #ifdef RX_ENABLE_LOCKS
3782 CV_WAIT(&call->cv_tq, &call->lock);
3783 #else /* RX_ENABLE_LOCKS */
3784 osi_rxSleep(&call->tq);
3785 #endif /* RX_ENABLE_LOCKS */
3787 MUTEX_ENTER(&peer->peer_lock);
3788 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3789 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
3790 call->flags |= RX_CALL_FAST_RECOVER;
3791 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
3793 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
3794 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
3795 call->nextCwind = call->ssthresh;
3798 peer->MTU = call->MTU;
3799 peer->cwind = call->nextCwind;
3800 peer->nDgramPackets = call->nDgramPackets;
3802 call->congestSeq = peer->congestSeq;
3803 /* Reset the resend times on the packets that were nacked
3804 * so we will retransmit as soon as the window permits*/
3805 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
3807 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3808 clock_Zero(&tp->retryTime);
3810 } else if (tp->flags & RX_PKTFLAG_ACKED) {
3815 /* If cwind is smaller than ssthresh, then increase
3816 * the window one packet for each ack we receive (exponential
3818 * If cwind is greater than or equal to ssthresh then increase
3819 * the congestion window by one packet for each cwind acks we
3820 * receive (linear growth). */
3821 if (call->cwind < call->ssthresh) {
3823 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
3824 call->nCwindAcks = 0;
3826 call->nCwindAcks += newAckCount;
3827 if (call->nCwindAcks >= call->cwind) {
3828 call->nCwindAcks = 0;
3829 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
3833 * If we have received several acknowledgements in a row then
3834 * it is time to increase the size of our datagrams
3836 if ((int)call->nAcks > rx_nDgramThreshold) {
3837 if (peer->maxDgramPackets > 1) {
3838 if (call->nDgramPackets < peer->maxDgramPackets) {
3839 call->nDgramPackets++;
3841 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
3842 } else if (call->MTU < peer->maxMTU) {
3843 call->MTU += peer->natMTU;
3844 call->MTU = MIN(call->MTU, peer->maxMTU);
3850 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
3852 /* Servers need to hold the call until all response packets have
3853 * been acknowledged. Soft acks are good enough since clients
3854 * are not allowed to clear their receive queues. */
3855 if (call->state == RX_STATE_HOLD
3856 && call->tfirst + call->nSoftAcked >= call->tnext) {
3857 call->state = RX_STATE_DALLY;
3858 rxi_ClearTransmitQueue(call, 0);
3859 } else if (!queue_IsEmpty(&call->tq)) {
3860 rxi_Start(0, call, 0, istack);
3865 /* Received a response to a challenge packet */
3867 rxi_ReceiveResponsePacket(register struct rx_connection *conn,
3868 register struct rx_packet *np, int istack)
3872 /* Ignore the packet if we're the client */
3873 if (conn->type == RX_CLIENT_CONNECTION)
3876 /* If already authenticated, ignore the packet (it's probably a retry) */
3877 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
3880 /* Otherwise, have the security object evaluate the response packet */
3881 error = RXS_CheckResponse(conn->securityObject, conn, np);
3883 /* If the response is invalid, reset the connection, sending
3884 * an abort to the peer */
3888 rxi_ConnectionError(conn, error);
3889 MUTEX_ENTER(&conn->conn_data_lock);
3890 np = rxi_SendConnectionAbort(conn, np, istack, 0);
3891 MUTEX_EXIT(&conn->conn_data_lock);
3894 /* If the response is valid, any calls waiting to attach
3895 * servers can now do so */
3898 for (i = 0; i < RX_MAXCALLS; i++) {
3899 struct rx_call *call = conn->call[i];
3901 MUTEX_ENTER(&call->lock);
3902 if (call->state == RX_STATE_PRECALL)
3903 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
3904 /* tnop can be null if newcallp is null */
3905 MUTEX_EXIT(&call->lock);
3909 /* Update the peer reachability information, just in case
3910 * some calls went into attach-wait while we were waiting
3911 * for authentication..
3913 rxi_UpdatePeerReach(conn, NULL);
3918 /* A client has received an authentication challenge: the security
3919 * object is asked to cough up a respectable response packet to send
3920 * back to the server. The server is responsible for retrying the
3921 * challenge if it fails to get a response. */
3924 rxi_ReceiveChallengePacket(register struct rx_connection *conn,
3925 register struct rx_packet *np, int istack)
3929 /* Ignore the challenge if we're the server */
3930 if (conn->type == RX_SERVER_CONNECTION)
3933 /* Ignore the challenge if the connection is otherwise idle; someone's
3934 * trying to use us as an oracle. */
3935 if (!rxi_HasActiveCalls(conn))
3938 /* Send the security object the challenge packet. It is expected to fill
3939 * in the response. */
3940 error = RXS_GetResponse(conn->securityObject, conn, np);
3942 /* If the security object is unable to return a valid response, reset the
3943 * connection and send an abort to the peer. Otherwise send the response
3944 * packet to the peer connection. */
3946 rxi_ConnectionError(conn, error);
3947 MUTEX_ENTER(&conn->conn_data_lock);
3948 np = rxi_SendConnectionAbort(conn, np, istack, 0);
3949 MUTEX_EXIT(&conn->conn_data_lock);
3951 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
3952 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
3958 /* Find an available server process to service the current request in
3959 * the given call structure. If one isn't available, queue up this
3960 * call so it eventually gets one */
3962 rxi_AttachServerProc(register struct rx_call *call,
3963 register osi_socket socket, register int *tnop,
3964 register struct rx_call **newcallp)
3966 register struct rx_serverQueueEntry *sq;
3967 register struct rx_service *service = call->conn->service;
3968 register int haveQuota = 0;
3970 /* May already be attached */
3971 if (call->state == RX_STATE_ACTIVE)
3974 MUTEX_ENTER(&rx_serverPool_lock);
3976 haveQuota = QuotaOK(service);
3977 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
3978 /* If there are no processes available to service this call,
3979 * put the call on the incoming call queue (unless it's
3980 * already on the queue).
3982 #ifdef RX_ENABLE_LOCKS
3984 ReturnToServerPool(service);
3985 #endif /* RX_ENABLE_LOCKS */
3987 if (!(call->flags & RX_CALL_WAIT_PROC)) {
3988 call->flags |= RX_CALL_WAIT_PROC;
3989 MUTEX_ENTER(&rx_stats_mutex);
3992 MUTEX_EXIT(&rx_stats_mutex);
3993 rxi_calltrace(RX_CALL_ARRIVAL, call);
3994 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
3995 queue_Append(&rx_incomingCallQueue, call);
3998 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4000 /* If hot threads are enabled, and both newcallp and sq->socketp
4001 * are non-null, then this thread will process the call, and the
4002 * idle server thread will start listening on this threads socket.
4005 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4008 *sq->socketp = socket;
4009 clock_GetTime(&call->startTime);
4010 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4014 if (call->flags & RX_CALL_WAIT_PROC) {
4015 /* Conservative: I don't think this should happen */
4016 call->flags &= ~RX_CALL_WAIT_PROC;
4017 if (queue_IsOnQueue(call)) {
4019 MUTEX_ENTER(&rx_stats_mutex);
4021 MUTEX_EXIT(&rx_stats_mutex);
4024 call->state = RX_STATE_ACTIVE;
4025 call->mode = RX_MODE_RECEIVING;
4026 #ifdef RX_KERNEL_TRACE
4028 int glockOwner = ISAFS_GLOCK();
4031 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4032 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4038 if (call->flags & RX_CALL_CLEARED) {
4039 /* send an ack now to start the packet flow up again */
4040 call->flags &= ~RX_CALL_CLEARED;
4041 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4043 #ifdef RX_ENABLE_LOCKS
4046 service->nRequestsRunning++;
4047 if (service->nRequestsRunning <= service->minProcs)
4053 MUTEX_EXIT(&rx_serverPool_lock);
4056 /* Delay the sending of an acknowledge event for a short while, while
4057 * a new call is being prepared (in the case of a client) or a reply
4058 * is being prepared (in the case of a server). Rather than sending
4059 * an ack packet, an ACKALL packet is sent. */
4061 rxi_AckAll(struct rxevent *event, register struct rx_call *call, char *dummy)
4063 #ifdef RX_ENABLE_LOCKS
4065 MUTEX_ENTER(&call->lock);
4066 call->delayedAckEvent = NULL;
4067 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4069 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4070 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4072 MUTEX_EXIT(&call->lock);
4073 #else /* RX_ENABLE_LOCKS */
4075 call->delayedAckEvent = NULL;
4076 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4077 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4078 #endif /* RX_ENABLE_LOCKS */
4082 rxi_SendDelayedAck(struct rxevent *event, register struct rx_call *call,
4085 #ifdef RX_ENABLE_LOCKS
4087 MUTEX_ENTER(&call->lock);
4088 if (event == call->delayedAckEvent)
4089 call->delayedAckEvent = NULL;
4090 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4092 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4094 MUTEX_EXIT(&call->lock);
4095 #else /* RX_ENABLE_LOCKS */
4097 call->delayedAckEvent = NULL;
4098 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4099 #endif /* RX_ENABLE_LOCKS */
4103 #ifdef RX_ENABLE_LOCKS
4104 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4105 * clearing them out.
4108 rxi_SetAcksInTransmitQueue(register struct rx_call *call)
4110 register struct rx_packet *p, *tp;
4113 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4116 p->flags |= RX_PKTFLAG_ACKED;
4120 call->flags |= RX_CALL_TQ_CLEARME;
4121 call->flags |= RX_CALL_TQ_SOME_ACKED;
4124 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4125 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4126 call->tfirst = call->tnext;
4127 call->nSoftAcked = 0;
4129 if (call->flags & RX_CALL_FAST_RECOVER) {
4130 call->flags &= ~RX_CALL_FAST_RECOVER;
4131 call->cwind = call->nextCwind;
4132 call->nextCwind = 0;
4135 CV_SIGNAL(&call->cv_twind);
4137 #endif /* RX_ENABLE_LOCKS */
4139 /* Clear out the transmit queue for the current call (all packets have
4140 * been received by peer) */
4142 rxi_ClearTransmitQueue(register struct rx_call *call, register int force)
4144 register struct rx_packet *p, *tp;
4146 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4147 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4149 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4152 p->flags |= RX_PKTFLAG_ACKED;
4156 call->flags |= RX_CALL_TQ_CLEARME;
4157 call->flags |= RX_CALL_TQ_SOME_ACKED;
4160 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4161 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4167 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4168 call->flags &= ~RX_CALL_TQ_CLEARME;
4170 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4172 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4173 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4174 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4175 call->nSoftAcked = 0;
4177 if (call->flags & RX_CALL_FAST_RECOVER) {
4178 call->flags &= ~RX_CALL_FAST_RECOVER;
4179 call->cwind = call->nextCwind;
4181 #ifdef RX_ENABLE_LOCKS
4182 CV_SIGNAL(&call->cv_twind);
4184 osi_rxWakeup(&call->twind);
4189 rxi_ClearReceiveQueue(register struct rx_call *call)
4191 register struct rx_packet *p, *tp;
4192 if (queue_IsNotEmpty(&call->rq)) {
4193 for (queue_Scan(&call->rq, p, tp, rx_packet)) {
4198 rx_packetReclaims++;
4200 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4202 if (call->state == RX_STATE_PRECALL) {
4203 call->flags |= RX_CALL_CLEARED;
4207 /* Send an abort packet for the specified call */
4209 rxi_SendCallAbort(register struct rx_call *call, struct rx_packet *packet,
4210 int istack, int force)
4218 /* Clients should never delay abort messages */
4219 if (rx_IsClientConn(call->conn))
4222 if (call->abortCode != call->error) {
4223 call->abortCode = call->error;
4224 call->abortCount = 0;
4227 if (force || rxi_callAbortThreshhold == 0
4228 || call->abortCount < rxi_callAbortThreshhold) {
4229 if (call->delayedAbortEvent) {
4230 rxevent_Cancel(call->delayedAbortEvent, call,
4231 RX_CALL_REFCOUNT_ABORT);
4233 error = htonl(call->error);
4236 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4237 (char *)&error, sizeof(error), istack);
4238 } else if (!call->delayedAbortEvent) {
4239 clock_GetTime(&when);
4240 clock_Addmsec(&when, rxi_callAbortDelay);
4241 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4242 call->delayedAbortEvent =
4243 rxevent_Post(&when, rxi_SendDelayedCallAbort, call, 0);
4248 /* Send an abort packet for the specified connection. Packet is an
4249 * optional pointer to a packet that can be used to send the abort.
4250 * Once the number of abort messages reaches the threshhold, an
4251 * event is scheduled to send the abort. Setting the force flag
4252 * overrides sending delayed abort messages.
4254 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4255 * to send the abort packet.
4258 rxi_SendConnectionAbort(register struct rx_connection *conn,
4259 struct rx_packet *packet, int istack, int force)
4267 /* Clients should never delay abort messages */
4268 if (rx_IsClientConn(conn))
4271 if (force || rxi_connAbortThreshhold == 0
4272 || conn->abortCount < rxi_connAbortThreshhold) {
4273 if (conn->delayedAbortEvent) {
4274 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4276 error = htonl(conn->error);
4278 MUTEX_EXIT(&conn->conn_data_lock);
4280 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4281 RX_PACKET_TYPE_ABORT, (char *)&error,
4282 sizeof(error), istack);
4283 MUTEX_ENTER(&conn->conn_data_lock);
4284 } else if (!conn->delayedAbortEvent) {
4285 clock_GetTime(&when);
4286 clock_Addmsec(&when, rxi_connAbortDelay);
4287 conn->delayedAbortEvent =
4288 rxevent_Post(&when, rxi_SendDelayedConnAbort, conn, 0);
4293 /* Associate an error all of the calls owned by a connection. Called
4294 * with error non-zero. This is only for really fatal things, like
4295 * bad authentication responses. The connection itself is set in
4296 * error at this point, so that future packets received will be
4299 rxi_ConnectionError(register struct rx_connection *conn,
4300 register afs_int32 error)
4304 MUTEX_ENTER(&conn->conn_data_lock);
4305 if (conn->challengeEvent)
4306 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4307 if (conn->checkReachEvent) {
4308 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4309 conn->checkReachEvent = 0;
4310 conn->flags &= ~RX_CONN_ATTACHWAIT;
4313 MUTEX_EXIT(&conn->conn_data_lock);
4314 for (i = 0; i < RX_MAXCALLS; i++) {
4315 struct rx_call *call = conn->call[i];
4317 MUTEX_ENTER(&call->lock);
4318 rxi_CallError(call, error);
4319 MUTEX_EXIT(&call->lock);
4322 conn->error = error;
4323 MUTEX_ENTER(&rx_stats_mutex);
4324 rx_stats.fatalErrors++;
4325 MUTEX_EXIT(&rx_stats_mutex);
4330 rxi_CallError(register struct rx_call *call, afs_int32 error)
4333 error = call->error;
4334 #ifdef RX_GLOBAL_RXLOCK_KERNEL
4335 if (!(call->flags & RX_CALL_TQ_BUSY)) {
4336 rxi_ResetCall(call, 0);
4339 rxi_ResetCall(call, 0);
4341 call->error = error;
4342 call->mode = RX_MODE_ERROR;
4345 /* Reset various fields in a call structure, and wakeup waiting
4346 * processes. Some fields aren't changed: state & mode are not
4347 * touched (these must be set by the caller), and bufptr, nLeft, and
4348 * nFree are not reset, since these fields are manipulated by
4349 * unprotected macros, and may only be reset by non-interrupting code.
4352 /* this code requires that call->conn be set properly as a pre-condition. */
4353 #endif /* ADAPT_WINDOW */
4356 rxi_ResetCall(register struct rx_call *call, register int newcall)
4359 register struct rx_peer *peer;
4360 struct rx_packet *packet;
4362 /* Notify anyone who is waiting for asynchronous packet arrival */
4363 if (call->arrivalProc) {
4364 (*call->arrivalProc) (call, call->arrivalProcHandle,
4365 call->arrivalProcArg);
4366 call->arrivalProc = (void (*)())0;
4369 if (call->delayedAbortEvent) {
4370 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4371 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4373 rxi_SendCallAbort(call, packet, 0, 1);
4374 rxi_FreePacket(packet);
4379 * Update the peer with the congestion information in this call
4380 * so other calls on this connection can pick up where this call
4381 * left off. If the congestion sequence numbers don't match then
4382 * another call experienced a retransmission.
4384 peer = call->conn->peer;
4385 MUTEX_ENTER(&peer->peer_lock);
4387 if (call->congestSeq == peer->congestSeq) {
4388 peer->cwind = MAX(peer->cwind, call->cwind);
4389 peer->MTU = MAX(peer->MTU, call->MTU);
4390 peer->nDgramPackets =
4391 MAX(peer->nDgramPackets, call->nDgramPackets);
4394 call->abortCode = 0;
4395 call->abortCount = 0;
4397 if (peer->maxDgramPackets > 1) {
4398 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4400 call->MTU = peer->MTU;
4402 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4403 call->ssthresh = rx_maxSendWindow;
4404 call->nDgramPackets = peer->nDgramPackets;
4405 call->congestSeq = peer->congestSeq;
4406 MUTEX_EXIT(&peer->peer_lock);
4408 flags = call->flags;
4409 rxi_ClearReceiveQueue(call);
4410 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4411 if (call->flags & RX_CALL_TQ_BUSY) {
4412 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4413 call->flags |= (flags & RX_CALL_TQ_WAIT);
4415 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4417 rxi_ClearTransmitQueue(call, 0);
4418 queue_Init(&call->tq);
4421 queue_Init(&call->rq);
4423 call->rwind = rx_initReceiveWindow;
4424 call->twind = rx_initSendWindow;
4425 call->nSoftAcked = 0;
4426 call->nextCwind = 0;
4429 call->nCwindAcks = 0;
4430 call->nSoftAcks = 0;
4431 call->nHardAcks = 0;
4433 call->tfirst = call->rnext = call->tnext = 1;
4435 call->lastAcked = 0;
4436 call->localStatus = call->remoteStatus = 0;
4438 if (flags & RX_CALL_READER_WAIT) {
4439 #ifdef RX_ENABLE_LOCKS
4440 CV_BROADCAST(&call->cv_rq);
4442 osi_rxWakeup(&call->rq);
4445 if (flags & RX_CALL_WAIT_PACKETS) {
4446 MUTEX_ENTER(&rx_freePktQ_lock);
4447 rxi_PacketsUnWait(); /* XXX */
4448 MUTEX_EXIT(&rx_freePktQ_lock);
4450 #ifdef RX_ENABLE_LOCKS
4451 CV_SIGNAL(&call->cv_twind);
4453 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4454 osi_rxWakeup(&call->twind);
4457 #ifdef RX_ENABLE_LOCKS
4458 /* The following ensures that we don't mess with any queue while some
4459 * other thread might also be doing so. The call_queue_lock field is
4460 * is only modified under the call lock. If the call is in the process
4461 * of being removed from a queue, the call is not locked until the
4462 * the queue lock is dropped and only then is the call_queue_lock field
4463 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4464 * Note that any other routine which removes a call from a queue has to
4465 * obtain the queue lock before examing the queue and removing the call.
4467 if (call->call_queue_lock) {
4468 MUTEX_ENTER(call->call_queue_lock);
4469 if (queue_IsOnQueue(call)) {
4471 if (flags & RX_CALL_WAIT_PROC) {
4472 MUTEX_ENTER(&rx_stats_mutex);
4474 MUTEX_EXIT(&rx_stats_mutex);
4477 MUTEX_EXIT(call->call_queue_lock);
4478 CLEAR_CALL_QUEUE_LOCK(call);
4480 #else /* RX_ENABLE_LOCKS */
4481 if (queue_IsOnQueue(call)) {
4483 if (flags & RX_CALL_WAIT_PROC)
4486 #endif /* RX_ENABLE_LOCKS */
4488 rxi_KeepAliveOff(call);
4489 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4492 /* Send an acknowledge for the indicated packet (seq,serial) of the
4493 * indicated call, for the indicated reason (reason). This
4494 * acknowledge will specifically acknowledge receiving the packet, and
4495 * will also specify which other packets for this call have been
4496 * received. This routine returns the packet that was used to the
4497 * caller. The caller is responsible for freeing it or re-using it.
4498 * This acknowledgement also returns the highest sequence number
4499 * actually read out by the higher level to the sender; the sender
4500 * promises to keep around packets that have not been read by the
4501 * higher level yet (unless, of course, the sender decides to abort
4502 * the call altogether). Any of p, seq, serial, pflags, or reason may
4503 * be set to zero without ill effect. That is, if they are zero, they
4504 * will not convey any information.
4505 * NOW there is a trailer field, after the ack where it will safely be
4506 * ignored by mundanes, which indicates the maximum size packet this
4507 * host can swallow. */
4509 register struct rx_packet *optionalPacket; use to send ack (or null)
4510 int seq; Sequence number of the packet we are acking
4511 int serial; Serial number of the packet
4512 int pflags; Flags field from packet header
4513 int reason; Reason an acknowledge was prompted
4517 rxi_SendAck(register struct rx_call *call,
4518 register struct rx_packet *optionalPacket, int serial, int reason,
4521 struct rx_ackPacket *ap;
4522 register struct rx_packet *rqp;
4523 register struct rx_packet *nxp; /* For queue_Scan */
4524 register struct rx_packet *p;
4529 * Open the receive window once a thread starts reading packets
4531 if (call->rnext > 1) {
4532 call->rwind = rx_maxReceiveWindow;
4535 call->nHardAcks = 0;
4536 call->nSoftAcks = 0;
4537 if (call->rnext > call->lastAcked)
4538 call->lastAcked = call->rnext;
4542 rx_computelen(p, p->length); /* reset length, you never know */
4543 } /* where that's been... */
4544 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4545 /* We won't send the ack, but don't panic. */
4546 return optionalPacket;
4550 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4553 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL)) {
4554 if (!optionalPacket)
4556 return optionalPacket;
4558 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4559 if (rx_Contiguous(p) < templ) {
4560 if (!optionalPacket)
4562 return optionalPacket;
4567 /* MTUXXX failing to send an ack is very serious. We should */
4568 /* try as hard as possible to send even a partial ack; it's */
4569 /* better than nothing. */
4570 ap = (struct rx_ackPacket *)rx_DataOf(p);
4571 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4572 ap->reason = reason;
4574 /* The skew computation used to be bogus, I think it's better now. */
4575 /* We should start paying attention to skew. XXX */
4576 ap->serial = htonl(serial);
4577 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4579 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4580 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4582 /* No fear of running out of ack packet here because there can only be at most
4583 * one window full of unacknowledged packets. The window size must be constrained
4584 * to be less than the maximum ack size, of course. Also, an ack should always
4585 * fit into a single packet -- it should not ever be fragmented. */
4586 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4587 if (!rqp || !call->rq.next
4588 || (rqp->header.seq > (call->rnext + call->rwind))) {
4589 if (!optionalPacket)
4591 rxi_CallError(call, RX_CALL_DEAD);
4592 return optionalPacket;
4595 while (rqp->header.seq > call->rnext + offset)
4596 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4597 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4599 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4600 if (!optionalPacket)
4602 rxi_CallError(call, RX_CALL_DEAD);
4603 return optionalPacket;
4608 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4610 /* these are new for AFS 3.3 */
4611 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4612 templ = htonl(templ);
4613 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4614 templ = htonl(call->conn->peer->ifMTU);
4615 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4616 sizeof(afs_int32), &templ);
4618 /* new for AFS 3.4 */
4619 templ = htonl(call->rwind);
4620 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4621 sizeof(afs_int32), &templ);
4623 /* new for AFS 3.5 */
4624 templ = htonl(call->conn->peer->ifDgramPackets);
4625 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4626 sizeof(afs_int32), &templ);
4628 p->header.serviceId = call->conn->serviceId;
4629 p->header.cid = (call->conn->cid | call->channel);
4630 p->header.callNumber = *call->callNumber;
4632 p->header.securityIndex = call->conn->securityIndex;
4633 p->header.epoch = call->conn->epoch;
4634 p->header.type = RX_PACKET_TYPE_ACK;
4635 p->header.flags = RX_SLOW_START_OK;
4636 if (reason == RX_ACK_PING) {
4637 p->header.flags |= RX_REQUEST_ACK;
4639 clock_GetTime(&call->pingRequestTime);
4642 if (call->conn->type == RX_CLIENT_CONNECTION)
4643 p->header.flags |= RX_CLIENT_INITIATED;
4647 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u",
4648 ap->reason, ntohl(ap->previousPacket),
4649 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
4651 for (offset = 0; offset < ap->nAcks; offset++)
4652 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4660 register int i, nbytes = p->length;
4662 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
4663 if (nbytes <= p->wirevec[i].iov_len) {
4664 register int savelen, saven;
4666 savelen = p->wirevec[i].iov_len;
4668 p->wirevec[i].iov_len = nbytes;
4670 rxi_Send(call, p, istack);
4671 p->wirevec[i].iov_len = savelen;
4675 nbytes -= p->wirevec[i].iov_len;
4678 MUTEX_ENTER(&rx_stats_mutex);
4679 rx_stats.ackPacketsSent++;
4680 MUTEX_EXIT(&rx_stats_mutex);
4681 if (!optionalPacket)
4683 return optionalPacket; /* Return packet for re-use by caller */
4686 /* Send all of the packets in the list in single datagram */
4688 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
4689 int istack, int moreFlag, struct clock *now,
4690 struct clock *retryTime, int resending)
4695 struct rx_connection *conn = call->conn;
4696 struct rx_peer *peer = conn->peer;
4698 MUTEX_ENTER(&peer->peer_lock);
4701 peer->reSends += len;
4702 MUTEX_ENTER(&rx_stats_mutex);
4703 rx_stats.dataPacketsSent += len;
4704 MUTEX_EXIT(&rx_stats_mutex);
4705 MUTEX_EXIT(&peer->peer_lock);
4707 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
4711 /* Set the packet flags and schedule the resend events */
4712 /* Only request an ack for the last packet in the list */
4713 for (i = 0; i < len; i++) {
4714 list[i]->retryTime = *retryTime;
4715 if (list[i]->header.serial) {
4716 /* Exponentially backoff retry times */
4717 if (list[i]->backoff < MAXBACKOFF) {
4718 /* so it can't stay == 0 */
4719 list[i]->backoff = (list[i]->backoff << 1) + 1;
4722 clock_Addmsec(&(list[i]->retryTime),
4723 ((afs_uint32) list[i]->backoff) << 8);
4726 /* Wait a little extra for the ack on the last packet */
4727 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
4728 clock_Addmsec(&(list[i]->retryTime), 400);
4731 /* Record the time sent */
4732 list[i]->timeSent = *now;
4734 /* Ask for an ack on retransmitted packets, on every other packet
4735 * if the peer doesn't support slow start. Ask for an ack on every
4736 * packet until the congestion window reaches the ack rate. */
4737 if (list[i]->header.serial) {
4739 MUTEX_ENTER(&rx_stats_mutex);
4740 rx_stats.dataPacketsReSent++;
4741 MUTEX_EXIT(&rx_stats_mutex);
4743 /* improved RTO calculation- not Karn */
4744 list[i]->firstSent = *now;
4745 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
4746 || (!(call->flags & RX_CALL_SLOW_START_OK)
4747 && (list[i]->header.seq & 1)))) {
4752 MUTEX_ENTER(&peer->peer_lock);
4756 MUTEX_ENTER(&rx_stats_mutex);
4757 rx_stats.dataPacketsSent++;
4758 MUTEX_EXIT(&rx_stats_mutex);
4759 MUTEX_EXIT(&peer->peer_lock);
4761 /* Tag this packet as not being the last in this group,
4762 * for the receiver's benefit */
4763 if (i < len - 1 || moreFlag) {
4764 list[i]->header.flags |= RX_MORE_PACKETS;
4767 /* Install the new retransmit time for the packet, and
4768 * record the time sent */
4769 list[i]->timeSent = *now;
4773 list[len - 1]->header.flags |= RX_REQUEST_ACK;
4776 /* Since we're about to send a data packet to the peer, it's
4777 * safe to nuke any scheduled end-of-packets ack */
4778 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4780 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
4781 MUTEX_EXIT(&call->lock);
4783 rxi_SendPacketList(call, conn, list, len, istack);
4785 rxi_SendPacket(call, conn, list[0], istack);
4787 MUTEX_ENTER(&call->lock);
4788 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
4790 /* Update last send time for this call (for keep-alive
4791 * processing), and for the connection (so that we can discover
4792 * idle connections) */
4793 conn->lastSendTime = call->lastSendTime = clock_Sec();
4796 /* When sending packets we need to follow these rules:
4797 * 1. Never send more than maxDgramPackets in a jumbogram.
4798 * 2. Never send a packet with more than two iovecs in a jumbogram.
4799 * 3. Never send a retransmitted packet in a jumbogram.
4800 * 4. Never send more than cwind/4 packets in a jumbogram
4801 * We always keep the last list we should have sent so we
4802 * can set the RX_MORE_PACKETS flags correctly.
4805 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
4806 int istack, struct clock *now, struct clock *retryTime,
4809 int i, cnt, lastCnt = 0;
4810 struct rx_packet **listP, **lastP = 0;
4811 struct rx_peer *peer = call->conn->peer;
4812 int morePackets = 0;
4814 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
4815 /* Does the current packet force us to flush the current list? */
4817 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
4818 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
4820 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
4822 /* If the call enters an error state stop sending, or if
4823 * we entered congestion recovery mode, stop sending */
4824 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
4832 /* Add the current packet to the list if it hasn't been acked.
4833 * Otherwise adjust the list pointer to skip the current packet. */
4834 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
4836 /* Do we need to flush the list? */
4837 if (cnt >= (int)peer->maxDgramPackets
4838 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
4839 || list[i]->header.serial
4840 || list[i]->length != RX_JUMBOBUFFERSIZE) {
4842 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
4843 retryTime, resending);
4844 /* If the call enters an error state stop sending, or if
4845 * we entered congestion recovery mode, stop sending */
4847 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
4852 listP = &list[i + 1];
4857 osi_Panic("rxi_SendList error");
4859 listP = &list[i + 1];
4863 /* Send the whole list when the call is in receive mode, when
4864 * the call is in eof mode, when we are in fast recovery mode,
4865 * and when we have the last packet */
4866 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
4867 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
4868 || (call->flags & RX_CALL_FAST_RECOVER)) {
4869 /* Check for the case where the current list contains
4870 * an acked packet. Since we always send retransmissions
4871 * in a separate packet, we only need to check the first
4872 * packet in the list */
4873 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
4877 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
4878 retryTime, resending);
4879 /* If the call enters an error state stop sending, or if
4880 * we entered congestion recovery mode, stop sending */
4881 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
4885 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
4888 } else if (lastCnt > 0) {
4889 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
4894 #ifdef RX_ENABLE_LOCKS
4895 /* Call rxi_Start, below, but with the call lock held. */
4897 rxi_StartUnlocked(struct rxevent *event, register struct rx_call *call,
4898 void *arg1, int istack)
4900 MUTEX_ENTER(&call->lock);
4901 rxi_Start(event, call, arg1, istack);
4902 MUTEX_EXIT(&call->lock);
4904 #endif /* RX_ENABLE_LOCKS */
4906 /* This routine is called when new packets are readied for
4907 * transmission and when retransmission may be necessary, or when the
4908 * transmission window or burst count are favourable. This should be
4909 * better optimized for new packets, the usual case, now that we've
4910 * got rid of queues of send packets. XXXXXXXXXXX */
4912 rxi_Start(struct rxevent *event, register struct rx_call *call,
4913 void *arg1, int istack)
4915 struct rx_packet *p;
4916 register struct rx_packet *nxp; /* Next pointer for queue_Scan */
4917 struct rx_peer *peer = call->conn->peer;
4918 struct clock now, retryTime;
4922 struct rx_packet **xmitList;
4925 /* If rxi_Start is being called as a result of a resend event,
4926 * then make sure that the event pointer is removed from the call
4927 * structure, since there is no longer a per-call retransmission
4929 if (event && event == call->resendEvent) {
4930 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
4931 call->resendEvent = NULL;
4933 if (queue_IsEmpty(&call->tq)) {
4937 /* Timeouts trigger congestion recovery */
4938 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4939 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4940 /* someone else is waiting to start recovery */
4943 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4944 while (call->flags & RX_CALL_TQ_BUSY) {
4945 call->flags |= RX_CALL_TQ_WAIT;
4946 #ifdef RX_ENABLE_LOCKS
4947 CV_WAIT(&call->cv_tq, &call->lock);
4948 #else /* RX_ENABLE_LOCKS */
4949 osi_rxSleep(&call->tq);
4950 #endif /* RX_ENABLE_LOCKS */
4952 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4953 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4954 call->flags |= RX_CALL_FAST_RECOVER;
4955 if (peer->maxDgramPackets > 1) {
4956 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4958 call->MTU = MIN(peer->natMTU, peer->maxMTU);
4960 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4961 call->nDgramPackets = 1;
4963 call->nextCwind = 1;
4966 MUTEX_ENTER(&peer->peer_lock);
4967 peer->MTU = call->MTU;
4968 peer->cwind = call->cwind;
4969 peer->nDgramPackets = 1;
4971 call->congestSeq = peer->congestSeq;
4972 MUTEX_EXIT(&peer->peer_lock);
4973 /* Clear retry times on packets. Otherwise, it's possible for
4974 * some packets in the queue to force resends at rates faster
4975 * than recovery rates.
4977 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
4978 if (!(p->flags & RX_PKTFLAG_ACKED)) {
4979 clock_Zero(&p->retryTime);
4984 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4985 MUTEX_ENTER(&rx_stats_mutex);
4986 rx_tq_debug.rxi_start_in_error++;
4987 MUTEX_EXIT(&rx_stats_mutex);
4992 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
4993 /* Get clock to compute the re-transmit time for any packets
4994 * in this burst. Note, if we back off, it's reasonable to
4995 * back off all of the packets in the same manner, even if
4996 * some of them have been retransmitted more times than more
4997 * recent additions */
4998 clock_GetTime(&now);
4999 retryTime = now; /* initialize before use */
5000 MUTEX_ENTER(&peer->peer_lock);
5001 clock_Add(&retryTime, &peer->timeout);
5002 MUTEX_EXIT(&peer->peer_lock);
5004 /* Send (or resend) any packets that need it, subject to
5005 * window restrictions and congestion burst control
5006 * restrictions. Ask for an ack on the last packet sent in
5007 * this burst. For now, we're relying upon the window being
5008 * considerably bigger than the largest number of packets that
5009 * are typically sent at once by one initial call to
5010 * rxi_Start. This is probably bogus (perhaps we should ask
5011 * for an ack when we're half way through the current
5012 * window?). Also, for non file transfer applications, this
5013 * may end up asking for an ack for every packet. Bogus. XXXX
5016 * But check whether we're here recursively, and let the other guy
5019 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5020 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5021 call->flags |= RX_CALL_TQ_BUSY;
5023 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5025 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5026 call->flags &= ~RX_CALL_NEED_START;
5027 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5029 maxXmitPackets = MIN(call->twind, call->cwind);
5030 xmitList = (struct rx_packet **)
5031 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5032 if (xmitList == NULL)
5033 osi_Panic("rxi_Start, failed to allocate xmit list");
5034 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5035 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5036 /* We shouldn't be sending packets if a thread is waiting
5037 * to initiate congestion recovery */
5041 && (call->flags & RX_CALL_FAST_RECOVER)) {
5042 /* Only send one packet during fast recovery */
5045 if ((p->flags & RX_PKTFLAG_FREE)
5046 || (!queue_IsEnd(&call->tq, nxp)
5047 && (nxp->flags & RX_PKTFLAG_FREE))
5048 || (p == (struct rx_packet *)&rx_freePacketQueue)
5049 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5050 osi_Panic("rxi_Start: xmit queue clobbered");
5052 if (p->flags & RX_PKTFLAG_ACKED) {
5053 MUTEX_ENTER(&rx_stats_mutex);
5054 rx_stats.ignoreAckedPacket++;
5055 MUTEX_EXIT(&rx_stats_mutex);
5056 continue; /* Ignore this packet if it has been acknowledged */
5059 /* Turn off all flags except these ones, which are the same
5060 * on each transmission */
5061 p->header.flags &= RX_PRESET_FLAGS;
5063 if (p->header.seq >=
5064 call->tfirst + MIN((int)call->twind,
5065 (int)(call->nSoftAcked +
5067 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5068 /* Note: if we're waiting for more window space, we can
5069 * still send retransmits; hence we don't return here, but
5070 * break out to schedule a retransmit event */
5071 dpf(("call %d waiting for window",
5072 *(call->callNumber)));
5076 /* Transmit the packet if it needs to be sent. */
5077 if (!clock_Lt(&now, &p->retryTime)) {
5078 if (nXmitPackets == maxXmitPackets) {
5079 rxi_SendXmitList(call, xmitList, nXmitPackets,
5080 istack, &now, &retryTime,
5082 osi_Free(xmitList, maxXmitPackets *
5083 sizeof(struct rx_packet *));
5086 xmitList[nXmitPackets++] = p;
5090 /* xmitList now hold pointers to all of the packets that are
5091 * ready to send. Now we loop to send the packets */
5092 if (nXmitPackets > 0) {
5093 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5094 &now, &retryTime, resending);
5097 maxXmitPackets * sizeof(struct rx_packet *));
5099 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5101 * TQ references no longer protected by this flag; they must remain
5102 * protected by the global lock.
5104 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5105 call->flags &= ~RX_CALL_TQ_BUSY;
5106 if (call->flags & RX_CALL_TQ_WAIT) {
5107 call->flags &= ~RX_CALL_TQ_WAIT;
5108 #ifdef RX_ENABLE_LOCKS
5109 CV_BROADCAST(&call->cv_tq);
5110 #else /* RX_ENABLE_LOCKS */
5111 osi_rxWakeup(&call->tq);
5112 #endif /* RX_ENABLE_LOCKS */
5117 /* We went into the error state while sending packets. Now is
5118 * the time to reset the call. This will also inform the using
5119 * process that the call is in an error state.
5121 MUTEX_ENTER(&rx_stats_mutex);
5122 rx_tq_debug.rxi_start_aborted++;
5123 MUTEX_EXIT(&rx_stats_mutex);
5124 call->flags &= ~RX_CALL_TQ_BUSY;
5125 if (call->flags & RX_CALL_TQ_WAIT) {
5126 call->flags &= ~RX_CALL_TQ_WAIT;
5127 #ifdef RX_ENABLE_LOCKS
5128 CV_BROADCAST(&call->cv_tq);
5129 #else /* RX_ENABLE_LOCKS */
5130 osi_rxWakeup(&call->tq);
5131 #endif /* RX_ENABLE_LOCKS */
5133 rxi_CallError(call, call->error);
5136 #ifdef RX_ENABLE_LOCKS
5137 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5138 register int missing;
5139 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5140 /* Some packets have received acks. If they all have, we can clear
5141 * the transmit queue.
5144 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5145 if (p->header.seq < call->tfirst
5146 && (p->flags & RX_PKTFLAG_ACKED)) {
5153 call->flags |= RX_CALL_TQ_CLEARME;
5155 #endif /* RX_ENABLE_LOCKS */
5156 /* Don't bother doing retransmits if the TQ is cleared. */
5157 if (call->flags & RX_CALL_TQ_CLEARME) {
5158 rxi_ClearTransmitQueue(call, 1);
5160 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5163 /* Always post a resend event, if there is anything in the
5164 * queue, and resend is possible. There should be at least
5165 * one unacknowledged packet in the queue ... otherwise none
5166 * of these packets should be on the queue in the first place.
5168 if (call->resendEvent) {
5169 /* Cancel the existing event and post a new one */
5170 rxevent_Cancel(call->resendEvent, call,
5171 RX_CALL_REFCOUNT_RESEND);
5174 /* The retry time is the retry time on the first unacknowledged
5175 * packet inside the current window */
5177 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5178 /* Don't set timers for packets outside the window */
5179 if (p->header.seq >= call->tfirst + call->twind) {
5183 if (!(p->flags & RX_PKTFLAG_ACKED)
5184 && !clock_IsZero(&p->retryTime)) {
5186 retryTime = p->retryTime;
5191 /* Post a new event to re-run rxi_Start when retries may be needed */
5192 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5193 #ifdef RX_ENABLE_LOCKS
5194 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5196 rxevent_Post2(&retryTime, rxi_StartUnlocked,
5197 (void *)call, 0, istack);
5198 #else /* RX_ENABLE_LOCKS */
5200 rxevent_Post2(&retryTime, rxi_Start, (void *)call,
5202 #endif /* RX_ENABLE_LOCKS */
5205 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5206 } while (call->flags & RX_CALL_NEED_START);
5208 * TQ references no longer protected by this flag; they must remain
5209 * protected by the global lock.
5211 call->flags &= ~RX_CALL_TQ_BUSY;
5212 if (call->flags & RX_CALL_TQ_WAIT) {
5213 call->flags &= ~RX_CALL_TQ_WAIT;
5214 #ifdef RX_ENABLE_LOCKS
5215 CV_BROADCAST(&call->cv_tq);
5216 #else /* RX_ENABLE_LOCKS */
5217 osi_rxWakeup(&call->tq);
5218 #endif /* RX_ENABLE_LOCKS */
5221 call->flags |= RX_CALL_NEED_START;
5223 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5225 if (call->resendEvent) {
5226 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5231 /* Also adjusts the keep alive parameters for the call, to reflect
5232 * that we have just sent a packet (so keep alives aren't sent
5235 rxi_Send(register struct rx_call *call, register struct rx_packet *p,
5238 register struct rx_connection *conn = call->conn;
5240 /* Stamp each packet with the user supplied status */
5241 p->header.userStatus = call->localStatus;
5243 /* Allow the security object controlling this call's security to
5244 * make any last-minute changes to the packet */
5245 RXS_SendPacket(conn->securityObject, call, p);
5247 /* Since we're about to send SOME sort of packet to the peer, it's
5248 * safe to nuke any scheduled end-of-packets ack */
5249 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5251 /* Actually send the packet, filling in more connection-specific fields */
5252 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5253 MUTEX_EXIT(&call->lock);
5254 rxi_SendPacket(call, conn, p, istack);
5255 MUTEX_ENTER(&call->lock);
5256 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5258 /* Update last send time for this call (for keep-alive
5259 * processing), and for the connection (so that we can discover
5260 * idle connections) */
5261 conn->lastSendTime = call->lastSendTime = clock_Sec();
5265 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5266 * that things are fine. Also called periodically to guarantee that nothing
5267 * falls through the cracks (e.g. (error + dally) connections have keepalive
5268 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5270 * haveCTLock Set if calling from rxi_ReapConnections
5272 #ifdef RX_ENABLE_LOCKS
5274 rxi_CheckCall(register struct rx_call *call, int haveCTLock)
5275 #else /* RX_ENABLE_LOCKS */
5277 rxi_CheckCall(register struct rx_call *call)
5278 #endif /* RX_ENABLE_LOCKS */
5280 register struct rx_connection *conn = call->conn;
5282 afs_uint32 deadTime;
5284 #ifdef RX_GLOBAL_RXLOCK_KERNEL
5285 if (call->flags & RX_CALL_TQ_BUSY) {
5286 /* Call is active and will be reset by rxi_Start if it's
5287 * in an error state.
5292 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5294 (((afs_uint32) conn->secondsUntilDead << 10) +
5295 ((afs_uint32) conn->peer->rtt >> 3) +
5296 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5298 /* These are computed to the second (+- 1 second). But that's
5299 * good enough for these values, which should be a significant
5300 * number of seconds. */
5301 if (now > (call->lastReceiveTime + deadTime)) {
5302 if (call->state == RX_STATE_ACTIVE) {
5303 rxi_CallError(call, RX_CALL_DEAD);
5306 #ifdef RX_ENABLE_LOCKS
5307 /* Cancel pending events */
5308 rxevent_Cancel(call->delayedAckEvent, call,
5309 RX_CALL_REFCOUNT_DELAY);
5310 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5311 rxevent_Cancel(call->keepAliveEvent, call,
5312 RX_CALL_REFCOUNT_ALIVE);
5313 if (call->refCount == 0) {
5314 rxi_FreeCall(call, haveCTLock);
5318 #else /* RX_ENABLE_LOCKS */
5321 #endif /* RX_ENABLE_LOCKS */
5323 /* Non-active calls are destroyed if they are not responding
5324 * to pings; active calls are simply flagged in error, so the
5325 * attached process can die reasonably gracefully. */
5327 /* see if we have a non-activity timeout */
5328 if (call->startWait && conn->idleDeadTime
5329 && ((call->startWait + conn->idleDeadTime) < now)) {
5330 if (call->state == RX_STATE_ACTIVE) {
5331 rxi_CallError(call, RX_CALL_TIMEOUT);
5335 /* see if we have a hard timeout */
5336 if (conn->hardDeadTime
5337 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5338 if (call->state == RX_STATE_ACTIVE)
5339 rxi_CallError(call, RX_CALL_TIMEOUT);
5346 /* When a call is in progress, this routine is called occasionally to
5347 * make sure that some traffic has arrived (or been sent to) the peer.
5348 * If nothing has arrived in a reasonable amount of time, the call is
5349 * declared dead; if nothing has been sent for a while, we send a
5350 * keep-alive packet (if we're actually trying to keep the call alive)
5353 rxi_KeepAliveEvent(struct rxevent *event, register struct rx_call *call,
5356 struct rx_connection *conn;
5359 MUTEX_ENTER(&call->lock);
5360 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5361 if (event == call->keepAliveEvent)
5362 call->keepAliveEvent = NULL;
5365 #ifdef RX_ENABLE_LOCKS
5366 if (rxi_CheckCall(call, 0)) {
5367 MUTEX_EXIT(&call->lock);
5370 #else /* RX_ENABLE_LOCKS */
5371 if (rxi_CheckCall(call))
5373 #endif /* RX_ENABLE_LOCKS */
5375 /* Don't try to keep alive dallying calls */
5376 if (call->state == RX_STATE_DALLY) {
5377 MUTEX_EXIT(&call->lock);
5382 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
5383 /* Don't try to send keepalives if there is unacknowledged data */
5384 /* the rexmit code should be good enough, this little hack
5385 * doesn't quite work XXX */
5386 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5388 rxi_ScheduleKeepAliveEvent(call);
5389 MUTEX_EXIT(&call->lock);
5394 rxi_ScheduleKeepAliveEvent(register struct rx_call *call)
5396 if (!call->keepAliveEvent) {
5398 clock_GetTime(&when);
5399 when.sec += call->conn->secondsUntilPing;
5400 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5401 call->keepAliveEvent =
5402 rxevent_Post(&when, rxi_KeepAliveEvent, call, 0);
5406 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5408 rxi_KeepAliveOn(register struct rx_call *call)
5410 /* Pretend last packet received was received now--i.e. if another
5411 * packet isn't received within the keep alive time, then the call
5412 * will die; Initialize last send time to the current time--even
5413 * if a packet hasn't been sent yet. This will guarantee that a
5414 * keep-alive is sent within the ping time */
5415 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5416 rxi_ScheduleKeepAliveEvent(call);
5419 /* This routine is called to send connection abort messages
5420 * that have been delayed to throttle looping clients. */
5422 rxi_SendDelayedConnAbort(struct rxevent *event,
5423 register struct rx_connection *conn, char *dummy)
5426 struct rx_packet *packet;
5428 MUTEX_ENTER(&conn->conn_data_lock);
5429 conn->delayedAbortEvent = NULL;
5430 error = htonl(conn->error);
5432 MUTEX_EXIT(&conn->conn_data_lock);
5433 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5436 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5437 RX_PACKET_TYPE_ABORT, (char *)&error,
5439 rxi_FreePacket(packet);
5443 /* This routine is called to send call abort messages
5444 * that have been delayed to throttle looping clients. */
5446 rxi_SendDelayedCallAbort(struct rxevent *event, register struct rx_call *call,
5450 struct rx_packet *packet;
5452 MUTEX_ENTER(&call->lock);
5453 call->delayedAbortEvent = NULL;
5454 error = htonl(call->error);
5456 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5459 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5460 (char *)&error, sizeof(error), 0);
5461 rxi_FreePacket(packet);
5463 MUTEX_EXIT(&call->lock);
5466 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5467 * seconds) to ask the client to authenticate itself. The routine
5468 * issues a challenge to the client, which is obtained from the
5469 * security object associated with the connection */
5471 rxi_ChallengeEvent(struct rxevent *event, register struct rx_connection *conn,
5472 void *arg1, int tries)
5474 conn->challengeEvent = NULL;
5475 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5476 register struct rx_packet *packet;
5480 /* We've failed to authenticate for too long.
5481 * Reset any calls waiting for authentication;
5482 * they are all in RX_STATE_PRECALL.
5486 MUTEX_ENTER(&conn->conn_call_lock);
5487 for (i = 0; i < RX_MAXCALLS; i++) {
5488 struct rx_call *call = conn->call[i];
5490 MUTEX_ENTER(&call->lock);
5491 if (call->state == RX_STATE_PRECALL) {
5492 rxi_CallError(call, RX_CALL_DEAD);
5493 rxi_SendCallAbort(call, NULL, 0, 0);
5495 MUTEX_EXIT(&call->lock);
5498 MUTEX_EXIT(&conn->conn_call_lock);
5502 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5504 /* If there's no packet available, do this later. */
5505 RXS_GetChallenge(conn->securityObject, conn, packet);
5506 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5507 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5508 rxi_FreePacket(packet);
5510 clock_GetTime(&when);
5511 when.sec += RX_CHALLENGE_TIMEOUT;
5512 conn->challengeEvent =
5513 rxevent_Post2(&when, rxi_ChallengeEvent, conn, 0,
5518 /* Call this routine to start requesting the client to authenticate
5519 * itself. This will continue until authentication is established,
5520 * the call times out, or an invalid response is returned. The
5521 * security object associated with the connection is asked to create
5522 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5523 * defined earlier. */
5525 rxi_ChallengeOn(register struct rx_connection *conn)
5527 if (!conn->challengeEvent) {
5528 RXS_CreateChallenge(conn->securityObject, conn);
5529 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5534 /* Compute round trip time of the packet provided, in *rttp.
5537 /* rxi_ComputeRoundTripTime is called with peer locked. */
5538 /* sentp and/or peer may be null */
5540 rxi_ComputeRoundTripTime(register struct rx_packet *p,
5541 register struct clock *sentp,
5542 register struct rx_peer *peer)
5544 struct clock thisRtt, *rttp = &thisRtt;
5546 register int rtt_timeout;
5548 clock_GetTime(rttp);
5550 if (clock_Lt(rttp, sentp)) {
5552 return; /* somebody set the clock back, don't count this time. */
5554 clock_Sub(rttp, sentp);
5555 MUTEX_ENTER(&rx_stats_mutex);
5556 if (clock_Lt(rttp, &rx_stats.minRtt))
5557 rx_stats.minRtt = *rttp;
5558 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5559 if (rttp->sec > 60) {
5560 MUTEX_EXIT(&rx_stats_mutex);
5561 return; /* somebody set the clock ahead */
5563 rx_stats.maxRtt = *rttp;
5565 clock_Add(&rx_stats.totalRtt, rttp);
5566 rx_stats.nRttSamples++;
5567 MUTEX_EXIT(&rx_stats_mutex);
5569 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
5571 /* Apply VanJacobson round-trip estimations */
5576 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
5577 * srtt is stored as fixed point with 3 bits after the binary
5578 * point (i.e., scaled by 8). The following magic is
5579 * equivalent to the smoothing algorithm in rfc793 with an
5580 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
5581 * srtt*8 = srtt*8 + rtt - srtt
5582 * srtt = srtt + rtt/8 - srtt/8
5585 delta = MSEC(rttp) - (peer->rtt >> 3);
5589 * We accumulate a smoothed rtt variance (actually, a smoothed
5590 * mean difference), then set the retransmit timer to smoothed
5591 * rtt + 4 times the smoothed variance (was 2x in van's original
5592 * paper, but 4x works better for me, and apparently for him as
5594 * rttvar is stored as
5595 * fixed point with 2 bits after the binary point (scaled by
5596 * 4). The following is equivalent to rfc793 smoothing with
5597 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
5598 * replaces rfc793's wired-in beta.
5599 * dev*4 = dev*4 + (|actual - expected| - dev)
5605 delta -= (peer->rtt_dev >> 2);
5606 peer->rtt_dev += delta;
5608 /* I don't have a stored RTT so I start with this value. Since I'm
5609 * probably just starting a call, and will be pushing more data down
5610 * this, I expect congestion to increase rapidly. So I fudge a
5611 * little, and I set deviance to half the rtt. In practice,
5612 * deviance tends to approach something a little less than
5613 * half the smoothed rtt. */
5614 peer->rtt = (MSEC(rttp) << 3) + 8;
5615 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
5617 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
5618 * the other of these connections is usually in a user process, and can
5619 * be switched and/or swapped out. So on fast, reliable networks, the
5620 * timeout would otherwise be too short.
5622 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
5623 clock_Zero(&(peer->timeout));
5624 clock_Addmsec(&(peer->timeout), rtt_timeout);
5626 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)));
5630 /* Find all server connections that have not been active for a long time, and
5633 rxi_ReapConnections(void)
5636 clock_GetTime(&now);
5638 /* Find server connection structures that haven't been used for
5639 * greater than rx_idleConnectionTime */
5641 struct rx_connection **conn_ptr, **conn_end;
5642 int i, havecalls = 0;
5643 MUTEX_ENTER(&rx_connHashTable_lock);
5644 for (conn_ptr = &rx_connHashTable[0], conn_end =
5645 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
5647 struct rx_connection *conn, *next;
5648 struct rx_call *call;
5652 for (conn = *conn_ptr; conn; conn = next) {
5653 /* XXX -- Shouldn't the connection be locked? */
5656 for (i = 0; i < RX_MAXCALLS; i++) {
5657 call = conn->call[i];
5660 MUTEX_ENTER(&call->lock);
5661 #ifdef RX_ENABLE_LOCKS
5662 result = rxi_CheckCall(call, 1);
5663 #else /* RX_ENABLE_LOCKS */
5664 result = rxi_CheckCall(call);
5665 #endif /* RX_ENABLE_LOCKS */
5666 MUTEX_EXIT(&call->lock);
5668 /* If CheckCall freed the call, it might
5669 * have destroyed the connection as well,
5670 * which screws up the linked lists.
5676 if (conn->type == RX_SERVER_CONNECTION) {
5677 /* This only actually destroys the connection if
5678 * there are no outstanding calls */
5679 MUTEX_ENTER(&conn->conn_data_lock);
5680 if (!havecalls && !conn->refCount
5681 && ((conn->lastSendTime + rx_idleConnectionTime) <
5683 conn->refCount++; /* it will be decr in rx_DestroyConn */
5684 MUTEX_EXIT(&conn->conn_data_lock);
5685 #ifdef RX_ENABLE_LOCKS
5686 rxi_DestroyConnectionNoLock(conn);
5687 #else /* RX_ENABLE_LOCKS */
5688 rxi_DestroyConnection(conn);
5689 #endif /* RX_ENABLE_LOCKS */
5691 #ifdef RX_ENABLE_LOCKS
5693 MUTEX_EXIT(&conn->conn_data_lock);
5695 #endif /* RX_ENABLE_LOCKS */
5699 #ifdef RX_ENABLE_LOCKS
5700 while (rx_connCleanup_list) {
5701 struct rx_connection *conn;
5702 conn = rx_connCleanup_list;
5703 rx_connCleanup_list = rx_connCleanup_list->next;
5704 MUTEX_EXIT(&rx_connHashTable_lock);
5705 rxi_CleanupConnection(conn);
5706 MUTEX_ENTER(&rx_connHashTable_lock);
5708 MUTEX_EXIT(&rx_connHashTable_lock);
5709 #endif /* RX_ENABLE_LOCKS */
5712 /* Find any peer structures that haven't been used (haven't had an
5713 * associated connection) for greater than rx_idlePeerTime */
5715 struct rx_peer **peer_ptr, **peer_end;
5717 MUTEX_ENTER(&rx_rpc_stats);
5718 MUTEX_ENTER(&rx_peerHashTable_lock);
5719 for (peer_ptr = &rx_peerHashTable[0], peer_end =
5720 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
5722 struct rx_peer *peer, *next, *prev;
5723 for (prev = peer = *peer_ptr; peer; peer = next) {
5725 code = MUTEX_TRYENTER(&peer->peer_lock);
5726 if ((code) && (peer->refCount == 0)
5727 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
5728 rx_interface_stat_p rpc_stat, nrpc_stat;
5730 MUTEX_EXIT(&peer->peer_lock);
5731 MUTEX_DESTROY(&peer->peer_lock);
5733 (&peer->rpcStats, rpc_stat, nrpc_stat,
5734 rx_interface_stat)) {
5735 unsigned int num_funcs;
5738 queue_Remove(&rpc_stat->queue_header);
5739 queue_Remove(&rpc_stat->all_peers);
5740 num_funcs = rpc_stat->stats[0].func_total;
5742 sizeof(rx_interface_stat_t) +
5743 rpc_stat->stats[0].func_total *
5744 sizeof(rx_function_entry_v1_t);
5746 rxi_Free(rpc_stat, space);
5747 rxi_rpc_peer_stat_cnt -= num_funcs;
5750 MUTEX_ENTER(&rx_stats_mutex);
5751 rx_stats.nPeerStructs--;
5752 MUTEX_EXIT(&rx_stats_mutex);
5753 if (peer == *peer_ptr) {
5760 MUTEX_EXIT(&peer->peer_lock);
5766 MUTEX_EXIT(&rx_peerHashTable_lock);
5767 MUTEX_EXIT(&rx_rpc_stats);
5770 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
5771 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
5772 * GC, just below. Really, we shouldn't have to keep moving packets from
5773 * one place to another, but instead ought to always know if we can
5774 * afford to hold onto a packet in its particular use. */
5775 MUTEX_ENTER(&rx_freePktQ_lock);
5776 if (rx_waitingForPackets) {
5777 rx_waitingForPackets = 0;
5778 #ifdef RX_ENABLE_LOCKS
5779 CV_BROADCAST(&rx_waitingForPackets_cv);
5781 osi_rxWakeup(&rx_waitingForPackets);
5784 MUTEX_EXIT(&rx_freePktQ_lock);
5786 now.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
5787 rxevent_Post(&now, rxi_ReapConnections, 0, 0);
5791 /* rxs_Release - This isn't strictly necessary but, since the macro name from
5792 * rx.h is sort of strange this is better. This is called with a security
5793 * object before it is discarded. Each connection using a security object has
5794 * its own refcount to the object so it won't actually be freed until the last
5795 * connection is destroyed.
5797 * This is the only rxs module call. A hold could also be written but no one
5801 rxs_Release(struct rx_securityClass *aobj)
5803 return RXS_Close(aobj);
5807 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
5808 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
5809 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
5810 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
5812 /* Adjust our estimate of the transmission rate to this peer, given
5813 * that the packet p was just acked. We can adjust peer->timeout and
5814 * call->twind. Pragmatically, this is called
5815 * only with packets of maximal length.
5816 * Called with peer and call locked.
5820 rxi_ComputeRate(register struct rx_peer *peer, register struct rx_call *call,
5821 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
5823 afs_int32 xferSize, xferMs;
5824 register afs_int32 minTime;
5827 /* Count down packets */
5828 if (peer->rateFlag > 0)
5830 /* Do nothing until we're enabled */
5831 if (peer->rateFlag != 0)
5836 /* Count only when the ack seems legitimate */
5837 switch (ackReason) {
5838 case RX_ACK_REQUESTED:
5840 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
5844 case RX_ACK_PING_RESPONSE:
5845 if (p) /* want the response to ping-request, not data send */
5847 clock_GetTime(&newTO);
5848 if (clock_Gt(&newTO, &call->pingRequestTime)) {
5849 clock_Sub(&newTO, &call->pingRequestTime);
5850 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
5854 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
5861 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));
5863 /* Track only packets that are big enough. */
5864 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
5868 /* absorb RTT data (in milliseconds) for these big packets */
5869 if (peer->smRtt == 0) {
5870 peer->smRtt = xferMs;
5872 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
5877 if (peer->countDown) {
5881 peer->countDown = 10; /* recalculate only every so often */
5883 /* In practice, we can measure only the RTT for full packets,
5884 * because of the way Rx acks the data that it receives. (If it's
5885 * smaller than a full packet, it often gets implicitly acked
5886 * either by the call response (from a server) or by the next call
5887 * (from a client), and either case confuses transmission times
5888 * with processing times.) Therefore, replace the above
5889 * more-sophisticated processing with a simpler version, where the
5890 * smoothed RTT is kept for full-size packets, and the time to
5891 * transmit a windowful of full-size packets is simply RTT *
5892 * windowSize. Again, we take two steps:
5893 - ensure the timeout is large enough for a single packet's RTT;
5894 - ensure that the window is small enough to fit in the desired timeout.*/
5896 /* First, the timeout check. */
5897 minTime = peer->smRtt;
5898 /* Get a reasonable estimate for a timeout period */
5900 newTO.sec = minTime / 1000;
5901 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
5903 /* Increase the timeout period so that we can always do at least
5904 * one packet exchange */
5905 if (clock_Gt(&newTO, &peer->timeout)) {
5907 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));
5909 peer->timeout = newTO;
5912 /* Now, get an estimate for the transmit window size. */
5913 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
5914 /* Now, convert to the number of full packets that could fit in a
5915 * reasonable fraction of that interval */
5916 minTime /= (peer->smRtt << 1);
5917 xferSize = minTime; /* (make a copy) */
5919 /* Now clamp the size to reasonable bounds. */
5922 else if (minTime > rx_Window)
5923 minTime = rx_Window;
5924 /* if (minTime != peer->maxWindow) {
5925 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
5926 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
5927 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
5929 peer->maxWindow = minTime;
5930 elide... call->twind = minTime;
5934 /* Cut back on the peer timeout if it had earlier grown unreasonably.
5935 * Discern this by calculating the timeout necessary for rx_Window
5937 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
5938 /* calculate estimate for transmission interval in milliseconds */
5939 minTime = rx_Window * peer->smRtt;
5940 if (minTime < 1000) {
5941 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
5942 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
5943 peer->timeout.usec, peer->smRtt, peer->packetSize));
5945 newTO.sec = 0; /* cut back on timeout by half a second */
5946 newTO.usec = 500000;
5947 clock_Sub(&peer->timeout, &newTO);
5952 } /* end of rxi_ComputeRate */
5953 #endif /* ADAPT_WINDOW */
5961 /* Don't call this debugging routine directly; use dpf */
5963 rxi_DebugPrint(char *format, int a1, int a2, int a3, int a4, int a5, int a6,
5964 int a7, int a8, int a9, int a10, int a11, int a12, int a13,
5968 clock_GetTime(&now);
5969 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
5970 (unsigned int)now.usec / 1000);
5971 fprintf(rx_Log, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12,
5979 * This function is used to process the rx_stats structure that is local
5980 * to a process as well as an rx_stats structure received from a remote
5981 * process (via rxdebug). Therefore, it needs to do minimal version
5985 rx_PrintTheseStats(FILE * file, struct rx_stats *s, int size,
5986 afs_int32 freePackets, char version)
5990 if (size != sizeof(struct rx_stats)) {
5992 "Unexpected size of stats structure: was %d, expected %d\n",
5993 size, sizeof(struct rx_stats));
5996 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
5999 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6000 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
6001 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6002 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6003 s->specialPktAllocFailures);
6005 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
6006 s->receivePktAllocFailures, s->sendPktAllocFailures,
6007 s->specialPktAllocFailures);
6011 " greedy %d, " "bogusReads %d (last from host %x), "
6012 "noPackets %d, " "noBuffers %d, " "selects %d, "
6013 "sendSelects %d\n", s->socketGreedy, s->bogusPacketOnRead,
6014 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6015 s->selects, s->sendSelects);
6017 fprintf(file, " packets read: ");
6018 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6019 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsRead[i]);
6021 fprintf(file, "\n");
6024 " other read counters: data %d, " "ack %d, " "dup %d "
6025 "spurious %d " "dally %d\n", s->dataPacketsRead,
6026 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6027 s->ignorePacketDally);
6029 fprintf(file, " packets sent: ");
6030 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6031 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsSent[i]);
6033 fprintf(file, "\n");
6036 " other send counters: ack %d, " "data %d (not resends), "
6037 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6038 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6039 s->dataPacketsPushed, s->ignoreAckedPacket);
6042 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6043 s->netSendFailures, (int)s->fatalErrors);
6045 if (s->nRttSamples) {
6046 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6047 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6049 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6050 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6054 " %d server connections, " "%d client connections, "
6055 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6056 s->nServerConns, s->nClientConns, s->nPeerStructs,
6057 s->nCallStructs, s->nFreeCallStructs);
6059 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6060 fprintf(file, " %d clock updates\n", clock_nUpdates);
6065 /* for backward compatibility */
6067 rx_PrintStats(FILE * file)
6069 MUTEX_ENTER(&rx_stats_mutex);
6070 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6072 MUTEX_EXIT(&rx_stats_mutex);
6076 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6078 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6079 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6080 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6083 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6084 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6085 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6088 " Packet size %d, " "max in packet skew %d, "
6089 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6090 (int)peer->outPacketSkew);
6093 #ifdef AFS_PTHREAD_ENV
6095 * This mutex protects the following static variables:
6099 #define LOCK_RX_DEBUG assert(pthread_mutex_lock(&rx_debug_mutex)==0)
6100 #define UNLOCK_RX_DEBUG assert(pthread_mutex_unlock(&rx_debug_mutex)==0)
6102 #define LOCK_RX_DEBUG
6103 #define UNLOCK_RX_DEBUG
6104 #endif /* AFS_PTHREAD_ENV */
6107 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6108 u_char type, void *inputData, size_t inputLength,
6109 void *outputData, size_t outputLength)
6111 static afs_int32 counter = 100;
6113 struct rx_header theader;
6115 register afs_int32 code;
6117 struct sockaddr_in taddr, faddr;
6122 endTime = time(0) + 20; /* try for 20 seconds */
6126 tp = &tbuffer[sizeof(struct rx_header)];
6127 taddr.sin_family = AF_INET;
6128 taddr.sin_port = remotePort;
6129 taddr.sin_addr.s_addr = remoteAddr;
6130 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6131 taddr.sin_len = sizeof(struct sockaddr_in);
6134 memset(&theader, 0, sizeof(theader));
6135 theader.epoch = htonl(999);
6137 theader.callNumber = htonl(counter);
6140 theader.type = type;
6141 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6142 theader.serviceId = 0;
6144 memcpy(tbuffer, &theader, sizeof(theader));
6145 memcpy(tp, inputData, inputLength);
6147 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6148 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6150 /* see if there's a packet available */
6152 FD_SET(socket, &imask);
6155 code = select(socket + 1, &imask, 0, 0, &tv);
6156 if (code == 1 && FD_ISSET(socket, &imask)) {
6157 /* now receive a packet */
6158 faddrLen = sizeof(struct sockaddr_in);
6160 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6161 (struct sockaddr *)&faddr, &faddrLen);
6164 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6165 if (counter == ntohl(theader.callNumber))
6170 /* see if we've timed out */
6171 if (endTime < time(0))
6174 code -= sizeof(struct rx_header);
6175 if (code > outputLength)
6176 code = outputLength;
6177 memcpy(outputData, tp, code);
6182 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6183 afs_uint16 remotePort, struct rx_debugStats * stat,
6184 afs_uint32 * supportedValues)
6186 struct rx_debugIn in;
6189 *supportedValues = 0;
6190 in.type = htonl(RX_DEBUGI_GETSTATS);
6193 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6194 &in, sizeof(in), stat, sizeof(*stat));
6197 * If the call was successful, fixup the version and indicate
6198 * what contents of the stat structure are valid.
6199 * Also do net to host conversion of fields here.
6203 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6204 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6206 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6207 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6209 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6210 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6212 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6213 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6215 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6216 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6218 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6219 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6221 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6222 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6224 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6225 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6228 stat->nFreePackets = ntohl(stat->nFreePackets);
6229 stat->packetReclaims = ntohl(stat->packetReclaims);
6230 stat->callsExecuted = ntohl(stat->callsExecuted);
6231 stat->nWaiting = ntohl(stat->nWaiting);
6232 stat->idleThreads = ntohl(stat->idleThreads);
6239 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6240 afs_uint16 remotePort, struct rx_stats * stat,
6241 afs_uint32 * supportedValues)
6243 struct rx_debugIn in;
6244 afs_int32 *lp = (afs_int32 *) stat;
6249 * supportedValues is currently unused, but added to allow future
6250 * versioning of this function.
6253 *supportedValues = 0;
6254 in.type = htonl(RX_DEBUGI_RXSTATS);
6256 memset(stat, 0, sizeof(*stat));
6258 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6259 &in, sizeof(in), stat, sizeof(*stat));
6264 * Do net to host conversion here
6267 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6276 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6277 afs_uint16 remotePort, size_t version_length,
6281 return MakeDebugCall(socket, remoteAddr, remotePort,
6282 RX_PACKET_TYPE_VERSION, a, 1, version,
6287 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6288 afs_uint16 remotePort, afs_int32 * nextConnection,
6289 int allConnections, afs_uint32 debugSupportedValues,
6290 struct rx_debugConn * conn,
6291 afs_uint32 * supportedValues)
6293 struct rx_debugIn in;
6298 * supportedValues is currently unused, but added to allow future
6299 * versioning of this function.
6302 *supportedValues = 0;
6303 if (allConnections) {
6304 in.type = htonl(RX_DEBUGI_GETALLCONN);
6306 in.type = htonl(RX_DEBUGI_GETCONN);
6308 in.index = htonl(*nextConnection);
6309 memset(conn, 0, sizeof(*conn));
6311 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6312 &in, sizeof(in), conn, sizeof(*conn));
6315 *nextConnection += 1;
6318 * Convert old connection format to new structure.
6321 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6322 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6323 #define MOVEvL(a) (conn->a = vL->a)
6325 /* any old or unrecognized version... */
6326 for (i = 0; i < RX_MAXCALLS; i++) {
6327 MOVEvL(callState[i]);
6328 MOVEvL(callMode[i]);
6329 MOVEvL(callFlags[i]);
6330 MOVEvL(callOther[i]);
6332 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6333 MOVEvL(secStats.type);
6334 MOVEvL(secStats.level);
6335 MOVEvL(secStats.flags);
6336 MOVEvL(secStats.expires);
6337 MOVEvL(secStats.packetsReceived);
6338 MOVEvL(secStats.packetsSent);
6339 MOVEvL(secStats.bytesReceived);
6340 MOVEvL(secStats.bytesSent);
6345 * Do net to host conversion here
6347 * I don't convert host or port since we are most likely
6348 * going to want these in NBO.
6350 conn->cid = ntohl(conn->cid);
6351 conn->serial = ntohl(conn->serial);
6352 for (i = 0; i < RX_MAXCALLS; i++) {
6353 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6355 conn->error = ntohl(conn->error);
6356 conn->secStats.flags = ntohl(conn->secStats.flags);
6357 conn->secStats.expires = ntohl(conn->secStats.expires);
6358 conn->secStats.packetsReceived =
6359 ntohl(conn->secStats.packetsReceived);
6360 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6361 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6362 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6363 conn->epoch = ntohl(conn->epoch);
6364 conn->natMTU = ntohl(conn->natMTU);
6371 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6372 afs_uint16 remotePort, afs_int32 * nextPeer,
6373 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6374 afs_uint32 * supportedValues)
6376 struct rx_debugIn in;
6380 * supportedValues is currently unused, but added to allow future
6381 * versioning of this function.
6384 *supportedValues = 0;
6385 in.type = htonl(RX_DEBUGI_GETPEER);
6386 in.index = htonl(*nextPeer);
6387 memset(peer, 0, sizeof(*peer));
6389 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6390 &in, sizeof(in), peer, sizeof(*peer));
6396 * Do net to host conversion here
6398 * I don't convert host or port since we are most likely
6399 * going to want these in NBO.
6401 peer->ifMTU = ntohs(peer->ifMTU);
6402 peer->idleWhen = ntohl(peer->idleWhen);
6403 peer->refCount = ntohs(peer->refCount);
6404 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6405 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6406 peer->rtt = ntohl(peer->rtt);
6407 peer->rtt_dev = ntohl(peer->rtt_dev);
6408 peer->timeout.sec = ntohl(peer->timeout.sec);
6409 peer->timeout.usec = ntohl(peer->timeout.usec);
6410 peer->nSent = ntohl(peer->nSent);
6411 peer->reSends = ntohl(peer->reSends);
6412 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6413 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6414 peer->rateFlag = ntohl(peer->rateFlag);
6415 peer->natMTU = ntohs(peer->natMTU);
6416 peer->maxMTU = ntohs(peer->maxMTU);
6417 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6418 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
6419 peer->MTU = ntohs(peer->MTU);
6420 peer->cwind = ntohs(peer->cwind);
6421 peer->nDgramPackets = ntohs(peer->nDgramPackets);
6422 peer->congestSeq = ntohs(peer->congestSeq);
6423 peer->bytesSent.high = ntohl(peer->bytesSent.high);
6424 peer->bytesSent.low = ntohl(peer->bytesSent.low);
6425 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
6426 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
6431 #endif /* RXDEBUG */
6436 struct rx_serverQueueEntry *np;
6439 register struct rx_call *call;
6440 register struct rx_serverQueueEntry *sq;
6444 if (rxinit_status == 1) {
6446 return; /* Already shutdown. */
6450 #ifndef AFS_PTHREAD_ENV
6451 FD_ZERO(&rx_selectMask);
6452 #endif /* AFS_PTHREAD_ENV */
6453 rxi_dataQuota = RX_MAX_QUOTA;
6454 #ifndef AFS_PTHREAD_ENV
6456 #endif /* AFS_PTHREAD_ENV */
6459 #ifndef AFS_PTHREAD_ENV
6460 #ifndef AFS_USE_GETTIMEOFDAY
6462 #endif /* AFS_USE_GETTIMEOFDAY */
6463 #endif /* AFS_PTHREAD_ENV */
6465 while (!queue_IsEmpty(&rx_freeCallQueue)) {
6466 call = queue_First(&rx_freeCallQueue, rx_call);
6468 rxi_Free(call, sizeof(struct rx_call));
6471 while (!queue_IsEmpty(&rx_idleServerQueue)) {
6472 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
6478 struct rx_peer **peer_ptr, **peer_end;
6479 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6480 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6482 struct rx_peer *peer, *next;
6483 for (peer = *peer_ptr; peer; peer = next) {
6484 rx_interface_stat_p rpc_stat, nrpc_stat;
6487 (&peer->rpcStats, rpc_stat, nrpc_stat,
6488 rx_interface_stat)) {
6489 unsigned int num_funcs;
6492 queue_Remove(&rpc_stat->queue_header);
6493 queue_Remove(&rpc_stat->all_peers);
6494 num_funcs = rpc_stat->stats[0].func_total;
6496 sizeof(rx_interface_stat_t) +
6497 rpc_stat->stats[0].func_total *
6498 sizeof(rx_function_entry_v1_t);
6500 rxi_Free(rpc_stat, space);
6501 MUTEX_ENTER(&rx_rpc_stats);
6502 rxi_rpc_peer_stat_cnt -= num_funcs;
6503 MUTEX_EXIT(&rx_rpc_stats);
6507 MUTEX_ENTER(&rx_stats_mutex);
6508 rx_stats.nPeerStructs--;
6509 MUTEX_EXIT(&rx_stats_mutex);
6513 for (i = 0; i < RX_MAX_SERVICES; i++) {
6515 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
6517 for (i = 0; i < rx_hashTableSize; i++) {
6518 register struct rx_connection *tc, *ntc;
6519 MUTEX_ENTER(&rx_connHashTable_lock);
6520 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
6522 for (j = 0; j < RX_MAXCALLS; j++) {
6524 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
6527 rxi_Free(tc, sizeof(*tc));
6529 MUTEX_EXIT(&rx_connHashTable_lock);
6532 MUTEX_ENTER(&freeSQEList_lock);
6534 while ((np = rx_FreeSQEList)) {
6535 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
6536 MUTEX_DESTROY(&np->lock);
6537 rxi_Free(np, sizeof(*np));
6540 MUTEX_EXIT(&freeSQEList_lock);
6541 MUTEX_DESTROY(&freeSQEList_lock);
6542 MUTEX_DESTROY(&rx_freeCallQueue_lock);
6543 MUTEX_DESTROY(&rx_connHashTable_lock);
6544 MUTEX_DESTROY(&rx_peerHashTable_lock);
6545 MUTEX_DESTROY(&rx_serverPool_lock);
6547 osi_Free(rx_connHashTable,
6548 rx_hashTableSize * sizeof(struct rx_connection *));
6549 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
6551 UNPIN(rx_connHashTable,
6552 rx_hashTableSize * sizeof(struct rx_connection *));
6553 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
6555 rxi_FreeAllPackets();
6557 MUTEX_ENTER(&rx_stats_mutex);
6558 rxi_dataQuota = RX_MAX_QUOTA;
6559 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
6560 MUTEX_EXIT(&rx_stats_mutex);
6566 #ifdef RX_ENABLE_LOCKS
6568 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
6570 if (!MUTEX_ISMINE(lockaddr))
6571 osi_Panic("Lock not held: %s", msg);
6573 #endif /* RX_ENABLE_LOCKS */
6578 * Routines to implement connection specific data.
6582 rx_KeyCreate(rx_destructor_t rtn)
6585 MUTEX_ENTER(&rxi_keyCreate_lock);
6586 key = rxi_keyCreate_counter++;
6587 rxi_keyCreate_destructor = (rx_destructor_t *)
6588 realloc((void *)rxi_keyCreate_destructor,
6589 (key + 1) * sizeof(rx_destructor_t));
6590 rxi_keyCreate_destructor[key] = rtn;
6591 MUTEX_EXIT(&rxi_keyCreate_lock);
6596 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
6599 MUTEX_ENTER(&conn->conn_data_lock);
6600 if (!conn->specific) {
6601 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
6602 for (i = 0; i < key; i++)
6603 conn->specific[i] = NULL;
6604 conn->nSpecific = key + 1;
6605 conn->specific[key] = ptr;
6606 } else if (key >= conn->nSpecific) {
6607 conn->specific = (void **)
6608 realloc(conn->specific, (key + 1) * sizeof(void *));
6609 for (i = conn->nSpecific; i < key; i++)
6610 conn->specific[i] = NULL;
6611 conn->nSpecific = key + 1;
6612 conn->specific[key] = ptr;
6614 if (conn->specific[key] && rxi_keyCreate_destructor[key])
6615 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
6616 conn->specific[key] = ptr;
6618 MUTEX_EXIT(&conn->conn_data_lock);
6622 rx_GetSpecific(struct rx_connection *conn, int key)
6625 MUTEX_ENTER(&conn->conn_data_lock);
6626 if (key >= conn->nSpecific)
6629 ptr = conn->specific[key];
6630 MUTEX_EXIT(&conn->conn_data_lock);
6634 #endif /* !KERNEL */
6637 * processStats is a queue used to store the statistics for the local
6638 * process. Its contents are similar to the contents of the rpcStats
6639 * queue on a rx_peer structure, but the actual data stored within
6640 * this queue contains totals across the lifetime of the process (assuming
6641 * the stats have not been reset) - unlike the per peer structures
6642 * which can come and go based upon the peer lifetime.
6645 static struct rx_queue processStats = { &processStats, &processStats };
6648 * peerStats is a queue used to store the statistics for all peer structs.
6649 * Its contents are the union of all the peer rpcStats queues.
6652 static struct rx_queue peerStats = { &peerStats, &peerStats };
6655 * rxi_monitor_processStats is used to turn process wide stat collection
6659 static int rxi_monitor_processStats = 0;
6662 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
6665 static int rxi_monitor_peerStats = 0;
6668 * rxi_AddRpcStat - given all of the information for a particular rpc
6669 * call, create (if needed) and update the stat totals for the rpc.
6673 * IN stats - the queue of stats that will be updated with the new value
6675 * IN rxInterface - a unique number that identifies the rpc interface
6677 * IN currentFunc - the index of the function being invoked
6679 * IN totalFunc - the total number of functions in this interface
6681 * IN queueTime - the amount of time this function waited for a thread
6683 * IN execTime - the amount of time this function invocation took to execute
6685 * IN bytesSent - the number bytes sent by this invocation
6687 * IN bytesRcvd - the number bytes received by this invocation
6689 * IN isServer - if true, this invocation was made to a server
6691 * IN remoteHost - the ip address of the remote host
6693 * IN remotePort - the port of the remote host
6695 * IN addToPeerList - if != 0, add newly created stat to the global peer list
6697 * INOUT counter - if a new stats structure is allocated, the counter will
6698 * be updated with the new number of allocated stat structures
6706 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
6707 afs_uint32 currentFunc, afs_uint32 totalFunc,
6708 struct clock *queueTime, struct clock *execTime,
6709 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
6710 afs_uint32 remoteHost, afs_uint32 remotePort,
6711 int addToPeerList, unsigned int *counter)
6714 rx_interface_stat_p rpc_stat, nrpc_stat;
6717 * See if there's already a structure for this interface
6720 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
6721 if ((rpc_stat->stats[0].interfaceId == rxInterface)
6722 && (rpc_stat->stats[0].remote_is_server == isServer))
6727 * Didn't find a match so allocate a new structure and add it to the
6731 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
6732 || (rpc_stat->stats[0].interfaceId != rxInterface)
6733 || (rpc_stat->stats[0].remote_is_server != isServer)) {
6738 sizeof(rx_interface_stat_t) +
6739 totalFunc * sizeof(rx_function_entry_v1_t);
6741 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
6742 if (rpc_stat == NULL) {
6746 *counter += totalFunc;
6747 for (i = 0; i < totalFunc; i++) {
6748 rpc_stat->stats[i].remote_peer = remoteHost;
6749 rpc_stat->stats[i].remote_port = remotePort;
6750 rpc_stat->stats[i].remote_is_server = isServer;
6751 rpc_stat->stats[i].interfaceId = rxInterface;
6752 rpc_stat->stats[i].func_total = totalFunc;
6753 rpc_stat->stats[i].func_index = i;
6754 hzero(rpc_stat->stats[i].invocations);
6755 hzero(rpc_stat->stats[i].bytes_sent);
6756 hzero(rpc_stat->stats[i].bytes_rcvd);
6757 rpc_stat->stats[i].queue_time_sum.sec = 0;
6758 rpc_stat->stats[i].queue_time_sum.usec = 0;
6759 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
6760 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
6761 rpc_stat->stats[i].queue_time_min.sec = 9999999;
6762 rpc_stat->stats[i].queue_time_min.usec = 9999999;
6763 rpc_stat->stats[i].queue_time_max.sec = 0;
6764 rpc_stat->stats[i].queue_time_max.usec = 0;
6765 rpc_stat->stats[i].execution_time_sum.sec = 0;
6766 rpc_stat->stats[i].execution_time_sum.usec = 0;
6767 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
6768 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
6769 rpc_stat->stats[i].execution_time_min.sec = 9999999;
6770 rpc_stat->stats[i].execution_time_min.usec = 9999999;
6771 rpc_stat->stats[i].execution_time_max.sec = 0;
6772 rpc_stat->stats[i].execution_time_max.usec = 0;
6774 queue_Prepend(stats, rpc_stat);
6775 if (addToPeerList) {
6776 queue_Prepend(&peerStats, &rpc_stat->all_peers);
6781 * Increment the stats for this function
6784 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
6785 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
6786 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
6787 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
6788 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
6789 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
6790 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
6792 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
6793 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
6795 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
6796 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
6798 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
6799 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
6801 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
6802 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
6810 * rx_IncrementTimeAndCount - increment the times and count for a particular
6815 * IN peer - the peer who invoked the rpc
6817 * IN rxInterface - a unique number that identifies the rpc interface
6819 * IN currentFunc - the index of the function being invoked
6821 * IN totalFunc - the total number of functions in this interface
6823 * IN queueTime - the amount of time this function waited for a thread
6825 * IN execTime - the amount of time this function invocation took to execute
6827 * IN bytesSent - the number bytes sent by this invocation
6829 * IN bytesRcvd - the number bytes received by this invocation
6831 * IN isServer - if true, this invocation was made to a server
6839 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
6840 afs_uint32 currentFunc, afs_uint32 totalFunc,
6841 struct clock *queueTime, struct clock *execTime,
6842 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
6846 MUTEX_ENTER(&rx_rpc_stats);
6847 MUTEX_ENTER(&peer->peer_lock);
6849 if (rxi_monitor_peerStats) {
6850 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
6851 queueTime, execTime, bytesSent, bytesRcvd, isServer,
6852 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
6855 if (rxi_monitor_processStats) {
6856 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
6857 queueTime, execTime, bytesSent, bytesRcvd, isServer,
6858 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
6861 MUTEX_EXIT(&peer->peer_lock);
6862 MUTEX_EXIT(&rx_rpc_stats);
6867 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
6871 * IN callerVersion - the rpc stat version of the caller.
6873 * IN count - the number of entries to marshall.
6875 * IN stats - pointer to stats to be marshalled.
6877 * OUT ptr - Where to store the marshalled data.
6884 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
6885 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
6891 * We only support the first version
6893 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
6894 *(ptr++) = stats->remote_peer;
6895 *(ptr++) = stats->remote_port;
6896 *(ptr++) = stats->remote_is_server;
6897 *(ptr++) = stats->interfaceId;
6898 *(ptr++) = stats->func_total;
6899 *(ptr++) = stats->func_index;
6900 *(ptr++) = hgethi(stats->invocations);
6901 *(ptr++) = hgetlo(stats->invocations);
6902 *(ptr++) = hgethi(stats->bytes_sent);
6903 *(ptr++) = hgetlo(stats->bytes_sent);
6904 *(ptr++) = hgethi(stats->bytes_rcvd);
6905 *(ptr++) = hgetlo(stats->bytes_rcvd);
6906 *(ptr++) = stats->queue_time_sum.sec;
6907 *(ptr++) = stats->queue_time_sum.usec;
6908 *(ptr++) = stats->queue_time_sum_sqr.sec;
6909 *(ptr++) = stats->queue_time_sum_sqr.usec;
6910 *(ptr++) = stats->queue_time_min.sec;
6911 *(ptr++) = stats->queue_time_min.usec;
6912 *(ptr++) = stats->queue_time_max.sec;
6913 *(ptr++) = stats->queue_time_max.usec;
6914 *(ptr++) = stats->execution_time_sum.sec;
6915 *(ptr++) = stats->execution_time_sum.usec;
6916 *(ptr++) = stats->execution_time_sum_sqr.sec;
6917 *(ptr++) = stats->execution_time_sum_sqr.usec;
6918 *(ptr++) = stats->execution_time_min.sec;
6919 *(ptr++) = stats->execution_time_min.usec;
6920 *(ptr++) = stats->execution_time_max.sec;
6921 *(ptr++) = stats->execution_time_max.usec;
6927 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
6932 * IN callerVersion - the rpc stat version of the caller
6934 * OUT myVersion - the rpc stat version of this function
6936 * OUT clock_sec - local time seconds
6938 * OUT clock_usec - local time microseconds
6940 * OUT allocSize - the number of bytes allocated to contain stats
6942 * OUT statCount - the number stats retrieved from this process.
6944 * OUT stats - the actual stats retrieved from this process.
6948 * Returns void. If successful, stats will != NULL.
6952 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
6953 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
6954 size_t * allocSize, afs_uint32 * statCount,
6955 afs_uint32 ** stats)
6965 *myVersion = RX_STATS_RETRIEVAL_VERSION;
6968 * Check to see if stats are enabled
6971 MUTEX_ENTER(&rx_rpc_stats);
6972 if (!rxi_monitor_processStats) {
6973 MUTEX_EXIT(&rx_rpc_stats);
6977 clock_GetTime(&now);
6978 *clock_sec = now.sec;
6979 *clock_usec = now.usec;
6982 * Allocate the space based upon the caller version
6984 * If the client is at an older version than we are,
6985 * we return the statistic data in the older data format, but
6986 * we still return our version number so the client knows we
6987 * are maintaining more data than it can retrieve.
6990 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
6991 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
6992 *statCount = rxi_rpc_process_stat_cnt;
6995 * This can't happen yet, but in the future version changes
6996 * can be handled by adding additional code here
7000 if (space > (size_t) 0) {
7002 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7005 rx_interface_stat_p rpc_stat, nrpc_stat;
7009 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7011 * Copy the data based upon the caller version
7013 rx_MarshallProcessRPCStats(callerVersion,
7014 rpc_stat->stats[0].func_total,
7015 rpc_stat->stats, &ptr);
7021 MUTEX_EXIT(&rx_rpc_stats);
7026 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7030 * IN callerVersion - the rpc stat version of the caller
7032 * OUT myVersion - the rpc stat version of this function
7034 * OUT clock_sec - local time seconds
7036 * OUT clock_usec - local time microseconds
7038 * OUT allocSize - the number of bytes allocated to contain stats
7040 * OUT statCount - the number of stats retrieved from the individual
7043 * OUT stats - the actual stats retrieved from the individual peer structures.
7047 * Returns void. If successful, stats will != NULL.
7051 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7052 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7053 size_t * allocSize, afs_uint32 * statCount,
7054 afs_uint32 ** stats)
7064 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7067 * Check to see if stats are enabled
7070 MUTEX_ENTER(&rx_rpc_stats);
7071 if (!rxi_monitor_peerStats) {
7072 MUTEX_EXIT(&rx_rpc_stats);
7076 clock_GetTime(&now);
7077 *clock_sec = now.sec;
7078 *clock_usec = now.usec;
7081 * Allocate the space based upon the caller version
7083 * If the client is at an older version than we are,
7084 * we return the statistic data in the older data format, but
7085 * we still return our version number so the client knows we
7086 * are maintaining more data than it can retrieve.
7089 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7090 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7091 *statCount = rxi_rpc_peer_stat_cnt;
7094 * This can't happen yet, but in the future version changes
7095 * can be handled by adding additional code here
7099 if (space > (size_t) 0) {
7101 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7104 rx_interface_stat_p rpc_stat, nrpc_stat;
7108 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7110 * We have to fix the offset of rpc_stat since we are
7111 * keeping this structure on two rx_queues. The rx_queue
7112 * package assumes that the rx_queue member is the first
7113 * member of the structure. That is, rx_queue assumes that
7114 * any one item is only on one queue at a time. We are
7115 * breaking that assumption and so we have to do a little
7116 * math to fix our pointers.
7119 fix_offset = (char *)rpc_stat;
7120 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7121 rpc_stat = (rx_interface_stat_p) fix_offset;
7124 * Copy the data based upon the caller version
7126 rx_MarshallProcessRPCStats(callerVersion,
7127 rpc_stat->stats[0].func_total,
7128 rpc_stat->stats, &ptr);
7134 MUTEX_EXIT(&rx_rpc_stats);
7139 * rx_FreeRPCStats - free memory allocated by
7140 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7144 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7145 * rx_RetrievePeerRPCStats
7147 * IN allocSize - the number of bytes in stats.
7155 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7157 rxi_Free(stats, allocSize);
7161 * rx_queryProcessRPCStats - see if process rpc stat collection is
7162 * currently enabled.
7168 * Returns 0 if stats are not enabled != 0 otherwise
7172 rx_queryProcessRPCStats(void)
7175 MUTEX_ENTER(&rx_rpc_stats);
7176 rc = rxi_monitor_processStats;
7177 MUTEX_EXIT(&rx_rpc_stats);
7182 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7188 * Returns 0 if stats are not enabled != 0 otherwise
7192 rx_queryPeerRPCStats(void)
7195 MUTEX_ENTER(&rx_rpc_stats);
7196 rc = rxi_monitor_peerStats;
7197 MUTEX_EXIT(&rx_rpc_stats);
7202 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7212 rx_enableProcessRPCStats(void)
7214 MUTEX_ENTER(&rx_rpc_stats);
7215 rx_enable_stats = 1;
7216 rxi_monitor_processStats = 1;
7217 MUTEX_EXIT(&rx_rpc_stats);
7221 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7231 rx_enablePeerRPCStats(void)
7233 MUTEX_ENTER(&rx_rpc_stats);
7234 rx_enable_stats = 1;
7235 rxi_monitor_peerStats = 1;
7236 MUTEX_EXIT(&rx_rpc_stats);
7240 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7250 rx_disableProcessRPCStats(void)
7252 rx_interface_stat_p rpc_stat, nrpc_stat;
7255 MUTEX_ENTER(&rx_rpc_stats);
7258 * Turn off process statistics and if peer stats is also off, turn
7262 rxi_monitor_processStats = 0;
7263 if (rxi_monitor_peerStats == 0) {
7264 rx_enable_stats = 0;
7267 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7268 unsigned int num_funcs = 0;
7271 queue_Remove(rpc_stat);
7272 num_funcs = rpc_stat->stats[0].func_total;
7274 sizeof(rx_interface_stat_t) +
7275 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7277 rxi_Free(rpc_stat, space);
7278 rxi_rpc_process_stat_cnt -= num_funcs;
7280 MUTEX_EXIT(&rx_rpc_stats);
7284 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7294 rx_disablePeerRPCStats(void)
7296 struct rx_peer **peer_ptr, **peer_end;
7299 MUTEX_ENTER(&rx_rpc_stats);
7302 * Turn off peer statistics and if process stats is also off, turn
7306 rxi_monitor_peerStats = 0;
7307 if (rxi_monitor_processStats == 0) {
7308 rx_enable_stats = 0;
7311 MUTEX_ENTER(&rx_peerHashTable_lock);
7312 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7313 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7315 struct rx_peer *peer, *next, *prev;
7316 for (prev = peer = *peer_ptr; peer; peer = next) {
7318 code = MUTEX_TRYENTER(&peer->peer_lock);
7320 rx_interface_stat_p rpc_stat, nrpc_stat;
7323 (&peer->rpcStats, rpc_stat, nrpc_stat,
7324 rx_interface_stat)) {
7325 unsigned int num_funcs = 0;
7328 queue_Remove(&rpc_stat->queue_header);
7329 queue_Remove(&rpc_stat->all_peers);
7330 num_funcs = rpc_stat->stats[0].func_total;
7332 sizeof(rx_interface_stat_t) +
7333 rpc_stat->stats[0].func_total *
7334 sizeof(rx_function_entry_v1_t);
7336 rxi_Free(rpc_stat, space);
7337 rxi_rpc_peer_stat_cnt -= num_funcs;
7339 MUTEX_EXIT(&peer->peer_lock);
7340 if (prev == *peer_ptr) {
7350 MUTEX_EXIT(&rx_peerHashTable_lock);
7351 MUTEX_EXIT(&rx_rpc_stats);
7355 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7360 * IN clearFlag - flag indicating which stats to clear
7368 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7370 rx_interface_stat_p rpc_stat, nrpc_stat;
7372 MUTEX_ENTER(&rx_rpc_stats);
7374 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7375 unsigned int num_funcs = 0, i;
7376 num_funcs = rpc_stat->stats[0].func_total;
7377 for (i = 0; i < num_funcs; i++) {
7378 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7379 hzero(rpc_stat->stats[i].invocations);
7381 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7382 hzero(rpc_stat->stats[i].bytes_sent);
7384 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7385 hzero(rpc_stat->stats[i].bytes_rcvd);
7387 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7388 rpc_stat->stats[i].queue_time_sum.sec = 0;
7389 rpc_stat->stats[i].queue_time_sum.usec = 0;
7391 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7392 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7393 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7395 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7396 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7397 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7399 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7400 rpc_stat->stats[i].queue_time_max.sec = 0;
7401 rpc_stat->stats[i].queue_time_max.usec = 0;
7403 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7404 rpc_stat->stats[i].execution_time_sum.sec = 0;
7405 rpc_stat->stats[i].execution_time_sum.usec = 0;
7407 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7408 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7409 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7411 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7412 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7413 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7415 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7416 rpc_stat->stats[i].execution_time_max.sec = 0;
7417 rpc_stat->stats[i].execution_time_max.usec = 0;
7422 MUTEX_EXIT(&rx_rpc_stats);
7426 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
7431 * IN clearFlag - flag indicating which stats to clear
7439 rx_clearPeerRPCStats(afs_uint32 clearFlag)
7441 rx_interface_stat_p rpc_stat, nrpc_stat;
7443 MUTEX_ENTER(&rx_rpc_stats);
7445 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7446 unsigned int num_funcs = 0, i;
7449 * We have to fix the offset of rpc_stat since we are
7450 * keeping this structure on two rx_queues. The rx_queue
7451 * package assumes that the rx_queue member is the first
7452 * member of the structure. That is, rx_queue assumes that
7453 * any one item is only on one queue at a time. We are
7454 * breaking that assumption and so we have to do a little
7455 * math to fix our pointers.
7458 fix_offset = (char *)rpc_stat;
7459 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7460 rpc_stat = (rx_interface_stat_p) fix_offset;
7462 num_funcs = rpc_stat->stats[0].func_total;
7463 for (i = 0; i < num_funcs; i++) {
7464 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7465 hzero(rpc_stat->stats[i].invocations);
7467 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7468 hzero(rpc_stat->stats[i].bytes_sent);
7470 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7471 hzero(rpc_stat->stats[i].bytes_rcvd);
7473 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7474 rpc_stat->stats[i].queue_time_sum.sec = 0;
7475 rpc_stat->stats[i].queue_time_sum.usec = 0;
7477 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7478 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7479 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7481 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7482 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7483 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7485 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7486 rpc_stat->stats[i].queue_time_max.sec = 0;
7487 rpc_stat->stats[i].queue_time_max.usec = 0;
7489 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7490 rpc_stat->stats[i].execution_time_sum.sec = 0;
7491 rpc_stat->stats[i].execution_time_sum.usec = 0;
7493 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7494 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7495 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7497 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7498 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7499 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7501 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7502 rpc_stat->stats[i].execution_time_max.sec = 0;
7503 rpc_stat->stats[i].execution_time_max.usec = 0;
7508 MUTEX_EXIT(&rx_rpc_stats);
7512 * rxi_rxstat_userok points to a routine that returns 1 if the caller
7513 * is authorized to enable/disable/clear RX statistics.
7515 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
7518 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
7520 rxi_rxstat_userok = proc;
7524 rx_RxStatUserOk(struct rx_call *call)
7526 if (!rxi_rxstat_userok)
7528 return rxi_rxstat_userok(call);