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"
37 #include "inet/common.h"
39 #include "inet/ip_ire.h"
41 #include "afs/afs_args.h"
42 #include "afs/afs_osi.h"
43 #ifdef RX_KERNEL_TRACE
44 #include "rx_kcommon.h"
46 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
50 #undef RXDEBUG /* turn off debugging */
52 #if defined(AFS_SGI_ENV)
53 #include "sys/debug.h"
62 #endif /* AFS_OSF_ENV */
64 #include "afs/sysincludes.h"
65 #include "afsincludes.h"
68 #include "rx_kmutex.h"
69 #include "rx_kernel.h"
73 #include "rx_globals.h"
75 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
76 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
77 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
79 extern afs_int32 afs_termState;
81 #include "sys/lockl.h"
82 #include "sys/lock_def.h"
83 #endif /* AFS_AIX41_ENV */
84 # include "rxgen_consts.h"
86 # include <sys/types.h>
92 # include <afs/afsutil.h>
93 # include <WINNT\afsreg.h>
95 # include <sys/socket.h>
96 # include <sys/file.h>
98 # include <sys/stat.h>
99 # include <netinet/in.h>
100 # 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 des_init_mutex;
157 extern pthread_mutex_t des_random_mutex;
158 extern pthread_mutex_t rx_clock_mutex;
159 extern pthread_mutex_t rxi_connCacheMutex;
160 extern pthread_mutex_t rx_event_mutex;
161 extern pthread_mutex_t osi_malloc_mutex;
162 extern pthread_mutex_t event_handler_mutex;
163 extern pthread_mutex_t listener_mutex;
164 extern pthread_mutex_t rx_if_init_mutex;
165 extern pthread_mutex_t rx_if_mutex;
166 extern pthread_mutex_t rxkad_client_uid_mutex;
167 extern pthread_mutex_t rxkad_random_mutex;
169 extern pthread_cond_t rx_event_handler_cond;
170 extern pthread_cond_t rx_listener_cond;
172 static pthread_mutex_t epoch_mutex;
173 static pthread_mutex_t rx_init_mutex;
174 static pthread_mutex_t rx_debug_mutex;
175 static pthread_mutex_t rx_rpc_stats;
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(&rx_debug_mutex, (const pthread_mutexattr_t *)0)
213 assert(pthread_cond_init
214 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
215 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
217 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
218 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
220 rxkad_global_stats_init();
222 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
224 #ifdef RX_ENABLE_LOCKS
227 #endif /* RX_LOCKS_DB */
228 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
229 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
231 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
233 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
235 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
237 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
238 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
239 #endif /* RX_ENABLE_LOCKS */
242 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
243 #define INIT_PTHREAD_LOCKS \
244 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
246 * The rx_stats_mutex mutex protects the following global variables:
251 * rxi_lowConnRefCount
252 * rxi_lowPeerRefCount
261 #define INIT_PTHREAD_LOCKS
265 /* Variables for handling the minProcs implementation. availProcs gives the
266 * number of threads available in the pool at this moment (not counting dudes
267 * executing right now). totalMin gives the total number of procs required
268 * for handling all minProcs requests. minDeficit is a dynamic variable
269 * tracking the # of procs required to satisfy all of the remaining minProcs
271 * For fine grain locking to work, the quota check and the reservation of
272 * a server thread has to come while rxi_availProcs and rxi_minDeficit
273 * are locked. To this end, the code has been modified under #ifdef
274 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
275 * same time. A new function, ReturnToServerPool() returns the allocation.
277 * A call can be on several queue's (but only one at a time). When
278 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
279 * that no one else is touching the queue. To this end, we store the address
280 * of the queue lock in the call structure (under the call lock) when we
281 * put the call on a queue, and we clear the call_queue_lock when the
282 * call is removed from a queue (once the call lock has been obtained).
283 * This allows rxi_ResetCall to safely synchronize with others wishing
284 * to manipulate the queue.
287 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
288 static afs_kmutex_t rx_rpc_stats;
289 void rxi_StartUnlocked();
292 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
293 ** pretty good that the next packet coming in is from the same connection
294 ** as the last packet, since we're send multiple packets in a transmit window.
296 struct rx_connection *rxLastConn = 0;
298 #ifdef RX_ENABLE_LOCKS
299 /* The locking hierarchy for rx fine grain locking is composed of these
302 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
303 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
304 * call->lock - locks call data fields.
305 * These are independent of each other:
306 * rx_freeCallQueue_lock
311 * serverQueueEntry->lock
313 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
314 * peer->lock - locks peer data fields.
315 * conn_data_lock - that more than one thread is not updating a conn data
316 * field at the same time.
324 * Do we need a lock to protect the peer field in the conn structure?
325 * conn->peer was previously a constant for all intents and so has no
326 * lock protecting this field. The multihomed client delta introduced
327 * a RX code change : change the peer field in the connection structure
328 * to that remote inetrface from which the last packet for this
329 * connection was sent out. This may become an issue if further changes
332 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
333 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
335 /* rxdb_fileID is used to identify the lock location, along with line#. */
336 static int rxdb_fileID = RXDB_FILE_RX;
337 #endif /* RX_LOCKS_DB */
338 #else /* RX_ENABLE_LOCKS */
339 #define SET_CALL_QUEUE_LOCK(C, L)
340 #define CLEAR_CALL_QUEUE_LOCK(C)
341 #endif /* RX_ENABLE_LOCKS */
342 struct rx_serverQueueEntry *rx_waitForPacket = 0;
343 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
345 /* ------------Exported Interfaces------------- */
347 /* This function allows rxkad to set the epoch to a suitably random number
348 * which rx_NewConnection will use in the future. The principle purpose is to
349 * get rxnull connections to use the same epoch as the rxkad connections do, at
350 * least once the first rxkad connection is established. This is important now
351 * that the host/port addresses aren't used in FindConnection: the uniqueness
352 * of epoch/cid matters and the start time won't do. */
354 #ifdef AFS_PTHREAD_ENV
356 * This mutex protects the following global variables:
360 #define LOCK_EPOCH assert(pthread_mutex_lock(&epoch_mutex)==0)
361 #define UNLOCK_EPOCH assert(pthread_mutex_unlock(&epoch_mutex)==0)
365 #endif /* AFS_PTHREAD_ENV */
368 rx_SetEpoch(afs_uint32 epoch)
375 /* Initialize rx. A port number may be mentioned, in which case this
376 * becomes the default port number for any service installed later.
377 * If 0 is provided for the port number, a random port will be chosen
378 * by the kernel. Whether this will ever overlap anything in
379 * /etc/services is anybody's guess... Returns 0 on success, -1 on
384 int rxinit_status = 1;
385 #ifdef AFS_PTHREAD_ENV
387 * This mutex protects the following global variables:
391 #define LOCK_RX_INIT assert(pthread_mutex_lock(&rx_init_mutex)==0)
392 #define UNLOCK_RX_INIT assert(pthread_mutex_unlock(&rx_init_mutex)==0)
395 #define UNLOCK_RX_INIT
399 rx_InitHost(u_int host, u_int port)
406 char *htable, *ptable;
413 if (rxinit_status == 0) {
414 tmp_status = rxinit_status;
416 return tmp_status; /* Already started; return previous error code. */
422 if (afs_winsockInit() < 0)
428 * Initialize anything necessary to provide a non-premptive threading
431 rxi_InitializeThreadSupport();
434 /* Allocate and initialize a socket for client and perhaps server
437 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
438 if (rx_socket == OSI_NULLSOCKET) {
442 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
445 #endif /* RX_LOCKS_DB */
446 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
447 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
448 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
449 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
450 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
452 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
454 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
456 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
458 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
459 #if defined(AFS_HPUX110_ENV)
461 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
462 #endif /* AFS_HPUX110_ENV */
463 #endif /* RX_ENABLE_LOCKS && KERNEL */
466 rx_connDeadTime = 12;
467 rx_tranquil = 0; /* reset flag */
468 memset((char *)&rx_stats, 0, sizeof(struct rx_stats));
470 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
471 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
472 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
473 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
474 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
475 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
477 /* Malloc up a bunch of packets & buffers */
479 queue_Init(&rx_freePacketQueue);
480 rxi_NeedMorePackets = FALSE;
481 #ifdef RX_ENABLE_TSFPQ
482 rx_nPackets = 0; /* in TSFPQ version, rx_nPackets is managed by rxi_MorePackets* */
483 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
484 #else /* RX_ENABLE_TSFPQ */
485 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
486 rxi_MorePackets(rx_nPackets);
487 #endif /* RX_ENABLE_TSFPQ */
494 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
495 tv.tv_sec = clock_now.sec;
496 tv.tv_usec = clock_now.usec;
497 srand((unsigned int)tv.tv_usec);
504 #if defined(KERNEL) && !defined(UKERNEL)
505 /* Really, this should never happen in a real kernel */
508 struct sockaddr_in addr;
509 int addrlen = sizeof(addr);
510 if (getsockname((int)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
514 rx_port = addr.sin_port;
517 rx_stats.minRtt.sec = 9999999;
519 rx_SetEpoch(tv.tv_sec | 0x80000000);
521 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
522 * will provide a randomer value. */
524 MUTEX_ENTER(&rx_stats_mutex);
525 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
526 MUTEX_EXIT(&rx_stats_mutex);
527 /* *Slightly* random start time for the cid. This is just to help
528 * out with the hashing function at the peer */
529 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
530 rx_connHashTable = (struct rx_connection **)htable;
531 rx_peerHashTable = (struct rx_peer **)ptable;
533 rx_lastAckDelay.sec = 0;
534 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
535 rx_hardAckDelay.sec = 0;
536 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
537 rx_softAckDelay.sec = 0;
538 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
540 rxevent_Init(20, rxi_ReScheduleEvents);
542 /* Initialize various global queues */
543 queue_Init(&rx_idleServerQueue);
544 queue_Init(&rx_incomingCallQueue);
545 queue_Init(&rx_freeCallQueue);
547 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
548 /* Initialize our list of usable IP addresses. */
552 /* Start listener process (exact function is dependent on the
553 * implementation environment--kernel or user space) */
557 tmp_status = rxinit_status = 0;
565 return rx_InitHost(htonl(INADDR_ANY), port);
568 /* called with unincremented nRequestsRunning to see if it is OK to start
569 * a new thread in this service. Could be "no" for two reasons: over the
570 * max quota, or would prevent others from reaching their min quota.
572 #ifdef RX_ENABLE_LOCKS
573 /* This verion of QuotaOK reserves quota if it's ok while the
574 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
577 QuotaOK(register struct rx_service *aservice)
579 /* check if over max quota */
580 if (aservice->nRequestsRunning >= aservice->maxProcs) {
584 /* under min quota, we're OK */
585 /* otherwise, can use only if there are enough to allow everyone
586 * to go to their min quota after this guy starts.
588 MUTEX_ENTER(&rx_stats_mutex);
589 if ((aservice->nRequestsRunning < aservice->minProcs)
590 || (rxi_availProcs > rxi_minDeficit)) {
591 aservice->nRequestsRunning++;
592 /* just started call in minProcs pool, need fewer to maintain
594 if (aservice->nRequestsRunning <= aservice->minProcs)
597 MUTEX_EXIT(&rx_stats_mutex);
600 MUTEX_EXIT(&rx_stats_mutex);
606 ReturnToServerPool(register struct rx_service *aservice)
608 aservice->nRequestsRunning--;
609 MUTEX_ENTER(&rx_stats_mutex);
610 if (aservice->nRequestsRunning < aservice->minProcs)
613 MUTEX_EXIT(&rx_stats_mutex);
616 #else /* RX_ENABLE_LOCKS */
618 QuotaOK(register struct rx_service *aservice)
621 /* under min quota, we're OK */
622 if (aservice->nRequestsRunning < aservice->minProcs)
625 /* check if over max quota */
626 if (aservice->nRequestsRunning >= aservice->maxProcs)
629 /* otherwise, can use only if there are enough to allow everyone
630 * to go to their min quota after this guy starts.
632 if (rxi_availProcs > rxi_minDeficit)
636 #endif /* RX_ENABLE_LOCKS */
639 /* Called by rx_StartServer to start up lwp's to service calls.
640 NExistingProcs gives the number of procs already existing, and which
641 therefore needn't be created. */
643 rxi_StartServerProcs(int nExistingProcs)
645 register struct rx_service *service;
650 /* For each service, reserve N processes, where N is the "minimum"
651 * number of processes that MUST be able to execute a request in parallel,
652 * at any time, for that process. Also compute the maximum difference
653 * between any service's maximum number of processes that can run
654 * (i.e. the maximum number that ever will be run, and a guarantee
655 * that this number will run if other services aren't running), and its
656 * minimum number. The result is the extra number of processes that
657 * we need in order to provide the latter guarantee */
658 for (i = 0; i < RX_MAX_SERVICES; i++) {
660 service = rx_services[i];
661 if (service == (struct rx_service *)0)
663 nProcs += service->minProcs;
664 diff = service->maxProcs - service->minProcs;
668 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
669 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
670 for (i = 0; i < nProcs; i++) {
671 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
677 /* This routine is only required on Windows */
679 rx_StartClientThread(void)
681 #ifdef AFS_PTHREAD_ENV
683 pid = pthread_self();
684 #endif /* AFS_PTHREAD_ENV */
686 #endif /* AFS_NT40_ENV */
688 /* This routine must be called if any services are exported. If the
689 * donateMe flag is set, the calling process is donated to the server
692 rx_StartServer(int donateMe)
694 register struct rx_service *service;
700 /* Start server processes, if necessary (exact function is dependent
701 * on the implementation environment--kernel or user space). DonateMe
702 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
703 * case, one less new proc will be created rx_StartServerProcs.
705 rxi_StartServerProcs(donateMe);
707 /* count up the # of threads in minProcs, and add set the min deficit to
708 * be that value, too.
710 for (i = 0; i < RX_MAX_SERVICES; i++) {
711 service = rx_services[i];
712 if (service == (struct rx_service *)0)
714 MUTEX_ENTER(&rx_stats_mutex);
715 rxi_totalMin += service->minProcs;
716 /* below works even if a thread is running, since minDeficit would
717 * still have been decremented and later re-incremented.
719 rxi_minDeficit += service->minProcs;
720 MUTEX_EXIT(&rx_stats_mutex);
723 /* Turn on reaping of idle server connections */
724 rxi_ReapConnections();
733 #ifdef AFS_PTHREAD_ENV
735 pid = (pid_t) pthread_self();
736 #else /* AFS_PTHREAD_ENV */
738 LWP_CurrentProcess(&pid);
739 #endif /* AFS_PTHREAD_ENV */
741 sprintf(name, "srv_%d", ++nProcs);
743 (*registerProgram) (pid, name);
745 #endif /* AFS_NT40_ENV */
746 rx_ServerProc(NULL); /* Never returns */
748 #ifdef RX_ENABLE_TSFPQ
749 /* no use leaving packets around in this thread's local queue if
750 * it isn't getting donated to the server thread pool.
752 rxi_FlushLocalPacketsTSFPQ();
753 #endif /* RX_ENABLE_TSFPQ */
757 /* Create a new client connection to the specified service, using the
758 * specified security object to implement the security model for this
760 struct rx_connection *
761 rx_NewConnection(register afs_uint32 shost, u_short sport, u_short sservice,
762 register struct rx_securityClass *securityObject,
763 int serviceSecurityIndex)
766 afs_int32 cid, cix, nclones;
767 register struct rx_connection *conn, *tconn, *ptconn;
772 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n", ntohl(shost), ntohs(sport), sservice, securityObject, serviceSecurityIndex));
775 nclones = rx_max_clones_per_connection;
777 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
778 * the case of kmem_alloc? */
781 MUTEX_ENTER(&rx_connHashTable_lock);
783 /* send in the clones */
784 for(cix = 0; cix <= nclones; ++cix) {
787 tconn = rxi_AllocConnection();
788 tconn->type = RX_CLIENT_CONNECTION;
789 tconn->epoch = rx_epoch;
790 tconn->peer = rxi_FindPeer(shost, sport, 0, 1);
791 tconn->serviceId = sservice;
792 tconn->securityObject = securityObject;
793 tconn->securityData = (void *) 0;
794 tconn->securityIndex = serviceSecurityIndex;
795 tconn->ackRate = RX_FAST_ACK_RATE;
796 tconn->nSpecific = 0;
797 tconn->specific = NULL;
798 tconn->challengeEvent = NULL;
799 tconn->delayedAbortEvent = NULL;
800 tconn->abortCount = 0;
802 for (i = 0; i < RX_MAXCALLS; i++) {
803 tconn->twind[i] = rx_initSendWindow;
804 tconn->rwind[i] = rx_initReceiveWindow;
807 tconn->next_clone = 0;
808 tconn->nclones = nclones;
809 rx_SetConnDeadTime(tconn, rx_connDeadTime);
814 tconn->flags |= RX_CLONED_CONNECTION;
815 tconn->parent = conn;
816 ptconn->next_clone = tconn;
819 /* generic connection setup */
820 #ifdef RX_ENABLE_LOCKS
821 MUTEX_INIT(&tconn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
822 MUTEX_INIT(&tconn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
823 CV_INIT(&tconn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
825 cid = (rx_nextCid += RX_MAXCALLS);
827 RXS_NewConnection(securityObject, tconn);
829 CONN_HASH(shost, sport, tconn->cid, tconn->epoch,
830 RX_CLIENT_CONNECTION);
831 tconn->refCount++; /* no lock required since only this thread knows */
832 tconn->next = rx_connHashTable[hashindex];
833 rx_connHashTable[hashindex] = tconn;
834 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
837 MUTEX_EXIT(&rx_connHashTable_lock);
843 rx_SetConnDeadTime(register struct rx_connection *conn, register int seconds)
845 /* The idea is to set the dead time to a value that allows several
846 * keepalives to be dropped without timing out the connection. */
847 struct rx_connection *tconn;
850 tconn->secondsUntilDead = MAX(seconds, 6);
851 tconn->secondsUntilPing = tconn->secondsUntilDead / 6;
852 } while(tconn->next_clone && (tconn = tconn->next_clone));
855 int rxi_lowPeerRefCount = 0;
856 int rxi_lowConnRefCount = 0;
859 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
860 * NOTE: must not be called with rx_connHashTable_lock held.
863 rxi_CleanupConnection(struct rx_connection *conn)
865 /* Notify the service exporter, if requested, that this connection
866 * is being destroyed */
867 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
868 (*conn->service->destroyConnProc) (conn);
870 /* Notify the security module that this connection is being destroyed */
871 RXS_DestroyConnection(conn->securityObject, conn);
873 /* If this is the last connection using the rx_peer struct, set its
874 * idle time to now. rxi_ReapConnections will reap it if it's still
875 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
877 MUTEX_ENTER(&rx_peerHashTable_lock);
878 if (conn->peer->refCount < 2) {
879 conn->peer->idleWhen = clock_Sec();
880 if (conn->peer->refCount < 1) {
881 conn->peer->refCount = 1;
882 MUTEX_ENTER(&rx_stats_mutex);
883 rxi_lowPeerRefCount++;
884 MUTEX_EXIT(&rx_stats_mutex);
887 conn->peer->refCount--;
888 MUTEX_EXIT(&rx_peerHashTable_lock);
890 if (conn->type == RX_SERVER_CONNECTION)
891 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
893 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
895 if (conn->specific) {
897 for (i = 0; i < conn->nSpecific; i++) {
898 if (conn->specific[i] && rxi_keyCreate_destructor[i])
899 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
900 conn->specific[i] = NULL;
902 free(conn->specific);
904 conn->specific = NULL;
908 MUTEX_DESTROY(&conn->conn_call_lock);
909 MUTEX_DESTROY(&conn->conn_data_lock);
910 CV_DESTROY(&conn->conn_call_cv);
912 rxi_FreeConnection(conn);
915 /* Destroy the specified connection */
917 rxi_DestroyConnection(register struct rx_connection *conn)
919 register struct rx_connection *tconn, *dtconn;
921 MUTEX_ENTER(&rx_connHashTable_lock);
923 if(!(conn->flags & RX_CLONED_CONNECTION)) {
924 tconn = conn->next_clone;
925 conn->next_clone = 0; /* once */
929 tconn = tconn->next_clone;
930 rxi_DestroyConnectionNoLock(dtconn);
932 if (dtconn == rx_connCleanup_list) {
933 rx_connCleanup_list = rx_connCleanup_list->next;
934 MUTEX_EXIT(&rx_connHashTable_lock);
935 /* rxi_CleanupConnection will free tconn */
936 rxi_CleanupConnection(dtconn);
937 MUTEX_ENTER(&rx_connHashTable_lock);
944 rxi_DestroyConnectionNoLock(conn);
945 /* conn should be at the head of the cleanup list */
946 if (conn == rx_connCleanup_list) {
947 rx_connCleanup_list = rx_connCleanup_list->next;
948 MUTEX_EXIT(&rx_connHashTable_lock);
949 rxi_CleanupConnection(conn);
951 #ifdef RX_ENABLE_LOCKS
953 MUTEX_EXIT(&rx_connHashTable_lock);
955 #endif /* RX_ENABLE_LOCKS */
959 rxi_DestroyConnectionNoLock(register struct rx_connection *conn)
961 register struct rx_connection **conn_ptr;
962 register int havecalls = 0;
963 struct rx_packet *packet;
970 MUTEX_ENTER(&conn->conn_data_lock);
971 if (conn->refCount > 0)
974 MUTEX_ENTER(&rx_stats_mutex);
975 rxi_lowConnRefCount++;
976 MUTEX_EXIT(&rx_stats_mutex);
979 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
980 /* Busy; wait till the last guy before proceeding */
981 MUTEX_EXIT(&conn->conn_data_lock);
986 /* If the client previously called rx_NewCall, but it is still
987 * waiting, treat this as a running call, and wait to destroy the
988 * connection later when the call completes. */
989 if ((conn->type == RX_CLIENT_CONNECTION)
990 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
991 conn->flags |= RX_CONN_DESTROY_ME;
992 MUTEX_EXIT(&conn->conn_data_lock);
996 MUTEX_EXIT(&conn->conn_data_lock);
998 /* Check for extant references to this connection */
999 for (i = 0; i < RX_MAXCALLS; i++) {
1000 register struct rx_call *call = conn->call[i];
1003 if (conn->type == RX_CLIENT_CONNECTION) {
1004 MUTEX_ENTER(&call->lock);
1005 if (call->delayedAckEvent) {
1006 /* Push the final acknowledgment out now--there
1007 * won't be a subsequent call to acknowledge the
1008 * last reply packets */
1009 rxevent_Cancel(call->delayedAckEvent, call,
1010 RX_CALL_REFCOUNT_DELAY);
1011 if (call->state == RX_STATE_PRECALL
1012 || call->state == RX_STATE_ACTIVE) {
1013 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1015 rxi_AckAll(NULL, call, 0);
1018 MUTEX_EXIT(&call->lock);
1022 #ifdef RX_ENABLE_LOCKS
1024 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1025 MUTEX_EXIT(&conn->conn_data_lock);
1027 /* Someone is accessing a packet right now. */
1031 #endif /* RX_ENABLE_LOCKS */
1034 /* Don't destroy the connection if there are any call
1035 * structures still in use */
1036 MUTEX_ENTER(&conn->conn_data_lock);
1037 conn->flags |= RX_CONN_DESTROY_ME;
1038 MUTEX_EXIT(&conn->conn_data_lock);
1043 if (conn->delayedAbortEvent) {
1044 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1045 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1047 MUTEX_ENTER(&conn->conn_data_lock);
1048 rxi_SendConnectionAbort(conn, packet, 0, 1);
1049 MUTEX_EXIT(&conn->conn_data_lock);
1050 rxi_FreePacket(packet);
1054 /* Remove from connection hash table before proceeding */
1056 &rx_connHashTable[CONN_HASH
1057 (peer->host, peer->port, conn->cid, conn->epoch,
1059 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1060 if (*conn_ptr == conn) {
1061 *conn_ptr = conn->next;
1065 /* if the conn that we are destroying was the last connection, then we
1066 * clear rxLastConn as well */
1067 if (rxLastConn == conn)
1070 /* Make sure the connection is completely reset before deleting it. */
1071 /* get rid of pending events that could zap us later */
1072 if (conn->challengeEvent)
1073 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1074 if (conn->checkReachEvent)
1075 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1077 /* Add the connection to the list of destroyed connections that
1078 * need to be cleaned up. This is necessary to avoid deadlocks
1079 * in the routines we call to inform others that this connection is
1080 * being destroyed. */
1081 conn->next = rx_connCleanup_list;
1082 rx_connCleanup_list = conn;
1085 /* Externally available version */
1087 rx_DestroyConnection(register struct rx_connection *conn)
1092 rxi_DestroyConnection(conn);
1097 rx_GetConnection(register struct rx_connection *conn)
1102 MUTEX_ENTER(&conn->conn_data_lock);
1104 MUTEX_EXIT(&conn->conn_data_lock);
1108 /* Wait for the transmit queue to no longer be busy.
1109 * requires the call->lock to be held */
1110 static void rxi_WaitforTQBusy(struct rx_call *call) {
1111 while (call->flags & RX_CALL_TQ_BUSY) {
1112 call->flags |= RX_CALL_TQ_WAIT;
1114 #ifdef RX_ENABLE_LOCKS
1115 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1116 CV_WAIT(&call->cv_tq, &call->lock);
1117 #else /* RX_ENABLE_LOCKS */
1118 osi_rxSleep(&call->tq);
1119 #endif /* RX_ENABLE_LOCKS */
1121 if (call->tqWaiters == 0) {
1122 call->flags &= ~RX_CALL_TQ_WAIT;
1126 /* Start a new rx remote procedure call, on the specified connection.
1127 * If wait is set to 1, wait for a free call channel; otherwise return
1128 * 0. Maxtime gives the maximum number of seconds this call may take,
1129 * after rx_NewCall returns. After this time interval, a call to any
1130 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1131 * For fine grain locking, we hold the conn_call_lock in order to
1132 * to ensure that we don't get signalle after we found a call in an active
1133 * state and before we go to sleep.
1136 rx_NewCall(register struct rx_connection *conn)
1139 register struct rx_call *call;
1140 register struct rx_connection *tconn;
1141 struct clock queueTime;
1145 dpf(("rx_NewCall(conn %x)\n", conn));
1148 clock_GetTime(&queueTime);
1149 MUTEX_ENTER(&conn->conn_call_lock);
1152 * Check if there are others waiting for a new call.
1153 * If so, let them go first to avoid starving them.
1154 * This is a fairly simple scheme, and might not be
1155 * a complete solution for large numbers of waiters.
1157 * makeCallWaiters keeps track of the number of
1158 * threads waiting to make calls and the
1159 * RX_CONN_MAKECALL_WAITING flag bit is used to
1160 * indicate that there are indeed calls waiting.
1161 * The flag is set when the waiter is incremented.
1162 * It is only cleared in rx_EndCall when
1163 * makeCallWaiters is 0. This prevents us from
1164 * accidently destroying the connection while it
1165 * is potentially about to be used.
1167 MUTEX_ENTER(&conn->conn_data_lock);
1168 if (conn->makeCallWaiters) {
1169 conn->flags |= RX_CONN_MAKECALL_WAITING;
1170 conn->makeCallWaiters++;
1171 MUTEX_EXIT(&conn->conn_data_lock);
1173 #ifdef RX_ENABLE_LOCKS
1174 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1178 MUTEX_ENTER(&conn->conn_data_lock);
1179 conn->makeCallWaiters--;
1181 MUTEX_EXIT(&conn->conn_data_lock);
1183 /* search for next free call on this connection or
1184 * its clones, if any */
1188 for (i = 0; i < RX_MAXCALLS; i++) {
1189 call = tconn->call[i];
1191 MUTEX_ENTER(&call->lock);
1192 if (call->state == RX_STATE_DALLY) {
1193 rxi_ResetCall(call, 0);
1194 (*call->callNumber)++;
1197 MUTEX_EXIT(&call->lock);
1199 call = rxi_NewCall(tconn, i);
1202 } /* for i < RX_MAXCALLS */
1203 } while (tconn->next_clone && (tconn = tconn->next_clone));
1207 if (i < RX_MAXCALLS) {
1211 /* to be here, all available calls for this connection (and all
1212 * its clones) must be in use */
1214 MUTEX_ENTER(&conn->conn_data_lock);
1215 conn->flags |= RX_CONN_MAKECALL_WAITING;
1216 conn->makeCallWaiters++;
1217 MUTEX_EXIT(&conn->conn_data_lock);
1219 #ifdef RX_ENABLE_LOCKS
1220 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1224 MUTEX_ENTER(&conn->conn_data_lock);
1225 conn->makeCallWaiters--;
1226 MUTEX_EXIT(&conn->conn_data_lock);
1229 * Wake up anyone else who might be giving us a chance to
1230 * run (see code above that avoids resource starvation).
1232 #ifdef RX_ENABLE_LOCKS
1233 CV_BROADCAST(&conn->conn_call_cv);
1238 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1240 /* Client is initially in send mode */
1241 call->state = RX_STATE_ACTIVE;
1242 call->error = conn->error;
1244 call->mode = RX_MODE_ERROR;
1246 call->mode = RX_MODE_SENDING;
1248 /* remember start time for call in case we have hard dead time limit */
1249 call->queueTime = queueTime;
1250 clock_GetTime(&call->startTime);
1251 hzero(call->bytesSent);
1252 hzero(call->bytesRcvd);
1254 /* Turn on busy protocol. */
1255 rxi_KeepAliveOn(call);
1257 MUTEX_EXIT(&call->lock);
1258 MUTEX_EXIT(&conn->conn_call_lock);
1261 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1262 /* Now, if TQ wasn't cleared earlier, do it now. */
1263 MUTEX_ENTER(&call->lock);
1264 rxi_WaitforTQBusy(call);
1265 if (call->flags & RX_CALL_TQ_CLEARME) {
1266 rxi_ClearTransmitQueue(call, 0);
1267 queue_Init(&call->tq);
1269 MUTEX_EXIT(&call->lock);
1270 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1272 dpf(("rx_NewCall(call %x)\n", call));
1277 rxi_HasActiveCalls(register struct rx_connection *aconn)
1280 register struct rx_call *tcall;
1284 for (i = 0; i < RX_MAXCALLS; i++) {
1285 if ((tcall = aconn->call[i])) {
1286 if ((tcall->state == RX_STATE_ACTIVE)
1287 || (tcall->state == RX_STATE_PRECALL)) {
1298 rxi_GetCallNumberVector(register struct rx_connection *aconn,
1299 register afs_int32 * aint32s)
1302 register struct rx_call *tcall;
1306 for (i = 0; i < RX_MAXCALLS; i++) {
1307 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1308 aint32s[i] = aconn->callNumber[i] + 1;
1310 aint32s[i] = aconn->callNumber[i];
1317 rxi_SetCallNumberVector(register struct rx_connection *aconn,
1318 register afs_int32 * aint32s)
1321 register struct rx_call *tcall;
1325 for (i = 0; i < RX_MAXCALLS; i++) {
1326 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1327 aconn->callNumber[i] = aint32s[i] - 1;
1329 aconn->callNumber[i] = aint32s[i];
1335 /* Advertise a new service. A service is named locally by a UDP port
1336 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1339 char *serviceName; Name for identification purposes (e.g. the
1340 service name might be used for probing for
1343 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1344 char *serviceName, struct rx_securityClass **securityObjects,
1345 int nSecurityObjects,
1346 afs_int32(*serviceProc) (struct rx_call * acall))
1348 osi_socket socket = OSI_NULLSOCKET;
1349 register struct rx_service *tservice;
1355 if (serviceId == 0) {
1357 "rx_NewService: service id for service %s is not non-zero.\n",
1364 "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",
1372 tservice = rxi_AllocService();
1374 for (i = 0; i < RX_MAX_SERVICES; i++) {
1375 register struct rx_service *service = rx_services[i];
1377 if (port == service->servicePort && host == service->serviceHost) {
1378 if (service->serviceId == serviceId) {
1379 /* The identical service has already been
1380 * installed; if the caller was intending to
1381 * change the security classes used by this
1382 * service, he/she loses. */
1384 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1385 serviceName, serviceId, service->serviceName);
1387 rxi_FreeService(tservice);
1390 /* Different service, same port: re-use the socket
1391 * which is bound to the same port */
1392 socket = service->socket;
1395 if (socket == OSI_NULLSOCKET) {
1396 /* If we don't already have a socket (from another
1397 * service on same port) get a new one */
1398 socket = rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
1399 if (socket == OSI_NULLSOCKET) {
1401 rxi_FreeService(tservice);
1406 service->socket = socket;
1407 service->serviceHost = host;
1408 service->servicePort = port;
1409 service->serviceId = serviceId;
1410 service->serviceName = serviceName;
1411 service->nSecurityObjects = nSecurityObjects;
1412 service->securityObjects = securityObjects;
1413 service->minProcs = 0;
1414 service->maxProcs = 1;
1415 service->idleDeadTime = 60;
1416 service->idleDeadErr = 0;
1417 service->connDeadTime = rx_connDeadTime;
1418 service->executeRequestProc = serviceProc;
1419 service->checkReach = 0;
1420 rx_services[i] = service; /* not visible until now */
1426 rxi_FreeService(tservice);
1427 (osi_Msg "rx_NewService: cannot support > %d services\n",
1432 /* Set configuration options for all of a service's security objects */
1435 rx_SetSecurityConfiguration(struct rx_service *service,
1436 rx_securityConfigVariables type,
1440 for (i = 0; i<service->nSecurityObjects; i++) {
1441 if (service->securityObjects[i]) {
1442 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1450 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1451 struct rx_securityClass **securityObjects, int nSecurityObjects,
1452 afs_int32(*serviceProc) (struct rx_call * acall))
1454 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1457 /* Generic request processing loop. This routine should be called
1458 * by the implementation dependent rx_ServerProc. If socketp is
1459 * non-null, it will be set to the file descriptor that this thread
1460 * is now listening on. If socketp is null, this routine will never
1463 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1465 register struct rx_call *call;
1466 register afs_int32 code;
1467 register struct rx_service *tservice = NULL;
1474 call = rx_GetCall(threadID, tservice, socketp);
1475 if (socketp && *socketp != OSI_NULLSOCKET) {
1476 /* We are now a listener thread */
1481 /* if server is restarting( typically smooth shutdown) then do not
1482 * allow any new calls.
1485 if (rx_tranquil && (call != NULL)) {
1489 MUTEX_ENTER(&call->lock);
1491 rxi_CallError(call, RX_RESTARTING);
1492 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1494 MUTEX_EXIT(&call->lock);
1498 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1499 #ifdef RX_ENABLE_LOCKS
1501 #endif /* RX_ENABLE_LOCKS */
1502 afs_termState = AFSOP_STOP_AFS;
1503 afs_osi_Wakeup(&afs_termState);
1504 #ifdef RX_ENABLE_LOCKS
1506 #endif /* RX_ENABLE_LOCKS */
1511 tservice = call->conn->service;
1513 if (tservice->beforeProc)
1514 (*tservice->beforeProc) (call);
1516 code = call->conn->service->executeRequestProc(call);
1518 if (tservice->afterProc)
1519 (*tservice->afterProc) (call, code);
1521 rx_EndCall(call, code);
1522 MUTEX_ENTER(&rx_stats_mutex);
1524 MUTEX_EXIT(&rx_stats_mutex);
1530 rx_WakeupServerProcs(void)
1532 struct rx_serverQueueEntry *np, *tqp;
1536 MUTEX_ENTER(&rx_serverPool_lock);
1538 #ifdef RX_ENABLE_LOCKS
1539 if (rx_waitForPacket)
1540 CV_BROADCAST(&rx_waitForPacket->cv);
1541 #else /* RX_ENABLE_LOCKS */
1542 if (rx_waitForPacket)
1543 osi_rxWakeup(rx_waitForPacket);
1544 #endif /* RX_ENABLE_LOCKS */
1545 MUTEX_ENTER(&freeSQEList_lock);
1546 for (np = rx_FreeSQEList; np; np = tqp) {
1547 tqp = *(struct rx_serverQueueEntry **)np;
1548 #ifdef RX_ENABLE_LOCKS
1549 CV_BROADCAST(&np->cv);
1550 #else /* RX_ENABLE_LOCKS */
1552 #endif /* RX_ENABLE_LOCKS */
1554 MUTEX_EXIT(&freeSQEList_lock);
1555 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1556 #ifdef RX_ENABLE_LOCKS
1557 CV_BROADCAST(&np->cv);
1558 #else /* RX_ENABLE_LOCKS */
1560 #endif /* RX_ENABLE_LOCKS */
1562 MUTEX_EXIT(&rx_serverPool_lock);
1567 * One thing that seems to happen is that all the server threads get
1568 * tied up on some empty or slow call, and then a whole bunch of calls
1569 * arrive at once, using up the packet pool, so now there are more
1570 * empty calls. The most critical resources here are server threads
1571 * and the free packet pool. The "doreclaim" code seems to help in
1572 * general. I think that eventually we arrive in this state: there
1573 * are lots of pending calls which do have all their packets present,
1574 * so they won't be reclaimed, are multi-packet calls, so they won't
1575 * be scheduled until later, and thus are tying up most of the free
1576 * packet pool for a very long time.
1578 * 1. schedule multi-packet calls if all the packets are present.
1579 * Probably CPU-bound operation, useful to return packets to pool.
1580 * Do what if there is a full window, but the last packet isn't here?
1581 * 3. preserve one thread which *only* runs "best" calls, otherwise
1582 * it sleeps and waits for that type of call.
1583 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1584 * the current dataquota business is badly broken. The quota isn't adjusted
1585 * to reflect how many packets are presently queued for a running call.
1586 * So, when we schedule a queued call with a full window of packets queued
1587 * up for it, that *should* free up a window full of packets for other 2d-class
1588 * calls to be able to use from the packet pool. But it doesn't.
1590 * NB. Most of the time, this code doesn't run -- since idle server threads
1591 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1592 * as a new call arrives.
1594 /* Sleep until a call arrives. Returns a pointer to the call, ready
1595 * for an rx_Read. */
1596 #ifdef RX_ENABLE_LOCKS
1598 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1600 struct rx_serverQueueEntry *sq;
1601 register struct rx_call *call = (struct rx_call *)0;
1602 struct rx_service *service = NULL;
1605 MUTEX_ENTER(&freeSQEList_lock);
1607 if ((sq = rx_FreeSQEList)) {
1608 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1609 MUTEX_EXIT(&freeSQEList_lock);
1610 } else { /* otherwise allocate a new one and return that */
1611 MUTEX_EXIT(&freeSQEList_lock);
1612 sq = (struct rx_serverQueueEntry *)
1613 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1614 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1615 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1618 MUTEX_ENTER(&rx_serverPool_lock);
1619 if (cur_service != NULL) {
1620 ReturnToServerPool(cur_service);
1623 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1624 register struct rx_call *tcall, *ncall, *choice2 = NULL;
1626 /* Scan for eligible incoming calls. A call is not eligible
1627 * if the maximum number of calls for its service type are
1628 * already executing */
1629 /* One thread will process calls FCFS (to prevent starvation),
1630 * while the other threads may run ahead looking for calls which
1631 * have all their input data available immediately. This helps
1632 * keep threads from blocking, waiting for data from the client. */
1633 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1634 service = tcall->conn->service;
1635 if (!QuotaOK(service)) {
1638 if (tno == rxi_fcfs_thread_num
1639 || !tcall->queue_item_header.next) {
1640 /* If we're the fcfs thread , then we'll just use
1641 * this call. If we haven't been able to find an optimal
1642 * choice, and we're at the end of the list, then use a
1643 * 2d choice if one has been identified. Otherwise... */
1644 call = (choice2 ? choice2 : tcall);
1645 service = call->conn->service;
1646 } else if (!queue_IsEmpty(&tcall->rq)) {
1647 struct rx_packet *rp;
1648 rp = queue_First(&tcall->rq, rx_packet);
1649 if (rp->header.seq == 1) {
1651 || (rp->header.flags & RX_LAST_PACKET)) {
1653 } else if (rxi_2dchoice && !choice2
1654 && !(tcall->flags & RX_CALL_CLEARED)
1655 && (tcall->rprev > rxi_HardAckRate)) {
1664 ReturnToServerPool(service);
1671 MUTEX_EXIT(&rx_serverPool_lock);
1672 MUTEX_ENTER(&call->lock);
1674 if (call->flags & RX_CALL_WAIT_PROC) {
1675 call->flags &= ~RX_CALL_WAIT_PROC;
1676 MUTEX_ENTER(&rx_stats_mutex);
1678 MUTEX_EXIT(&rx_stats_mutex);
1681 if (call->state != RX_STATE_PRECALL || call->error) {
1682 MUTEX_EXIT(&call->lock);
1683 MUTEX_ENTER(&rx_serverPool_lock);
1684 ReturnToServerPool(service);
1689 if (queue_IsEmpty(&call->rq)
1690 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1691 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1693 CLEAR_CALL_QUEUE_LOCK(call);
1696 /* If there are no eligible incoming calls, add this process
1697 * to the idle server queue, to wait for one */
1701 *socketp = OSI_NULLSOCKET;
1703 sq->socketp = socketp;
1704 queue_Append(&rx_idleServerQueue, sq);
1705 #ifndef AFS_AIX41_ENV
1706 rx_waitForPacket = sq;
1708 rx_waitingForPacket = sq;
1709 #endif /* AFS_AIX41_ENV */
1711 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1713 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1714 MUTEX_EXIT(&rx_serverPool_lock);
1715 return (struct rx_call *)0;
1718 } while (!(call = sq->newcall)
1719 && !(socketp && *socketp != OSI_NULLSOCKET));
1720 MUTEX_EXIT(&rx_serverPool_lock);
1722 MUTEX_ENTER(&call->lock);
1728 MUTEX_ENTER(&freeSQEList_lock);
1729 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1730 rx_FreeSQEList = sq;
1731 MUTEX_EXIT(&freeSQEList_lock);
1734 clock_GetTime(&call->startTime);
1735 call->state = RX_STATE_ACTIVE;
1736 call->mode = RX_MODE_RECEIVING;
1737 #ifdef RX_KERNEL_TRACE
1738 if (ICL_SETACTIVE(afs_iclSetp)) {
1739 int glockOwner = ISAFS_GLOCK();
1742 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1743 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1750 rxi_calltrace(RX_CALL_START, call);
1751 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1752 call->conn->service->servicePort, call->conn->service->serviceId,
1755 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1756 MUTEX_EXIT(&call->lock);
1758 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1763 #else /* RX_ENABLE_LOCKS */
1765 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1767 struct rx_serverQueueEntry *sq;
1768 register struct rx_call *call = (struct rx_call *)0, *choice2;
1769 struct rx_service *service = NULL;
1773 MUTEX_ENTER(&freeSQEList_lock);
1775 if ((sq = rx_FreeSQEList)) {
1776 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1777 MUTEX_EXIT(&freeSQEList_lock);
1778 } else { /* otherwise allocate a new one and return that */
1779 MUTEX_EXIT(&freeSQEList_lock);
1780 sq = (struct rx_serverQueueEntry *)
1781 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1782 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1783 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1785 MUTEX_ENTER(&sq->lock);
1787 if (cur_service != NULL) {
1788 cur_service->nRequestsRunning--;
1789 if (cur_service->nRequestsRunning < cur_service->minProcs)
1793 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1794 register struct rx_call *tcall, *ncall;
1795 /* Scan for eligible incoming calls. A call is not eligible
1796 * if the maximum number of calls for its service type are
1797 * already executing */
1798 /* One thread will process calls FCFS (to prevent starvation),
1799 * while the other threads may run ahead looking for calls which
1800 * have all their input data available immediately. This helps
1801 * keep threads from blocking, waiting for data from the client. */
1802 choice2 = (struct rx_call *)0;
1803 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1804 service = tcall->conn->service;
1805 if (QuotaOK(service)) {
1806 if (tno == rxi_fcfs_thread_num
1807 || !tcall->queue_item_header.next) {
1808 /* If we're the fcfs thread, then we'll just use
1809 * this call. If we haven't been able to find an optimal
1810 * choice, and we're at the end of the list, then use a
1811 * 2d choice if one has been identified. Otherwise... */
1812 call = (choice2 ? choice2 : tcall);
1813 service = call->conn->service;
1814 } else if (!queue_IsEmpty(&tcall->rq)) {
1815 struct rx_packet *rp;
1816 rp = queue_First(&tcall->rq, rx_packet);
1817 if (rp->header.seq == 1
1819 || (rp->header.flags & RX_LAST_PACKET))) {
1821 } else if (rxi_2dchoice && !choice2
1822 && !(tcall->flags & RX_CALL_CLEARED)
1823 && (tcall->rprev > rxi_HardAckRate)) {
1836 /* we can't schedule a call if there's no data!!! */
1837 /* send an ack if there's no data, if we're missing the
1838 * first packet, or we're missing something between first
1839 * and last -- there's a "hole" in the incoming data. */
1840 if (queue_IsEmpty(&call->rq)
1841 || queue_First(&call->rq, rx_packet)->header.seq != 1
1842 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1843 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1845 call->flags &= (~RX_CALL_WAIT_PROC);
1846 service->nRequestsRunning++;
1847 /* just started call in minProcs pool, need fewer to maintain
1849 if (service->nRequestsRunning <= service->minProcs)
1853 /* MUTEX_EXIT(&call->lock); */
1855 /* If there are no eligible incoming calls, add this process
1856 * to the idle server queue, to wait for one */
1859 *socketp = OSI_NULLSOCKET;
1861 sq->socketp = socketp;
1862 queue_Append(&rx_idleServerQueue, sq);
1866 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1868 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1869 return (struct rx_call *)0;
1872 } while (!(call = sq->newcall)
1873 && !(socketp && *socketp != OSI_NULLSOCKET));
1875 MUTEX_EXIT(&sq->lock);
1877 MUTEX_ENTER(&freeSQEList_lock);
1878 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1879 rx_FreeSQEList = sq;
1880 MUTEX_EXIT(&freeSQEList_lock);
1883 clock_GetTime(&call->startTime);
1884 call->state = RX_STATE_ACTIVE;
1885 call->mode = RX_MODE_RECEIVING;
1886 #ifdef RX_KERNEL_TRACE
1887 if (ICL_SETACTIVE(afs_iclSetp)) {
1888 int glockOwner = ISAFS_GLOCK();
1891 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1892 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1899 rxi_calltrace(RX_CALL_START, call);
1900 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1901 call->conn->service->servicePort, call->conn->service->serviceId,
1904 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1911 #endif /* RX_ENABLE_LOCKS */
1915 /* Establish a procedure to be called when a packet arrives for a
1916 * call. This routine will be called at most once after each call,
1917 * and will also be called if there is an error condition on the or
1918 * the call is complete. Used by multi rx to build a selection
1919 * function which determines which of several calls is likely to be a
1920 * good one to read from.
1921 * NOTE: the way this is currently implemented it is probably only a
1922 * good idea to (1) use it immediately after a newcall (clients only)
1923 * and (2) only use it once. Other uses currently void your warranty
1926 rx_SetArrivalProc(register struct rx_call *call,
1927 register void (*proc) (register struct rx_call * call,
1929 register int index),
1930 register void * handle, register int arg)
1932 call->arrivalProc = proc;
1933 call->arrivalProcHandle = handle;
1934 call->arrivalProcArg = arg;
1937 /* Call is finished (possibly prematurely). Return rc to the peer, if
1938 * appropriate, and return the final error code from the conversation
1942 rx_EndCall(register struct rx_call *call, afs_int32 rc)
1944 register struct rx_connection *conn = call->conn;
1945 register struct rx_service *service;
1951 dpf(("rx_EndCall(call %x rc %d error %d abortCode %d)\n", call, rc, call->error, call->abortCode));
1954 MUTEX_ENTER(&call->lock);
1956 if (rc == 0 && call->error == 0) {
1957 call->abortCode = 0;
1958 call->abortCount = 0;
1961 call->arrivalProc = (void (*)())0;
1962 if (rc && call->error == 0) {
1963 rxi_CallError(call, rc);
1964 /* Send an abort message to the peer if this error code has
1965 * only just been set. If it was set previously, assume the
1966 * peer has already been sent the error code or will request it
1968 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1970 if (conn->type == RX_SERVER_CONNECTION) {
1971 /* Make sure reply or at least dummy reply is sent */
1972 if (call->mode == RX_MODE_RECEIVING) {
1973 rxi_WriteProc(call, 0, 0);
1975 if (call->mode == RX_MODE_SENDING) {
1976 rxi_FlushWrite(call);
1978 service = conn->service;
1979 rxi_calltrace(RX_CALL_END, call);
1980 /* Call goes to hold state until reply packets are acknowledged */
1981 if (call->tfirst + call->nSoftAcked < call->tnext) {
1982 call->state = RX_STATE_HOLD;
1984 call->state = RX_STATE_DALLY;
1985 rxi_ClearTransmitQueue(call, 0);
1986 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
1987 rxevent_Cancel(call->keepAliveEvent, call,
1988 RX_CALL_REFCOUNT_ALIVE);
1990 } else { /* Client connection */
1992 /* Make sure server receives input packets, in the case where
1993 * no reply arguments are expected */
1994 if ((call->mode == RX_MODE_SENDING)
1995 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
1996 (void)rxi_ReadProc(call, &dummy, 1);
1999 /* If we had an outstanding delayed ack, be nice to the server
2000 * and force-send it now.
2002 if (call->delayedAckEvent) {
2003 rxevent_Cancel(call->delayedAckEvent, call,
2004 RX_CALL_REFCOUNT_DELAY);
2005 call->delayedAckEvent = NULL;
2006 rxi_SendDelayedAck(NULL, call, NULL);
2009 /* We need to release the call lock since it's lower than the
2010 * conn_call_lock and we don't want to hold the conn_call_lock
2011 * over the rx_ReadProc call. The conn_call_lock needs to be held
2012 * here for the case where rx_NewCall is perusing the calls on
2013 * the connection structure. We don't want to signal until
2014 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2015 * have checked this call, found it active and by the time it
2016 * goes to sleep, will have missed the signal.
2018 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2019 * there are threads waiting to use the conn object.
2021 MUTEX_EXIT(&call->lock);
2022 MUTEX_ENTER(&conn->conn_call_lock);
2023 MUTEX_ENTER(&call->lock);
2024 MUTEX_ENTER(&conn->conn_data_lock);
2025 conn->flags |= RX_CONN_BUSY;
2026 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2027 if (conn->makeCallWaiters == 0)
2028 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2029 MUTEX_EXIT(&conn->conn_data_lock);
2030 #ifdef RX_ENABLE_LOCKS
2031 CV_BROADCAST(&conn->conn_call_cv);
2036 #ifdef RX_ENABLE_LOCKS
2038 MUTEX_EXIT(&conn->conn_data_lock);
2040 #endif /* RX_ENABLE_LOCKS */
2041 call->state = RX_STATE_DALLY;
2043 error = call->error;
2045 /* currentPacket, nLeft, and NFree must be zeroed here, because
2046 * ResetCall cannot: ResetCall may be called at splnet(), in the
2047 * kernel version, and may interrupt the macros rx_Read or
2048 * rx_Write, which run at normal priority for efficiency. */
2049 if (call->currentPacket) {
2050 queue_Prepend(&call->iovq, call->currentPacket);
2051 call->currentPacket = (struct rx_packet *)0;
2054 call->nLeft = call->nFree = call->curlen = 0;
2056 /* Free any packets from the last call to ReadvProc/WritevProc */
2057 rxi_FreePackets(0, &call->iovq);
2059 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2060 MUTEX_EXIT(&call->lock);
2061 if (conn->type == RX_CLIENT_CONNECTION) {
2062 MUTEX_EXIT(&conn->conn_call_lock);
2063 conn->flags &= ~RX_CONN_BUSY;
2067 * Map errors to the local host's errno.h format.
2069 error = ntoh_syserr_conv(error);
2073 #if !defined(KERNEL)
2075 /* Call this routine when shutting down a server or client (especially
2076 * clients). This will allow Rx to gracefully garbage collect server
2077 * connections, and reduce the number of retries that a server might
2078 * make to a dead client.
2079 * This is not quite right, since some calls may still be ongoing and
2080 * we can't lock them to destroy them. */
2084 register struct rx_connection **conn_ptr, **conn_end;
2088 if (rxinit_status == 1) {
2090 return; /* Already shutdown. */
2092 rxi_DeleteCachedConnections();
2093 if (rx_connHashTable) {
2094 MUTEX_ENTER(&rx_connHashTable_lock);
2095 for (conn_ptr = &rx_connHashTable[0], conn_end =
2096 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2098 struct rx_connection *conn, *next;
2099 for (conn = *conn_ptr; conn; conn = next) {
2101 if (conn->type == RX_CLIENT_CONNECTION) {
2102 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2104 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2105 #ifdef RX_ENABLE_LOCKS
2106 rxi_DestroyConnectionNoLock(conn);
2107 #else /* RX_ENABLE_LOCKS */
2108 rxi_DestroyConnection(conn);
2109 #endif /* RX_ENABLE_LOCKS */
2113 #ifdef RX_ENABLE_LOCKS
2114 while (rx_connCleanup_list) {
2115 struct rx_connection *conn;
2116 conn = rx_connCleanup_list;
2117 rx_connCleanup_list = rx_connCleanup_list->next;
2118 MUTEX_EXIT(&rx_connHashTable_lock);
2119 rxi_CleanupConnection(conn);
2120 MUTEX_ENTER(&rx_connHashTable_lock);
2122 MUTEX_EXIT(&rx_connHashTable_lock);
2123 #endif /* RX_ENABLE_LOCKS */
2128 afs_winsockCleanup();
2136 /* if we wakeup packet waiter too often, can get in loop with two
2137 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2139 rxi_PacketsUnWait(void)
2141 if (!rx_waitingForPackets) {
2145 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2146 return; /* still over quota */
2149 rx_waitingForPackets = 0;
2150 #ifdef RX_ENABLE_LOCKS
2151 CV_BROADCAST(&rx_waitingForPackets_cv);
2153 osi_rxWakeup(&rx_waitingForPackets);
2159 /* ------------------Internal interfaces------------------------- */
2161 /* Return this process's service structure for the
2162 * specified socket and service */
2164 rxi_FindService(register osi_socket socket, register u_short serviceId)
2166 register struct rx_service **sp;
2167 for (sp = &rx_services[0]; *sp; sp++) {
2168 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2174 /* Allocate a call structure, for the indicated channel of the
2175 * supplied connection. The mode and state of the call must be set by
2176 * the caller. Returns the call with mutex locked. */
2178 rxi_NewCall(register struct rx_connection *conn, register int channel)
2180 register struct rx_call *call;
2181 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2182 register struct rx_call *cp; /* Call pointer temp */
2183 register struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2184 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2186 dpf(("rxi_NewCall(conn %x, channel %d)\n", conn, channel));
2188 /* Grab an existing call structure, or allocate a new one.
2189 * Existing call structures are assumed to have been left reset by
2191 MUTEX_ENTER(&rx_freeCallQueue_lock);
2193 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2195 * EXCEPT that the TQ might not yet be cleared out.
2196 * Skip over those with in-use TQs.
2199 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2200 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2206 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2207 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2208 call = queue_First(&rx_freeCallQueue, rx_call);
2209 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2211 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2212 MUTEX_EXIT(&rx_freeCallQueue_lock);
2213 MUTEX_ENTER(&call->lock);
2214 CLEAR_CALL_QUEUE_LOCK(call);
2215 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2216 /* Now, if TQ wasn't cleared earlier, do it now. */
2217 if (call->flags & RX_CALL_TQ_CLEARME) {
2218 rxi_ClearTransmitQueue(call, 0);
2219 queue_Init(&call->tq);
2221 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2222 /* Bind the call to its connection structure */
2224 rxi_ResetCall(call, 1);
2227 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2229 MUTEX_EXIT(&rx_freeCallQueue_lock);
2230 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2231 MUTEX_ENTER(&call->lock);
2232 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2233 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2234 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2236 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2237 /* Initialize once-only items */
2238 queue_Init(&call->tq);
2239 queue_Init(&call->rq);
2240 queue_Init(&call->iovq);
2241 /* Bind the call to its connection structure (prereq for reset) */
2243 rxi_ResetCall(call, 1);
2245 call->channel = channel;
2246 call->callNumber = &conn->callNumber[channel];
2247 call->rwind = conn->rwind[channel];
2248 call->twind = conn->twind[channel];
2249 /* Note that the next expected call number is retained (in
2250 * conn->callNumber[i]), even if we reallocate the call structure
2252 conn->call[channel] = call;
2253 /* if the channel's never been used (== 0), we should start at 1, otherwise
2254 * the call number is valid from the last time this channel was used */
2255 if (*call->callNumber == 0)
2256 *call->callNumber = 1;
2261 /* A call has been inactive long enough that so we can throw away
2262 * state, including the call structure, which is placed on the call
2264 * Call is locked upon entry.
2265 * haveCTLock set if called from rxi_ReapConnections
2267 #ifdef RX_ENABLE_LOCKS
2269 rxi_FreeCall(register struct rx_call *call, int haveCTLock)
2270 #else /* RX_ENABLE_LOCKS */
2272 rxi_FreeCall(register struct rx_call *call)
2273 #endif /* RX_ENABLE_LOCKS */
2275 register int channel = call->channel;
2276 register struct rx_connection *conn = call->conn;
2279 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2280 (*call->callNumber)++;
2281 rxi_ResetCall(call, 0);
2282 call->conn->call[channel] = (struct rx_call *)0;
2284 MUTEX_ENTER(&rx_freeCallQueue_lock);
2285 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2286 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2287 /* A call may be free even though its transmit queue is still in use.
2288 * Since we search the call list from head to tail, put busy calls at
2289 * the head of the list, and idle calls at the tail.
2291 if (call->flags & RX_CALL_TQ_BUSY)
2292 queue_Prepend(&rx_freeCallQueue, call);
2294 queue_Append(&rx_freeCallQueue, call);
2295 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2296 queue_Append(&rx_freeCallQueue, call);
2297 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2298 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2299 MUTEX_EXIT(&rx_freeCallQueue_lock);
2301 /* Destroy the connection if it was previously slated for
2302 * destruction, i.e. the Rx client code previously called
2303 * rx_DestroyConnection (client connections), or
2304 * rxi_ReapConnections called the same routine (server
2305 * connections). Only do this, however, if there are no
2306 * outstanding calls. Note that for fine grain locking, there appears
2307 * to be a deadlock in that rxi_FreeCall has a call locked and
2308 * DestroyConnectionNoLock locks each call in the conn. But note a
2309 * few lines up where we have removed this call from the conn.
2310 * If someone else destroys a connection, they either have no
2311 * call lock held or are going through this section of code.
2313 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2314 MUTEX_ENTER(&conn->conn_data_lock);
2316 MUTEX_EXIT(&conn->conn_data_lock);
2317 #ifdef RX_ENABLE_LOCKS
2319 rxi_DestroyConnectionNoLock(conn);
2321 rxi_DestroyConnection(conn);
2322 #else /* RX_ENABLE_LOCKS */
2323 rxi_DestroyConnection(conn);
2324 #endif /* RX_ENABLE_LOCKS */
2328 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2330 rxi_Alloc(register size_t size)
2334 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2337 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2338 afs_osi_Alloc_NoSleep(size);
2343 osi_Panic("rxi_Alloc error");
2349 rxi_Free(void *addr, register size_t size)
2351 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2352 osi_Free(addr, size);
2356 rxi_SetPeerMtu(register afs_uint32 host, register afs_uint32 port, int mtu)
2358 struct rx_peer **peer_ptr, **peer_end;
2361 MUTEX_ENTER(&rx_peerHashTable_lock);
2363 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2364 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2366 struct rx_peer *peer, *next;
2367 for (peer = *peer_ptr; peer; peer = next) {
2369 if (host == peer->host) {
2370 MUTEX_ENTER(&peer->peer_lock);
2371 peer->ifMTU=MIN(mtu, peer->ifMTU);
2372 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2373 MUTEX_EXIT(&peer->peer_lock);
2378 struct rx_peer *peer, *next;
2379 hashIndex = PEER_HASH(host, port);
2380 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2381 if ((peer->host == host) && (peer->port == port)) {
2382 MUTEX_ENTER(&peer->peer_lock);
2383 peer->ifMTU=MIN(mtu, peer->ifMTU);
2384 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2385 MUTEX_EXIT(&peer->peer_lock);
2389 MUTEX_EXIT(&rx_peerHashTable_lock);
2392 /* Find the peer process represented by the supplied (host,port)
2393 * combination. If there is no appropriate active peer structure, a
2394 * new one will be allocated and initialized
2395 * The origPeer, if set, is a pointer to a peer structure on which the
2396 * refcount will be be decremented. This is used to replace the peer
2397 * structure hanging off a connection structure */
2399 rxi_FindPeer(register afs_uint32 host, register u_short port,
2400 struct rx_peer *origPeer, int create)
2402 register struct rx_peer *pp;
2404 hashIndex = PEER_HASH(host, port);
2405 MUTEX_ENTER(&rx_peerHashTable_lock);
2406 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2407 if ((pp->host == host) && (pp->port == port))
2412 pp = rxi_AllocPeer(); /* This bzero's *pp */
2413 pp->host = host; /* set here or in InitPeerParams is zero */
2415 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2416 queue_Init(&pp->congestionQueue);
2417 queue_Init(&pp->rpcStats);
2418 pp->next = rx_peerHashTable[hashIndex];
2419 rx_peerHashTable[hashIndex] = pp;
2420 rxi_InitPeerParams(pp);
2421 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2428 origPeer->refCount--;
2429 MUTEX_EXIT(&rx_peerHashTable_lock);
2434 /* Find the connection at (host, port) started at epoch, and with the
2435 * given connection id. Creates the server connection if necessary.
2436 * The type specifies whether a client connection or a server
2437 * connection is desired. In both cases, (host, port) specify the
2438 * peer's (host, pair) pair. Client connections are not made
2439 * automatically by this routine. The parameter socket gives the
2440 * socket descriptor on which the packet was received. This is used,
2441 * in the case of server connections, to check that *new* connections
2442 * come via a valid (port, serviceId). Finally, the securityIndex
2443 * parameter must match the existing index for the connection. If a
2444 * server connection is created, it will be created using the supplied
2445 * index, if the index is valid for this service */
2446 struct rx_connection *
2447 rxi_FindConnection(osi_socket socket, register afs_int32 host,
2448 register u_short port, u_short serviceId, afs_uint32 cid,
2449 afs_uint32 epoch, int type, u_int securityIndex)
2451 int hashindex, flag, i;
2452 register struct rx_connection *conn;
2453 hashindex = CONN_HASH(host, port, cid, epoch, type);
2454 MUTEX_ENTER(&rx_connHashTable_lock);
2455 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2456 rx_connHashTable[hashindex],
2459 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2460 && (epoch == conn->epoch)) {
2461 register struct rx_peer *pp = conn->peer;
2462 if (securityIndex != conn->securityIndex) {
2463 /* this isn't supposed to happen, but someone could forge a packet
2464 * like this, and there seems to be some CM bug that makes this
2465 * happen from time to time -- in which case, the fileserver
2467 MUTEX_EXIT(&rx_connHashTable_lock);
2468 return (struct rx_connection *)0;
2470 if (pp->host == host && pp->port == port)
2472 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2474 /* So what happens when it's a callback connection? */
2475 if ( /*type == RX_CLIENT_CONNECTION && */
2476 (conn->epoch & 0x80000000))
2480 /* the connection rxLastConn that was used the last time is not the
2481 ** one we are looking for now. Hence, start searching in the hash */
2483 conn = rx_connHashTable[hashindex];
2488 struct rx_service *service;
2489 if (type == RX_CLIENT_CONNECTION) {
2490 MUTEX_EXIT(&rx_connHashTable_lock);
2491 return (struct rx_connection *)0;
2493 service = rxi_FindService(socket, serviceId);
2494 if (!service || (securityIndex >= service->nSecurityObjects)
2495 || (service->securityObjects[securityIndex] == 0)) {
2496 MUTEX_EXIT(&rx_connHashTable_lock);
2497 return (struct rx_connection *)0;
2499 conn = rxi_AllocConnection(); /* This bzero's the connection */
2500 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2501 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2502 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2503 conn->next = rx_connHashTable[hashindex];
2504 rx_connHashTable[hashindex] = conn;
2505 conn->peer = rxi_FindPeer(host, port, 0, 1);
2506 conn->type = RX_SERVER_CONNECTION;
2507 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2508 conn->epoch = epoch;
2509 conn->cid = cid & RX_CIDMASK;
2510 /* conn->serial = conn->lastSerial = 0; */
2511 /* conn->timeout = 0; */
2512 conn->ackRate = RX_FAST_ACK_RATE;
2513 conn->service = service;
2514 conn->serviceId = serviceId;
2515 conn->securityIndex = securityIndex;
2516 conn->securityObject = service->securityObjects[securityIndex];
2517 conn->nSpecific = 0;
2518 conn->specific = NULL;
2519 rx_SetConnDeadTime(conn, service->connDeadTime);
2520 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2521 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2522 for (i = 0; i < RX_MAXCALLS; i++) {
2523 conn->twind[i] = rx_initSendWindow;
2524 conn->rwind[i] = rx_initReceiveWindow;
2526 /* Notify security object of the new connection */
2527 RXS_NewConnection(conn->securityObject, conn);
2528 /* XXXX Connection timeout? */
2529 if (service->newConnProc)
2530 (*service->newConnProc) (conn);
2531 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2534 MUTEX_ENTER(&conn->conn_data_lock);
2536 MUTEX_EXIT(&conn->conn_data_lock);
2538 rxLastConn = conn; /* store this connection as the last conn used */
2539 MUTEX_EXIT(&rx_connHashTable_lock);
2543 /* There are two packet tracing routines available for testing and monitoring
2544 * Rx. One is called just after every packet is received and the other is
2545 * called just before every packet is sent. Received packets, have had their
2546 * headers decoded, and packets to be sent have not yet had their headers
2547 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2548 * containing the network address. Both can be modified. The return value, if
2549 * non-zero, indicates that the packet should be dropped. */
2551 int (*rx_justReceived) () = 0;
2552 int (*rx_almostSent) () = 0;
2554 /* A packet has been received off the interface. Np is the packet, socket is
2555 * the socket number it was received from (useful in determining which service
2556 * this packet corresponds to), and (host, port) reflect the host,port of the
2557 * sender. This call returns the packet to the caller if it is finished with
2558 * it, rather than de-allocating it, just as a small performance hack */
2561 rxi_ReceivePacket(register struct rx_packet *np, osi_socket socket,
2562 afs_uint32 host, u_short port, int *tnop,
2563 struct rx_call **newcallp)
2565 register struct rx_call *call;
2566 register struct rx_connection *conn;
2568 afs_uint32 currentCallNumber;
2574 struct rx_packet *tnp;
2577 /* We don't print out the packet until now because (1) the time may not be
2578 * accurate enough until now in the lwp implementation (rx_Listener only gets
2579 * the time after the packet is read) and (2) from a protocol point of view,
2580 * this is the first time the packet has been seen */
2581 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2582 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2583 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2584 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2585 np->header.epoch, np->header.cid, np->header.callNumber,
2586 np->header.seq, np->header.flags, np));
2589 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2590 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2593 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2594 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2597 /* If an input tracer function is defined, call it with the packet and
2598 * network address. Note this function may modify its arguments. */
2599 if (rx_justReceived) {
2600 struct sockaddr_in addr;
2602 addr.sin_family = AF_INET;
2603 addr.sin_port = port;
2604 addr.sin_addr.s_addr = host;
2605 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2606 addr.sin_len = sizeof(addr);
2607 #endif /* AFS_OSF_ENV */
2608 drop = (*rx_justReceived) (np, &addr);
2609 /* drop packet if return value is non-zero */
2612 port = addr.sin_port; /* in case fcn changed addr */
2613 host = addr.sin_addr.s_addr;
2617 /* If packet was not sent by the client, then *we* must be the client */
2618 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2619 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2621 /* Find the connection (or fabricate one, if we're the server & if
2622 * necessary) associated with this packet */
2624 rxi_FindConnection(socket, host, port, np->header.serviceId,
2625 np->header.cid, np->header.epoch, type,
2626 np->header.securityIndex);
2629 /* If no connection found or fabricated, just ignore the packet.
2630 * (An argument could be made for sending an abort packet for
2635 MUTEX_ENTER(&conn->conn_data_lock);
2636 if (conn->maxSerial < np->header.serial)
2637 conn->maxSerial = np->header.serial;
2638 MUTEX_EXIT(&conn->conn_data_lock);
2640 /* If the connection is in an error state, send an abort packet and ignore
2641 * the incoming packet */
2643 /* Don't respond to an abort packet--we don't want loops! */
2644 MUTEX_ENTER(&conn->conn_data_lock);
2645 if (np->header.type != RX_PACKET_TYPE_ABORT)
2646 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2648 MUTEX_EXIT(&conn->conn_data_lock);
2652 /* Check for connection-only requests (i.e. not call specific). */
2653 if (np->header.callNumber == 0) {
2654 switch (np->header.type) {
2655 case RX_PACKET_TYPE_ABORT: {
2656 /* What if the supplied error is zero? */
2657 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2658 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2659 rxi_ConnectionError(conn, errcode);
2660 MUTEX_ENTER(&conn->conn_data_lock);
2662 MUTEX_EXIT(&conn->conn_data_lock);
2665 case RX_PACKET_TYPE_CHALLENGE:
2666 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2667 MUTEX_ENTER(&conn->conn_data_lock);
2669 MUTEX_EXIT(&conn->conn_data_lock);
2671 case RX_PACKET_TYPE_RESPONSE:
2672 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2673 MUTEX_ENTER(&conn->conn_data_lock);
2675 MUTEX_EXIT(&conn->conn_data_lock);
2677 case RX_PACKET_TYPE_PARAMS:
2678 case RX_PACKET_TYPE_PARAMS + 1:
2679 case RX_PACKET_TYPE_PARAMS + 2:
2680 /* ignore these packet types for now */
2681 MUTEX_ENTER(&conn->conn_data_lock);
2683 MUTEX_EXIT(&conn->conn_data_lock);
2688 /* Should not reach here, unless the peer is broken: send an
2690 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2691 MUTEX_ENTER(&conn->conn_data_lock);
2692 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2694 MUTEX_EXIT(&conn->conn_data_lock);
2699 channel = np->header.cid & RX_CHANNELMASK;
2700 call = conn->call[channel];
2701 #ifdef RX_ENABLE_LOCKS
2703 MUTEX_ENTER(&call->lock);
2704 /* Test to see if call struct is still attached to conn. */
2705 if (call != conn->call[channel]) {
2707 MUTEX_EXIT(&call->lock);
2708 if (type == RX_SERVER_CONNECTION) {
2709 call = conn->call[channel];
2710 /* If we started with no call attached and there is one now,
2711 * another thread is also running this routine and has gotten
2712 * the connection channel. We should drop this packet in the tests
2713 * below. If there was a call on this connection and it's now
2714 * gone, then we'll be making a new call below.
2715 * If there was previously a call and it's now different then
2716 * the old call was freed and another thread running this routine
2717 * has created a call on this channel. One of these two threads
2718 * has a packet for the old call and the code below handles those
2722 MUTEX_ENTER(&call->lock);
2724 /* This packet can't be for this call. If the new call address is
2725 * 0 then no call is running on this channel. If there is a call
2726 * then, since this is a client connection we're getting data for
2727 * it must be for the previous call.
2729 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2730 MUTEX_ENTER(&conn->conn_data_lock);
2732 MUTEX_EXIT(&conn->conn_data_lock);
2737 currentCallNumber = conn->callNumber[channel];
2739 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2740 if (np->header.callNumber < currentCallNumber) {
2741 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2742 #ifdef RX_ENABLE_LOCKS
2744 MUTEX_EXIT(&call->lock);
2746 MUTEX_ENTER(&conn->conn_data_lock);
2748 MUTEX_EXIT(&conn->conn_data_lock);
2752 MUTEX_ENTER(&conn->conn_call_lock);
2753 call = rxi_NewCall(conn, channel);
2754 MUTEX_EXIT(&conn->conn_call_lock);
2755 *call->callNumber = np->header.callNumber;
2756 if (np->header.callNumber == 0)
2757 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %lx resend %d.%0.3d len %d", np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port), np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq, np->header.flags, (unsigned long)np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2759 call->state = RX_STATE_PRECALL;
2760 clock_GetTime(&call->queueTime);
2761 hzero(call->bytesSent);
2762 hzero(call->bytesRcvd);
2764 * If the number of queued calls exceeds the overload
2765 * threshold then abort this call.
2767 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2768 struct rx_packet *tp;
2770 rxi_CallError(call, rx_BusyError);
2771 tp = rxi_SendCallAbort(call, np, 1, 0);
2772 MUTEX_EXIT(&call->lock);
2773 MUTEX_ENTER(&conn->conn_data_lock);
2775 MUTEX_EXIT(&conn->conn_data_lock);
2776 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2779 rxi_KeepAliveOn(call);
2780 } else if (np->header.callNumber != currentCallNumber) {
2781 /* Wait until the transmit queue is idle before deciding
2782 * whether to reset the current call. Chances are that the
2783 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2786 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2787 while ((call->state == RX_STATE_ACTIVE)
2788 && (call->flags & RX_CALL_TQ_BUSY)) {
2789 call->flags |= RX_CALL_TQ_WAIT;
2791 #ifdef RX_ENABLE_LOCKS
2792 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2793 CV_WAIT(&call->cv_tq, &call->lock);
2794 #else /* RX_ENABLE_LOCKS */
2795 osi_rxSleep(&call->tq);
2796 #endif /* RX_ENABLE_LOCKS */
2798 if (call->tqWaiters == 0)
2799 call->flags &= ~RX_CALL_TQ_WAIT;
2801 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2802 /* If the new call cannot be taken right now send a busy and set
2803 * the error condition in this call, so that it terminates as
2804 * quickly as possible */
2805 if (call->state == RX_STATE_ACTIVE) {
2806 struct rx_packet *tp;
2808 rxi_CallError(call, RX_CALL_DEAD);
2809 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2811 MUTEX_EXIT(&call->lock);
2812 MUTEX_ENTER(&conn->conn_data_lock);
2814 MUTEX_EXIT(&conn->conn_data_lock);
2817 rxi_ResetCall(call, 0);
2818 *call->callNumber = np->header.callNumber;
2819 if (np->header.callNumber == 0)
2820 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %lx resend %d.%0.3d len %d", np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port), np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq, np->header.flags, (unsigned long)np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2822 call->state = RX_STATE_PRECALL;
2823 clock_GetTime(&call->queueTime);
2824 hzero(call->bytesSent);
2825 hzero(call->bytesRcvd);
2827 * If the number of queued calls exceeds the overload
2828 * threshold then abort this call.
2830 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2831 struct rx_packet *tp;
2833 rxi_CallError(call, rx_BusyError);
2834 tp = rxi_SendCallAbort(call, np, 1, 0);
2835 MUTEX_EXIT(&call->lock);
2836 MUTEX_ENTER(&conn->conn_data_lock);
2838 MUTEX_EXIT(&conn->conn_data_lock);
2839 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2842 rxi_KeepAliveOn(call);
2844 /* Continuing call; do nothing here. */
2846 } else { /* we're the client */
2847 /* Ignore all incoming acknowledgements for calls in DALLY state */
2848 if (call && (call->state == RX_STATE_DALLY)
2849 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2850 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2851 #ifdef RX_ENABLE_LOCKS
2853 MUTEX_EXIT(&call->lock);
2856 MUTEX_ENTER(&conn->conn_data_lock);
2858 MUTEX_EXIT(&conn->conn_data_lock);
2862 /* Ignore anything that's not relevant to the current call. If there
2863 * isn't a current call, then no packet is relevant. */
2864 if (!call || (np->header.callNumber != currentCallNumber)) {
2865 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2866 #ifdef RX_ENABLE_LOCKS
2868 MUTEX_EXIT(&call->lock);
2871 MUTEX_ENTER(&conn->conn_data_lock);
2873 MUTEX_EXIT(&conn->conn_data_lock);
2876 /* If the service security object index stamped in the packet does not
2877 * match the connection's security index, ignore the packet */
2878 if (np->header.securityIndex != conn->securityIndex) {
2879 #ifdef RX_ENABLE_LOCKS
2880 MUTEX_EXIT(&call->lock);
2882 MUTEX_ENTER(&conn->conn_data_lock);
2884 MUTEX_EXIT(&conn->conn_data_lock);
2888 /* If we're receiving the response, then all transmit packets are
2889 * implicitly acknowledged. Get rid of them. */
2890 if (np->header.type == RX_PACKET_TYPE_DATA) {
2891 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2892 /* XXX Hack. Because we must release the global rx lock when
2893 * sending packets (osi_NetSend) we drop all acks while we're
2894 * traversing the tq in rxi_Start sending packets out because
2895 * packets may move to the freePacketQueue as result of being here!
2896 * So we drop these packets until we're safely out of the
2897 * traversing. Really ugly!
2898 * For fine grain RX locking, we set the acked field in the
2899 * packets and let rxi_Start remove them from the transmit queue.
2901 if (call->flags & RX_CALL_TQ_BUSY) {
2902 #ifdef RX_ENABLE_LOCKS
2903 rxi_SetAcksInTransmitQueue(call);
2906 return np; /* xmitting; drop packet */
2909 rxi_ClearTransmitQueue(call, 0);
2911 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2912 rxi_ClearTransmitQueue(call, 0);
2913 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2915 if (np->header.type == RX_PACKET_TYPE_ACK) {
2916 /* now check to see if this is an ack packet acknowledging that the
2917 * server actually *lost* some hard-acked data. If this happens we
2918 * ignore this packet, as it may indicate that the server restarted in
2919 * the middle of a call. It is also possible that this is an old ack
2920 * packet. We don't abort the connection in this case, because this
2921 * *might* just be an old ack packet. The right way to detect a server
2922 * restart in the midst of a call is to notice that the server epoch
2924 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2925 * XXX unacknowledged. I think that this is off-by-one, but
2926 * XXX I don't dare change it just yet, since it will
2927 * XXX interact badly with the server-restart detection
2928 * XXX code in receiveackpacket. */
2929 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2930 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2931 MUTEX_EXIT(&call->lock);
2932 MUTEX_ENTER(&conn->conn_data_lock);
2934 MUTEX_EXIT(&conn->conn_data_lock);
2938 } /* else not a data packet */
2941 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2942 /* Set remote user defined status from packet */
2943 call->remoteStatus = np->header.userStatus;
2945 /* Note the gap between the expected next packet and the actual
2946 * packet that arrived, when the new packet has a smaller serial number
2947 * than expected. Rioses frequently reorder packets all by themselves,
2948 * so this will be quite important with very large window sizes.
2949 * Skew is checked against 0 here to avoid any dependence on the type of
2950 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2952 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2953 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2954 * I think using a beta of 1/8 is probably appropriate. 93.04.21
2956 MUTEX_ENTER(&conn->conn_data_lock);
2957 skew = conn->lastSerial - np->header.serial;
2958 conn->lastSerial = np->header.serial;
2959 MUTEX_EXIT(&conn->conn_data_lock);
2961 register struct rx_peer *peer;
2963 if (skew > peer->inPacketSkew) {
2964 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
2966 peer->inPacketSkew = skew;
2970 /* Now do packet type-specific processing */
2971 switch (np->header.type) {
2972 case RX_PACKET_TYPE_DATA:
2973 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
2976 case RX_PACKET_TYPE_ACK:
2977 /* Respond immediately to ack packets requesting acknowledgement
2979 if (np->header.flags & RX_REQUEST_ACK) {
2981 (void)rxi_SendCallAbort(call, 0, 1, 0);
2983 (void)rxi_SendAck(call, 0, np->header.serial,
2984 RX_ACK_PING_RESPONSE, 1);
2986 np = rxi_ReceiveAckPacket(call, np, 1);
2988 case RX_PACKET_TYPE_ABORT: {
2989 /* An abort packet: reset the call, passing the error up to the user. */
2990 /* What if error is zero? */
2991 /* What if the error is -1? the application will treat it as a timeout. */
2992 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
2993 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
2994 rxi_CallError(call, errdata);
2995 MUTEX_EXIT(&call->lock);
2996 MUTEX_ENTER(&conn->conn_data_lock);
2998 MUTEX_EXIT(&conn->conn_data_lock);
2999 return np; /* xmitting; drop packet */
3001 case RX_PACKET_TYPE_BUSY:
3004 case RX_PACKET_TYPE_ACKALL:
3005 /* All packets acknowledged, so we can drop all packets previously
3006 * readied for sending */
3007 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3008 /* XXX Hack. We because we can't release the global rx lock when
3009 * sending packets (osi_NetSend) we drop all ack pkts while we're
3010 * traversing the tq in rxi_Start sending packets out because
3011 * packets may move to the freePacketQueue as result of being
3012 * here! So we drop these packets until we're safely out of the
3013 * traversing. Really ugly!
3014 * For fine grain RX locking, we set the acked field in the packets
3015 * and let rxi_Start remove the packets from the transmit queue.
3017 if (call->flags & RX_CALL_TQ_BUSY) {
3018 #ifdef RX_ENABLE_LOCKS
3019 rxi_SetAcksInTransmitQueue(call);
3021 #else /* RX_ENABLE_LOCKS */
3022 MUTEX_EXIT(&call->lock);
3023 MUTEX_ENTER(&conn->conn_data_lock);
3025 MUTEX_EXIT(&conn->conn_data_lock);
3026 return np; /* xmitting; drop packet */
3027 #endif /* RX_ENABLE_LOCKS */
3029 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3030 rxi_ClearTransmitQueue(call, 0);
3031 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3034 /* Should not reach here, unless the peer is broken: send an abort
3036 rxi_CallError(call, RX_PROTOCOL_ERROR);
3037 np = rxi_SendCallAbort(call, np, 1, 0);
3040 /* Note when this last legitimate packet was received, for keep-alive
3041 * processing. Note, we delay getting the time until now in the hope that
3042 * the packet will be delivered to the user before any get time is required
3043 * (if not, then the time won't actually be re-evaluated here). */
3044 call->lastReceiveTime = clock_Sec();
3045 MUTEX_EXIT(&call->lock);
3046 MUTEX_ENTER(&conn->conn_data_lock);
3048 MUTEX_EXIT(&conn->conn_data_lock);
3052 /* return true if this is an "interesting" connection from the point of view
3053 of someone trying to debug the system */
3055 rxi_IsConnInteresting(struct rx_connection *aconn)
3058 register struct rx_call *tcall;
3060 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3062 for (i = 0; i < RX_MAXCALLS; i++) {
3063 tcall = aconn->call[i];
3065 if ((tcall->state == RX_STATE_PRECALL)
3066 || (tcall->state == RX_STATE_ACTIVE))
3068 if ((tcall->mode == RX_MODE_SENDING)
3069 || (tcall->mode == RX_MODE_RECEIVING))
3077 /* if this is one of the last few packets AND it wouldn't be used by the
3078 receiving call to immediately satisfy a read request, then drop it on
3079 the floor, since accepting it might prevent a lock-holding thread from
3080 making progress in its reading. If a call has been cleared while in
3081 the precall state then ignore all subsequent packets until the call
3082 is assigned to a thread. */
3085 TooLow(struct rx_packet *ap, struct rx_call *acall)
3088 MUTEX_ENTER(&rx_stats_mutex);
3089 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3090 && (acall->state == RX_STATE_PRECALL))
3091 || ((rx_nFreePackets < rxi_dataQuota + 2)
3092 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3093 && (acall->flags & RX_CALL_READER_WAIT)))) {
3096 MUTEX_EXIT(&rx_stats_mutex);
3102 rxi_CheckReachEvent(struct rxevent *event, struct rx_connection *conn,
3103 struct rx_call *acall)
3105 struct rx_call *call = acall;
3106 struct clock when, now;
3109 MUTEX_ENTER(&conn->conn_data_lock);
3110 conn->checkReachEvent = NULL;
3111 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3114 MUTEX_EXIT(&conn->conn_data_lock);
3118 MUTEX_ENTER(&conn->conn_call_lock);
3119 MUTEX_ENTER(&conn->conn_data_lock);
3120 for (i = 0; i < RX_MAXCALLS; i++) {
3121 struct rx_call *tc = conn->call[i];
3122 if (tc && tc->state == RX_STATE_PRECALL) {
3128 /* Indicate that rxi_CheckReachEvent is no longer running by
3129 * clearing the flag. Must be atomic under conn_data_lock to
3130 * avoid a new call slipping by: rxi_CheckConnReach holds
3131 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3133 conn->flags &= ~RX_CONN_ATTACHWAIT;
3134 MUTEX_EXIT(&conn->conn_data_lock);
3135 MUTEX_EXIT(&conn->conn_call_lock);
3140 MUTEX_ENTER(&call->lock);
3141 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3143 MUTEX_EXIT(&call->lock);
3145 clock_GetTime(&now);
3147 when.sec += RX_CHECKREACH_TIMEOUT;
3148 MUTEX_ENTER(&conn->conn_data_lock);
3149 if (!conn->checkReachEvent) {
3151 conn->checkReachEvent =
3152 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3155 MUTEX_EXIT(&conn->conn_data_lock);
3161 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3163 struct rx_service *service = conn->service;
3164 struct rx_peer *peer = conn->peer;
3165 afs_uint32 now, lastReach;
3167 if (service->checkReach == 0)
3171 MUTEX_ENTER(&peer->peer_lock);
3172 lastReach = peer->lastReachTime;
3173 MUTEX_EXIT(&peer->peer_lock);
3174 if (now - lastReach < RX_CHECKREACH_TTL)
3177 MUTEX_ENTER(&conn->conn_data_lock);
3178 if (conn->flags & RX_CONN_ATTACHWAIT) {
3179 MUTEX_EXIT(&conn->conn_data_lock);
3182 conn->flags |= RX_CONN_ATTACHWAIT;
3183 MUTEX_EXIT(&conn->conn_data_lock);
3184 if (!conn->checkReachEvent)
3185 rxi_CheckReachEvent(NULL, conn, call);
3190 /* try to attach call, if authentication is complete */
3192 TryAttach(register struct rx_call *acall, register osi_socket socket,
3193 register int *tnop, register struct rx_call **newcallp,
3196 struct rx_connection *conn = acall->conn;
3198 if (conn->type == RX_SERVER_CONNECTION
3199 && acall->state == RX_STATE_PRECALL) {
3200 /* Don't attach until we have any req'd. authentication. */
3201 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3202 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3203 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3204 /* Note: this does not necessarily succeed; there
3205 * may not any proc available
3208 rxi_ChallengeOn(acall->conn);
3213 /* A data packet has been received off the interface. This packet is
3214 * appropriate to the call (the call is in the right state, etc.). This
3215 * routine can return a packet to the caller, for re-use */
3218 rxi_ReceiveDataPacket(register struct rx_call *call,
3219 register struct rx_packet *np, int istack,
3220 osi_socket socket, afs_uint32 host, u_short port,
3221 int *tnop, struct rx_call **newcallp)
3223 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3227 afs_uint32 seq, serial, flags;
3229 struct rx_packet *tnp;
3230 struct clock when, now;
3231 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3234 /* If there are no packet buffers, drop this new packet, unless we can find
3235 * packet buffers from inactive calls */
3237 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3238 MUTEX_ENTER(&rx_freePktQ_lock);
3239 rxi_NeedMorePackets = TRUE;
3240 MUTEX_EXIT(&rx_freePktQ_lock);
3241 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3242 call->rprev = np->header.serial;
3243 rxi_calltrace(RX_TRACE_DROP, call);
3244 dpf(("packet %x dropped on receipt - quota problems", np));
3246 rxi_ClearReceiveQueue(call);
3247 clock_GetTime(&now);
3249 clock_Add(&when, &rx_softAckDelay);
3250 if (!call->delayedAckEvent
3251 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3252 rxevent_Cancel(call->delayedAckEvent, call,
3253 RX_CALL_REFCOUNT_DELAY);
3254 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3255 call->delayedAckEvent =
3256 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3258 /* we've damaged this call already, might as well do it in. */
3264 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3265 * packet is one of several packets transmitted as a single
3266 * datagram. Do not send any soft or hard acks until all packets
3267 * in a jumbogram have been processed. Send negative acks right away.
3269 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3270 /* tnp is non-null when there are more packets in the
3271 * current jumbo gram */
3278 seq = np->header.seq;
3279 serial = np->header.serial;
3280 flags = np->header.flags;
3282 /* If the call is in an error state, send an abort message */
3284 return rxi_SendCallAbort(call, np, istack, 0);
3286 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3287 * AFS 3.5 jumbogram. */
3288 if (flags & RX_JUMBO_PACKET) {
3289 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3294 if (np->header.spare != 0) {
3295 MUTEX_ENTER(&call->conn->conn_data_lock);
3296 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3297 MUTEX_EXIT(&call->conn->conn_data_lock);
3300 /* The usual case is that this is the expected next packet */
3301 if (seq == call->rnext) {
3303 /* Check to make sure it is not a duplicate of one already queued */
3304 if (queue_IsNotEmpty(&call->rq)
3305 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3306 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3307 dpf(("packet %x dropped on receipt - duplicate", np));
3308 rxevent_Cancel(call->delayedAckEvent, call,
3309 RX_CALL_REFCOUNT_DELAY);
3310 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3316 /* It's the next packet. Stick it on the receive queue
3317 * for this call. Set newPackets to make sure we wake
3318 * the reader once all packets have been processed */
3319 queue_Prepend(&call->rq, np);
3321 np = NULL; /* We can't use this anymore */
3324 /* If an ack is requested then set a flag to make sure we
3325 * send an acknowledgement for this packet */
3326 if (flags & RX_REQUEST_ACK) {
3327 ackNeeded = RX_ACK_REQUESTED;
3330 /* Keep track of whether we have received the last packet */
3331 if (flags & RX_LAST_PACKET) {
3332 call->flags |= RX_CALL_HAVE_LAST;
3336 /* Check whether we have all of the packets for this call */
3337 if (call->flags & RX_CALL_HAVE_LAST) {
3338 afs_uint32 tseq; /* temporary sequence number */
3339 struct rx_packet *tp; /* Temporary packet pointer */
3340 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3342 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3343 if (tseq != tp->header.seq)
3345 if (tp->header.flags & RX_LAST_PACKET) {
3346 call->flags |= RX_CALL_RECEIVE_DONE;
3353 /* Provide asynchronous notification for those who want it
3354 * (e.g. multi rx) */
3355 if (call->arrivalProc) {
3356 (*call->arrivalProc) (call, call->arrivalProcHandle,
3357 call->arrivalProcArg);
3358 call->arrivalProc = (void (*)())0;
3361 /* Update last packet received */
3364 /* If there is no server process serving this call, grab
3365 * one, if available. We only need to do this once. If a
3366 * server thread is available, this thread becomes a server
3367 * thread and the server thread becomes a listener thread. */
3369 TryAttach(call, socket, tnop, newcallp, 0);
3372 /* This is not the expected next packet. */
3374 /* Determine whether this is a new or old packet, and if it's
3375 * a new one, whether it fits into the current receive window.
3376 * Also figure out whether the packet was delivered in sequence.
3377 * We use the prev variable to determine whether the new packet
3378 * is the successor of its immediate predecessor in the
3379 * receive queue, and the missing flag to determine whether
3380 * any of this packets predecessors are missing. */
3382 afs_uint32 prev; /* "Previous packet" sequence number */
3383 struct rx_packet *tp; /* Temporary packet pointer */
3384 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3385 int missing; /* Are any predecessors missing? */
3387 /* If the new packet's sequence number has been sent to the
3388 * application already, then this is a duplicate */
3389 if (seq < call->rnext) {
3390 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3391 rxevent_Cancel(call->delayedAckEvent, call,
3392 RX_CALL_REFCOUNT_DELAY);
3393 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3399 /* If the sequence number is greater than what can be
3400 * accomodated by the current window, then send a negative
3401 * acknowledge and drop the packet */
3402 if ((call->rnext + call->rwind) <= seq) {
3403 rxevent_Cancel(call->delayedAckEvent, call,
3404 RX_CALL_REFCOUNT_DELAY);
3405 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3412 /* Look for the packet in the queue of old received packets */
3413 for (prev = call->rnext - 1, missing =
3414 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3415 /*Check for duplicate packet */
3416 if (seq == tp->header.seq) {
3417 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3418 rxevent_Cancel(call->delayedAckEvent, call,
3419 RX_CALL_REFCOUNT_DELAY);
3420 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3426 /* If we find a higher sequence packet, break out and
3427 * insert the new packet here. */
3428 if (seq < tp->header.seq)
3430 /* Check for missing packet */
3431 if (tp->header.seq != prev + 1) {
3435 prev = tp->header.seq;
3438 /* Keep track of whether we have received the last packet. */
3439 if (flags & RX_LAST_PACKET) {
3440 call->flags |= RX_CALL_HAVE_LAST;
3443 /* It's within the window: add it to the the receive queue.
3444 * tp is left by the previous loop either pointing at the
3445 * packet before which to insert the new packet, or at the
3446 * queue head if the queue is empty or the packet should be
3448 queue_InsertBefore(tp, np);
3452 /* Check whether we have all of the packets for this call */
3453 if ((call->flags & RX_CALL_HAVE_LAST)
3454 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3455 afs_uint32 tseq; /* temporary sequence number */
3458 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3459 if (tseq != tp->header.seq)
3461 if (tp->header.flags & RX_LAST_PACKET) {
3462 call->flags |= RX_CALL_RECEIVE_DONE;
3469 /* We need to send an ack of the packet is out of sequence,
3470 * or if an ack was requested by the peer. */
3471 if (seq != prev + 1 || missing) {
3472 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3473 } else if (flags & RX_REQUEST_ACK) {
3474 ackNeeded = RX_ACK_REQUESTED;
3477 /* Acknowledge the last packet for each call */
3478 if (flags & RX_LAST_PACKET) {
3489 * If the receiver is waiting for an iovec, fill the iovec
3490 * using the data from the receive queue */
3491 if (call->flags & RX_CALL_IOVEC_WAIT) {
3492 didHardAck = rxi_FillReadVec(call, serial);
3493 /* the call may have been aborted */
3502 /* Wakeup the reader if any */
3503 if ((call->flags & RX_CALL_READER_WAIT)
3504 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3505 || (call->iovNext >= call->iovMax)
3506 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3507 call->flags &= ~RX_CALL_READER_WAIT;
3508 #ifdef RX_ENABLE_LOCKS
3509 CV_BROADCAST(&call->cv_rq);
3511 osi_rxWakeup(&call->rq);
3517 * Send an ack when requested by the peer, or once every
3518 * rxi_SoftAckRate packets until the last packet has been
3519 * received. Always send a soft ack for the last packet in
3520 * the server's reply. */
3522 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3523 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3524 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3525 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3526 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3527 } else if (call->nSoftAcks) {
3528 clock_GetTime(&now);
3530 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3531 clock_Add(&when, &rx_lastAckDelay);
3533 clock_Add(&when, &rx_softAckDelay);
3535 if (!call->delayedAckEvent
3536 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3537 rxevent_Cancel(call->delayedAckEvent, call,
3538 RX_CALL_REFCOUNT_DELAY);
3539 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3540 call->delayedAckEvent =
3541 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3543 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3544 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3551 static void rxi_ComputeRate();
3555 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3557 struct rx_peer *peer = conn->peer;
3559 MUTEX_ENTER(&peer->peer_lock);
3560 peer->lastReachTime = clock_Sec();
3561 MUTEX_EXIT(&peer->peer_lock);
3563 MUTEX_ENTER(&conn->conn_data_lock);
3564 if (conn->flags & RX_CONN_ATTACHWAIT) {
3567 conn->flags &= ~RX_CONN_ATTACHWAIT;
3568 MUTEX_EXIT(&conn->conn_data_lock);
3570 for (i = 0; i < RX_MAXCALLS; i++) {
3571 struct rx_call *call = conn->call[i];
3574 MUTEX_ENTER(&call->lock);
3575 /* tnop can be null if newcallp is null */
3576 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3578 MUTEX_EXIT(&call->lock);
3582 MUTEX_EXIT(&conn->conn_data_lock);
3586 rx_ack_reason(int reason)
3589 case RX_ACK_REQUESTED:
3591 case RX_ACK_DUPLICATE:
3593 case RX_ACK_OUT_OF_SEQUENCE:
3595 case RX_ACK_EXCEEDS_WINDOW:
3597 case RX_ACK_NOSPACE:
3601 case RX_ACK_PING_RESPONSE:
3613 /* rxi_ComputePeerNetStats
3615 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3616 * estimates (like RTT and throughput) based on ack packets. Caller
3617 * must ensure that the packet in question is the right one (i.e.
3618 * serial number matches).
3621 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3622 struct rx_ackPacket *ap, struct rx_packet *np)
3624 struct rx_peer *peer = call->conn->peer;
3626 /* Use RTT if not delayed by client. */
3627 if (ap->reason != RX_ACK_DELAY)
3628 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3630 rxi_ComputeRate(peer, call, p, np, ap->reason);
3634 /* The real smarts of the whole thing. */
3636 rxi_ReceiveAckPacket(register struct rx_call *call, struct rx_packet *np,
3639 struct rx_ackPacket *ap;
3641 register struct rx_packet *tp;
3642 register struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3643 register struct rx_connection *conn = call->conn;
3644 struct rx_peer *peer = conn->peer;
3647 /* because there are CM's that are bogus, sending weird values for this. */
3648 afs_uint32 skew = 0;
3653 int newAckCount = 0;
3654 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3655 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3657 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3658 ap = (struct rx_ackPacket *)rx_DataOf(np);
3659 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3661 return np; /* truncated ack packet */
3663 /* depends on ack packet struct */
3664 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3665 first = ntohl(ap->firstPacket);
3666 serial = ntohl(ap->serial);
3667 /* temporarily disabled -- needs to degrade over time
3668 * skew = ntohs(ap->maxSkew); */
3670 /* Ignore ack packets received out of order */
3671 if (first < call->tfirst) {
3675 if (np->header.flags & RX_SLOW_START_OK) {
3676 call->flags |= RX_CALL_SLOW_START_OK;
3679 if (ap->reason == RX_ACK_PING_RESPONSE)
3680 rxi_UpdatePeerReach(conn, call);
3684 if (rxdebug_active) {
3688 len = _snprintf(msg, sizeof(msg),
3689 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3690 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3691 ntohl(ap->serial), ntohl(ap->previousPacket),
3692 (unsigned int)np->header.seq, (unsigned int)skew,
3693 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3697 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3698 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3702 OutputDebugString(msg);
3704 #else /* AFS_NT40_ENV */
3707 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3708 ap->reason, ntohl(ap->previousPacket),
3709 (unsigned int)np->header.seq, (unsigned int)serial,
3710 (unsigned int)skew, ntohl(ap->firstPacket));
3713 for (offset = 0; offset < nAcks; offset++)
3714 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3719 #endif /* AFS_NT40_ENV */
3722 /* Update the outgoing packet skew value to the latest value of
3723 * the peer's incoming packet skew value. The ack packet, of
3724 * course, could arrive out of order, but that won't affect things
3726 MUTEX_ENTER(&peer->peer_lock);
3727 peer->outPacketSkew = skew;
3729 /* Check for packets that no longer need to be transmitted, and
3730 * discard them. This only applies to packets positively
3731 * acknowledged as having been sent to the peer's upper level.
3732 * All other packets must be retained. So only packets with
3733 * sequence numbers < ap->firstPacket are candidates. */
3734 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3735 if (tp->header.seq >= first)
3737 call->tfirst = tp->header.seq + 1;
3739 && (tp->header.serial == serial || tp->firstSerial == serial))
3740 rxi_ComputePeerNetStats(call, tp, ap, np);
3741 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3744 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3745 /* XXX Hack. Because we have to release the global rx lock when sending
3746 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3747 * in rxi_Start sending packets out because packets may move to the
3748 * freePacketQueue as result of being here! So we drop these packets until
3749 * we're safely out of the traversing. Really ugly!
3750 * To make it even uglier, if we're using fine grain locking, we can
3751 * set the ack bits in the packets and have rxi_Start remove the packets
3752 * when it's done transmitting.
3754 if (call->flags & RX_CALL_TQ_BUSY) {
3755 #ifdef RX_ENABLE_LOCKS
3756 tp->flags |= RX_PKTFLAG_ACKED;
3757 call->flags |= RX_CALL_TQ_SOME_ACKED;
3758 #else /* RX_ENABLE_LOCKS */
3760 #endif /* RX_ENABLE_LOCKS */
3762 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3765 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3770 /* Give rate detector a chance to respond to ping requests */
3771 if (ap->reason == RX_ACK_PING_RESPONSE) {
3772 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3776 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3778 /* Now go through explicit acks/nacks and record the results in
3779 * the waiting packets. These are packets that can't be released
3780 * yet, even with a positive acknowledge. This positive
3781 * acknowledge only means the packet has been received by the
3782 * peer, not that it will be retained long enough to be sent to
3783 * the peer's upper level. In addition, reset the transmit timers
3784 * of any missing packets (those packets that must be missing
3785 * because this packet was out of sequence) */
3787 call->nSoftAcked = 0;
3788 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3789 /* Update round trip time if the ack was stimulated on receipt
3791 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3792 #ifdef RX_ENABLE_LOCKS
3793 if (tp->header.seq >= first)
3794 #endif /* RX_ENABLE_LOCKS */
3795 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3797 && (tp->header.serial == serial || tp->firstSerial == serial))
3798 rxi_ComputePeerNetStats(call, tp, ap, np);
3800 /* Set the acknowledge flag per packet based on the
3801 * information in the ack packet. An acknowlegded packet can
3802 * be downgraded when the server has discarded a packet it
3803 * soacked previously, or when an ack packet is received
3804 * out of sequence. */
3805 if (tp->header.seq < first) {
3806 /* Implicit ack information */
3807 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3810 tp->flags |= RX_PKTFLAG_ACKED;
3811 } else if (tp->header.seq < first + nAcks) {
3812 /* Explicit ack information: set it in the packet appropriately */
3813 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3814 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3816 tp->flags |= RX_PKTFLAG_ACKED;
3823 } else /* RX_ACK_TYPE_NACK */ {
3824 tp->flags &= ~RX_PKTFLAG_ACKED;
3828 tp->flags &= ~RX_PKTFLAG_ACKED;
3832 /* If packet isn't yet acked, and it has been transmitted at least
3833 * once, reset retransmit time using latest timeout
3834 * ie, this should readjust the retransmit timer for all outstanding
3835 * packets... So we don't just retransmit when we should know better*/
3837 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3838 tp->retryTime = tp->timeSent;
3839 clock_Add(&tp->retryTime, &peer->timeout);
3840 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3841 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3845 /* If the window has been extended by this acknowledge packet,
3846 * then wakeup a sender waiting in alloc for window space, or try
3847 * sending packets now, if he's been sitting on packets due to
3848 * lack of window space */
3849 if (call->tnext < (call->tfirst + call->twind)) {
3850 #ifdef RX_ENABLE_LOCKS
3851 CV_SIGNAL(&call->cv_twind);
3853 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3854 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3855 osi_rxWakeup(&call->twind);
3858 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3859 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3863 /* if the ack packet has a receivelen field hanging off it,
3864 * update our state */
3865 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3868 /* If the ack packet has a "recommended" size that is less than
3869 * what I am using now, reduce my size to match */
3870 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3871 (int)sizeof(afs_int32), &tSize);
3872 tSize = (afs_uint32) ntohl(tSize);
3873 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3875 /* Get the maximum packet size to send to this peer */
3876 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3878 tSize = (afs_uint32) ntohl(tSize);
3879 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3880 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3882 /* sanity check - peer might have restarted with different params.
3883 * If peer says "send less", dammit, send less... Peer should never
3884 * be unable to accept packets of the size that prior AFS versions would
3885 * send without asking. */
3886 if (peer->maxMTU != tSize) {
3887 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3889 peer->maxMTU = tSize;
3890 peer->MTU = MIN(tSize, peer->MTU);
3891 call->MTU = MIN(call->MTU, tSize);
3894 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3897 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3898 (int)sizeof(afs_int32), &tSize);
3899 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3900 if (tSize < call->twind) { /* smaller than our send */
3901 call->twind = tSize; /* window, we must send less... */
3902 call->ssthresh = MIN(call->twind, call->ssthresh);
3903 call->conn->twind[call->channel] = call->twind;
3906 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3907 * network MTU confused with the loopback MTU. Calculate the
3908 * maximum MTU here for use in the slow start code below.
3910 maxMTU = peer->maxMTU;
3911 /* Did peer restart with older RX version? */
3912 if (peer->maxDgramPackets > 1) {
3913 peer->maxDgramPackets = 1;
3915 } else if (np->length >=
3916 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3919 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3920 sizeof(afs_int32), &tSize);
3921 tSize = (afs_uint32) ntohl(tSize);
3923 * As of AFS 3.5 we set the send window to match the receive window.
3925 if (tSize < call->twind) {
3926 call->twind = tSize;
3927 call->conn->twind[call->channel] = call->twind;
3928 call->ssthresh = MIN(call->twind, call->ssthresh);
3929 } else if (tSize > call->twind) {
3930 call->twind = tSize;
3931 call->conn->twind[call->channel] = call->twind;
3935 * As of AFS 3.5, a jumbogram is more than one fixed size
3936 * packet transmitted in a single UDP datagram. If the remote
3937 * MTU is smaller than our local MTU then never send a datagram
3938 * larger than the natural MTU.
3941 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
3942 sizeof(afs_int32), &tSize);
3943 maxDgramPackets = (afs_uint32) ntohl(tSize);
3944 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
3945 maxDgramPackets = MIN(maxDgramPackets, peer->ifDgramPackets);
3946 if (peer->natMTU < peer->ifMTU)
3947 maxDgramPackets = MIN(maxDgramPackets, rxi_AdjustDgramPackets(1, peer->natMTU));
3948 if (maxDgramPackets > 1) {
3949 peer->maxDgramPackets = maxDgramPackets;
3950 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
3952 peer->maxDgramPackets = 1;
3953 call->MTU = peer->natMTU;
3955 } else if (peer->maxDgramPackets > 1) {
3956 /* Restarted with lower version of RX */
3957 peer->maxDgramPackets = 1;
3959 } else if (peer->maxDgramPackets > 1
3960 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
3961 /* Restarted with lower version of RX */
3962 peer->maxMTU = OLD_MAX_PACKET_SIZE;
3963 peer->natMTU = OLD_MAX_PACKET_SIZE;
3964 peer->MTU = OLD_MAX_PACKET_SIZE;
3965 peer->maxDgramPackets = 1;
3966 peer->nDgramPackets = 1;
3968 call->MTU = OLD_MAX_PACKET_SIZE;
3973 * Calculate how many datagrams were successfully received after
3974 * the first missing packet and adjust the negative ack counter
3979 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
3980 if (call->nNacks < nNacked) {
3981 call->nNacks = nNacked;
3984 call->nAcks += newAckCount;
3988 if (call->flags & RX_CALL_FAST_RECOVER) {
3990 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
3992 call->flags &= ~RX_CALL_FAST_RECOVER;
3993 call->cwind = call->nextCwind;
3994 call->nextCwind = 0;
3997 call->nCwindAcks = 0;
3998 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
3999 /* Three negative acks in a row trigger congestion recovery */
4000 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4001 MUTEX_EXIT(&peer->peer_lock);
4002 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4003 /* someone else is waiting to start recovery */
4006 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4007 rxi_WaitforTQBusy(call);
4008 MUTEX_ENTER(&peer->peer_lock);
4009 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4010 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4011 call->flags |= RX_CALL_FAST_RECOVER;
4012 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4014 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4015 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4016 call->nextCwind = call->ssthresh;
4019 peer->MTU = call->MTU;
4020 peer->cwind = call->nextCwind;
4021 peer->nDgramPackets = call->nDgramPackets;
4023 call->congestSeq = peer->congestSeq;
4024 /* Reset the resend times on the packets that were nacked
4025 * so we will retransmit as soon as the window permits*/
4026 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4028 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4029 clock_Zero(&tp->retryTime);
4031 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4036 /* If cwind is smaller than ssthresh, then increase
4037 * the window one packet for each ack we receive (exponential
4039 * If cwind is greater than or equal to ssthresh then increase
4040 * the congestion window by one packet for each cwind acks we
4041 * receive (linear growth). */
4042 if (call->cwind < call->ssthresh) {
4044 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4045 call->nCwindAcks = 0;
4047 call->nCwindAcks += newAckCount;
4048 if (call->nCwindAcks >= call->cwind) {
4049 call->nCwindAcks = 0;
4050 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4054 * If we have received several acknowledgements in a row then
4055 * it is time to increase the size of our datagrams
4057 if ((int)call->nAcks > rx_nDgramThreshold) {
4058 if (peer->maxDgramPackets > 1) {
4059 if (call->nDgramPackets < peer->maxDgramPackets) {
4060 call->nDgramPackets++;
4062 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4063 } else if (call->MTU < peer->maxMTU) {
4064 call->MTU += peer->natMTU;
4065 call->MTU = MIN(call->MTU, peer->maxMTU);
4071 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4073 /* Servers need to hold the call until all response packets have
4074 * been acknowledged. Soft acks are good enough since clients
4075 * are not allowed to clear their receive queues. */
4076 if (call->state == RX_STATE_HOLD
4077 && call->tfirst + call->nSoftAcked >= call->tnext) {
4078 call->state = RX_STATE_DALLY;
4079 rxi_ClearTransmitQueue(call, 0);
4080 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4081 } else if (!queue_IsEmpty(&call->tq)) {
4082 rxi_Start(0, call, 0, istack);
4087 /* Received a response to a challenge packet */
4089 rxi_ReceiveResponsePacket(register struct rx_connection *conn,
4090 register struct rx_packet *np, int istack)
4094 /* Ignore the packet if we're the client */
4095 if (conn->type == RX_CLIENT_CONNECTION)
4098 /* If already authenticated, ignore the packet (it's probably a retry) */
4099 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4102 /* Otherwise, have the security object evaluate the response packet */
4103 error = RXS_CheckResponse(conn->securityObject, conn, np);
4105 /* If the response is invalid, reset the connection, sending
4106 * an abort to the peer */
4110 rxi_ConnectionError(conn, error);
4111 MUTEX_ENTER(&conn->conn_data_lock);
4112 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4113 MUTEX_EXIT(&conn->conn_data_lock);
4116 /* If the response is valid, any calls waiting to attach
4117 * servers can now do so */
4120 for (i = 0; i < RX_MAXCALLS; i++) {
4121 struct rx_call *call = conn->call[i];
4123 MUTEX_ENTER(&call->lock);
4124 if (call->state == RX_STATE_PRECALL)
4125 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4126 /* tnop can be null if newcallp is null */
4127 MUTEX_EXIT(&call->lock);
4131 /* Update the peer reachability information, just in case
4132 * some calls went into attach-wait while we were waiting
4133 * for authentication..
4135 rxi_UpdatePeerReach(conn, NULL);
4140 /* A client has received an authentication challenge: the security
4141 * object is asked to cough up a respectable response packet to send
4142 * back to the server. The server is responsible for retrying the
4143 * challenge if it fails to get a response. */
4146 rxi_ReceiveChallengePacket(register struct rx_connection *conn,
4147 register struct rx_packet *np, int istack)
4151 /* Ignore the challenge if we're the server */
4152 if (conn->type == RX_SERVER_CONNECTION)
4155 /* Ignore the challenge if the connection is otherwise idle; someone's
4156 * trying to use us as an oracle. */
4157 if (!rxi_HasActiveCalls(conn))
4160 /* Send the security object the challenge packet. It is expected to fill
4161 * in the response. */
4162 error = RXS_GetResponse(conn->securityObject, conn, np);
4164 /* If the security object is unable to return a valid response, reset the
4165 * connection and send an abort to the peer. Otherwise send the response
4166 * packet to the peer connection. */
4168 rxi_ConnectionError(conn, error);
4169 MUTEX_ENTER(&conn->conn_data_lock);
4170 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4171 MUTEX_EXIT(&conn->conn_data_lock);
4173 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4174 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4180 /* Find an available server process to service the current request in
4181 * the given call structure. If one isn't available, queue up this
4182 * call so it eventually gets one */
4184 rxi_AttachServerProc(register struct rx_call *call,
4185 register osi_socket socket, register int *tnop,
4186 register struct rx_call **newcallp)
4188 register struct rx_serverQueueEntry *sq;
4189 register struct rx_service *service = call->conn->service;
4190 register int haveQuota = 0;
4192 /* May already be attached */
4193 if (call->state == RX_STATE_ACTIVE)
4196 MUTEX_ENTER(&rx_serverPool_lock);
4198 haveQuota = QuotaOK(service);
4199 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4200 /* If there are no processes available to service this call,
4201 * put the call on the incoming call queue (unless it's
4202 * already on the queue).
4204 #ifdef RX_ENABLE_LOCKS
4206 ReturnToServerPool(service);
4207 #endif /* RX_ENABLE_LOCKS */
4209 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4210 call->flags |= RX_CALL_WAIT_PROC;
4211 MUTEX_ENTER(&rx_stats_mutex);
4214 MUTEX_EXIT(&rx_stats_mutex);
4215 rxi_calltrace(RX_CALL_ARRIVAL, call);
4216 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4217 queue_Append(&rx_incomingCallQueue, call);
4220 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4222 /* If hot threads are enabled, and both newcallp and sq->socketp
4223 * are non-null, then this thread will process the call, and the
4224 * idle server thread will start listening on this threads socket.
4227 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4230 *sq->socketp = socket;
4231 clock_GetTime(&call->startTime);
4232 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4236 if (call->flags & RX_CALL_WAIT_PROC) {
4237 /* Conservative: I don't think this should happen */
4238 call->flags &= ~RX_CALL_WAIT_PROC;
4239 if (queue_IsOnQueue(call)) {
4241 MUTEX_ENTER(&rx_stats_mutex);
4243 MUTEX_EXIT(&rx_stats_mutex);
4246 call->state = RX_STATE_ACTIVE;
4247 call->mode = RX_MODE_RECEIVING;
4248 #ifdef RX_KERNEL_TRACE
4250 int glockOwner = ISAFS_GLOCK();
4253 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4254 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4260 if (call->flags & RX_CALL_CLEARED) {
4261 /* send an ack now to start the packet flow up again */
4262 call->flags &= ~RX_CALL_CLEARED;
4263 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4265 #ifdef RX_ENABLE_LOCKS
4268 service->nRequestsRunning++;
4269 if (service->nRequestsRunning <= service->minProcs)
4275 MUTEX_EXIT(&rx_serverPool_lock);
4278 /* Delay the sending of an acknowledge event for a short while, while
4279 * a new call is being prepared (in the case of a client) or a reply
4280 * is being prepared (in the case of a server). Rather than sending
4281 * an ack packet, an ACKALL packet is sent. */
4283 rxi_AckAll(struct rxevent *event, register struct rx_call *call, char *dummy)
4285 #ifdef RX_ENABLE_LOCKS
4287 MUTEX_ENTER(&call->lock);
4288 call->delayedAckEvent = NULL;
4289 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4291 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4292 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4294 MUTEX_EXIT(&call->lock);
4295 #else /* RX_ENABLE_LOCKS */
4297 call->delayedAckEvent = NULL;
4298 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4299 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4300 #endif /* RX_ENABLE_LOCKS */
4304 rxi_SendDelayedAck(struct rxevent *event, register struct rx_call *call,
4307 #ifdef RX_ENABLE_LOCKS
4309 MUTEX_ENTER(&call->lock);
4310 if (event == call->delayedAckEvent)
4311 call->delayedAckEvent = NULL;
4312 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4314 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4316 MUTEX_EXIT(&call->lock);
4317 #else /* RX_ENABLE_LOCKS */
4319 call->delayedAckEvent = NULL;
4320 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4321 #endif /* RX_ENABLE_LOCKS */
4325 #ifdef RX_ENABLE_LOCKS
4326 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4327 * clearing them out.
4330 rxi_SetAcksInTransmitQueue(register struct rx_call *call)
4332 register struct rx_packet *p, *tp;
4335 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4336 p->flags |= RX_PKTFLAG_ACKED;
4340 call->flags |= RX_CALL_TQ_CLEARME;
4341 call->flags |= RX_CALL_TQ_SOME_ACKED;
4344 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4345 call->tfirst = call->tnext;
4346 call->nSoftAcked = 0;
4348 if (call->flags & RX_CALL_FAST_RECOVER) {
4349 call->flags &= ~RX_CALL_FAST_RECOVER;
4350 call->cwind = call->nextCwind;
4351 call->nextCwind = 0;
4354 CV_SIGNAL(&call->cv_twind);
4356 #endif /* RX_ENABLE_LOCKS */
4358 /* Clear out the transmit queue for the current call (all packets have
4359 * been received by peer) */
4361 rxi_ClearTransmitQueue(register struct rx_call *call, register int force)
4363 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4364 register struct rx_packet *p, *tp;
4366 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4368 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4369 p->flags |= RX_PKTFLAG_ACKED;
4373 call->flags |= RX_CALL_TQ_CLEARME;
4374 call->flags |= RX_CALL_TQ_SOME_ACKED;
4377 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4378 rxi_FreePackets(0, &call->tq);
4379 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4380 call->flags &= ~RX_CALL_TQ_CLEARME;
4382 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4384 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4385 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4386 call->nSoftAcked = 0;
4388 if (call->flags & RX_CALL_FAST_RECOVER) {
4389 call->flags &= ~RX_CALL_FAST_RECOVER;
4390 call->cwind = call->nextCwind;
4392 #ifdef RX_ENABLE_LOCKS
4393 CV_SIGNAL(&call->cv_twind);
4395 osi_rxWakeup(&call->twind);
4400 rxi_ClearReceiveQueue(register struct rx_call *call)
4402 if (queue_IsNotEmpty(&call->rq)) {
4403 rx_packetReclaims += rxi_FreePackets(0, &call->rq);
4404 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4406 if (call->state == RX_STATE_PRECALL) {
4407 call->flags |= RX_CALL_CLEARED;
4411 /* Send an abort packet for the specified call */
4413 rxi_SendCallAbort(register struct rx_call *call, struct rx_packet *packet,
4414 int istack, int force)
4417 struct clock when, now;
4422 /* Clients should never delay abort messages */
4423 if (rx_IsClientConn(call->conn))
4426 if (call->abortCode != call->error) {
4427 call->abortCode = call->error;
4428 call->abortCount = 0;
4431 if (force || rxi_callAbortThreshhold == 0
4432 || call->abortCount < rxi_callAbortThreshhold) {
4433 if (call->delayedAbortEvent) {
4434 rxevent_Cancel(call->delayedAbortEvent, call,
4435 RX_CALL_REFCOUNT_ABORT);
4437 error = htonl(call->error);
4440 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4441 (char *)&error, sizeof(error), istack);
4442 } else if (!call->delayedAbortEvent) {
4443 clock_GetTime(&now);
4445 clock_Addmsec(&when, rxi_callAbortDelay);
4446 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4447 call->delayedAbortEvent =
4448 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4453 /* Send an abort packet for the specified connection. Packet is an
4454 * optional pointer to a packet that can be used to send the abort.
4455 * Once the number of abort messages reaches the threshhold, an
4456 * event is scheduled to send the abort. Setting the force flag
4457 * overrides sending delayed abort messages.
4459 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4460 * to send the abort packet.
4463 rxi_SendConnectionAbort(register struct rx_connection *conn,
4464 struct rx_packet *packet, int istack, int force)
4467 struct clock when, now;
4472 /* Clients should never delay abort messages */
4473 if (rx_IsClientConn(conn))
4476 if (force || rxi_connAbortThreshhold == 0
4477 || conn->abortCount < rxi_connAbortThreshhold) {
4478 if (conn->delayedAbortEvent) {
4479 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4481 error = htonl(conn->error);
4483 MUTEX_EXIT(&conn->conn_data_lock);
4485 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4486 RX_PACKET_TYPE_ABORT, (char *)&error,
4487 sizeof(error), istack);
4488 MUTEX_ENTER(&conn->conn_data_lock);
4489 } else if (!conn->delayedAbortEvent) {
4490 clock_GetTime(&now);
4492 clock_Addmsec(&when, rxi_connAbortDelay);
4493 conn->delayedAbortEvent =
4494 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4499 /* Associate an error all of the calls owned by a connection. Called
4500 * with error non-zero. This is only for really fatal things, like
4501 * bad authentication responses. The connection itself is set in
4502 * error at this point, so that future packets received will be
4505 rxi_ConnectionError(register struct rx_connection *conn,
4506 register afs_int32 error)
4511 dpf(("rxi_ConnectionError conn %x error %d", conn, error));
4513 MUTEX_ENTER(&conn->conn_data_lock);
4514 if (conn->challengeEvent)
4515 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4516 if (conn->checkReachEvent) {
4517 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4518 conn->checkReachEvent = 0;
4519 conn->flags &= ~RX_CONN_ATTACHWAIT;
4522 MUTEX_EXIT(&conn->conn_data_lock);
4523 for (i = 0; i < RX_MAXCALLS; i++) {
4524 struct rx_call *call = conn->call[i];
4526 MUTEX_ENTER(&call->lock);
4527 rxi_CallError(call, error);
4528 MUTEX_EXIT(&call->lock);
4531 conn->error = error;
4532 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4537 rxi_CallError(register struct rx_call *call, afs_int32 error)
4539 dpf(("rxi_CallError call %x error %d call->error %d", call, error, call->error));
4541 error = call->error;
4543 #ifdef RX_GLOBAL_RXLOCK_KERNEL
4544 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4545 rxi_ResetCall(call, 0);
4548 rxi_ResetCall(call, 0);
4550 call->error = error;
4551 call->mode = RX_MODE_ERROR;
4554 /* Reset various fields in a call structure, and wakeup waiting
4555 * processes. Some fields aren't changed: state & mode are not
4556 * touched (these must be set by the caller), and bufptr, nLeft, and
4557 * nFree are not reset, since these fields are manipulated by
4558 * unprotected macros, and may only be reset by non-interrupting code.
4561 /* this code requires that call->conn be set properly as a pre-condition. */
4562 #endif /* ADAPT_WINDOW */
4565 rxi_ResetCall(register struct rx_call *call, register int newcall)
4568 register struct rx_peer *peer;
4569 struct rx_packet *packet;
4571 dpf(("rxi_ResetCall(call %x, newcall %d)\n", call, newcall));
4573 /* Notify anyone who is waiting for asynchronous packet arrival */
4574 if (call->arrivalProc) {
4575 (*call->arrivalProc) (call, call->arrivalProcHandle,
4576 call->arrivalProcArg);
4577 call->arrivalProc = (void (*)())0;
4580 if (call->delayedAbortEvent) {
4581 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4582 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4584 rxi_SendCallAbort(call, packet, 0, 1);
4585 rxi_FreePacket(packet);
4590 * Update the peer with the congestion information in this call
4591 * so other calls on this connection can pick up where this call
4592 * left off. If the congestion sequence numbers don't match then
4593 * another call experienced a retransmission.
4595 peer = call->conn->peer;
4596 MUTEX_ENTER(&peer->peer_lock);
4598 if (call->congestSeq == peer->congestSeq) {
4599 peer->cwind = MAX(peer->cwind, call->cwind);
4600 peer->MTU = MAX(peer->MTU, call->MTU);
4601 peer->nDgramPackets =
4602 MAX(peer->nDgramPackets, call->nDgramPackets);
4605 call->abortCode = 0;
4606 call->abortCount = 0;
4608 if (peer->maxDgramPackets > 1) {
4609 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4611 call->MTU = peer->MTU;
4613 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4614 call->ssthresh = rx_maxSendWindow;
4615 call->nDgramPackets = peer->nDgramPackets;
4616 call->congestSeq = peer->congestSeq;
4617 MUTEX_EXIT(&peer->peer_lock);
4619 flags = call->flags;
4620 rxi_ClearReceiveQueue(call);
4621 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4622 if (flags & RX_CALL_TQ_BUSY) {
4623 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4624 call->flags |= (flags & RX_CALL_TQ_WAIT);
4626 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4628 rxi_ClearTransmitQueue(call, 0);
4629 queue_Init(&call->tq);
4630 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4631 dpf(("rcall %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4634 while (call->tqWaiters) {
4635 #ifdef RX_ENABLE_LOCKS
4636 CV_BROADCAST(&call->cv_tq);
4637 #else /* RX_ENABLE_LOCKS */
4638 osi_rxWakeup(&call->tq);
4639 #endif /* RX_ENABLE_LOCKS */
4643 queue_Init(&call->rq);
4645 call->twind = call->conn->twind[call->channel];
4646 call->rwind = call->conn->rwind[call->channel];
4647 call->nSoftAcked = 0;
4648 call->nextCwind = 0;
4651 call->nCwindAcks = 0;
4652 call->nSoftAcks = 0;
4653 call->nHardAcks = 0;
4655 call->tfirst = call->rnext = call->tnext = 1;
4657 call->lastAcked = 0;
4658 call->localStatus = call->remoteStatus = 0;
4660 if (flags & RX_CALL_READER_WAIT) {
4661 #ifdef RX_ENABLE_LOCKS
4662 CV_BROADCAST(&call->cv_rq);
4664 osi_rxWakeup(&call->rq);
4667 if (flags & RX_CALL_WAIT_PACKETS) {
4668 MUTEX_ENTER(&rx_freePktQ_lock);
4669 rxi_PacketsUnWait(); /* XXX */
4670 MUTEX_EXIT(&rx_freePktQ_lock);
4672 #ifdef RX_ENABLE_LOCKS
4673 CV_SIGNAL(&call->cv_twind);
4675 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4676 osi_rxWakeup(&call->twind);
4679 #ifdef RX_ENABLE_LOCKS
4680 /* The following ensures that we don't mess with any queue while some
4681 * other thread might also be doing so. The call_queue_lock field is
4682 * is only modified under the call lock. If the call is in the process
4683 * of being removed from a queue, the call is not locked until the
4684 * the queue lock is dropped and only then is the call_queue_lock field
4685 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4686 * Note that any other routine which removes a call from a queue has to
4687 * obtain the queue lock before examing the queue and removing the call.
4689 if (call->call_queue_lock) {
4690 MUTEX_ENTER(call->call_queue_lock);
4691 if (queue_IsOnQueue(call)) {
4693 if (flags & RX_CALL_WAIT_PROC) {
4694 MUTEX_ENTER(&rx_stats_mutex);
4696 MUTEX_EXIT(&rx_stats_mutex);
4699 MUTEX_EXIT(call->call_queue_lock);
4700 CLEAR_CALL_QUEUE_LOCK(call);
4702 #else /* RX_ENABLE_LOCKS */
4703 if (queue_IsOnQueue(call)) {
4705 if (flags & RX_CALL_WAIT_PROC)
4708 #endif /* RX_ENABLE_LOCKS */
4710 rxi_KeepAliveOff(call);
4711 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4714 /* Send an acknowledge for the indicated packet (seq,serial) of the
4715 * indicated call, for the indicated reason (reason). This
4716 * acknowledge will specifically acknowledge receiving the packet, and
4717 * will also specify which other packets for this call have been
4718 * received. This routine returns the packet that was used to the
4719 * caller. The caller is responsible for freeing it or re-using it.
4720 * This acknowledgement also returns the highest sequence number
4721 * actually read out by the higher level to the sender; the sender
4722 * promises to keep around packets that have not been read by the
4723 * higher level yet (unless, of course, the sender decides to abort
4724 * the call altogether). Any of p, seq, serial, pflags, or reason may
4725 * be set to zero without ill effect. That is, if they are zero, they
4726 * will not convey any information.
4727 * NOW there is a trailer field, after the ack where it will safely be
4728 * ignored by mundanes, which indicates the maximum size packet this
4729 * host can swallow. */
4731 register struct rx_packet *optionalPacket; use to send ack (or null)
4732 int seq; Sequence number of the packet we are acking
4733 int serial; Serial number of the packet
4734 int pflags; Flags field from packet header
4735 int reason; Reason an acknowledge was prompted
4739 rxi_SendAck(register struct rx_call *call,
4740 register struct rx_packet *optionalPacket, int serial, int reason,
4743 struct rx_ackPacket *ap;
4744 register struct rx_packet *rqp;
4745 register struct rx_packet *nxp; /* For queue_Scan */
4746 register struct rx_packet *p;
4749 #ifdef RX_ENABLE_TSFPQ
4750 struct rx_ts_info_t * rx_ts_info;
4754 * Open the receive window once a thread starts reading packets
4756 if (call->rnext > 1) {
4757 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4760 call->nHardAcks = 0;
4761 call->nSoftAcks = 0;
4762 if (call->rnext > call->lastAcked)
4763 call->lastAcked = call->rnext;
4767 rx_computelen(p, p->length); /* reset length, you never know */
4768 } /* where that's been... */
4769 #ifdef RX_ENABLE_TSFPQ
4771 RX_TS_INFO_GET(rx_ts_info);
4772 if ((p = rx_ts_info->local_special_packet)) {
4773 rx_computelen(p, p->length);
4774 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4775 rx_ts_info->local_special_packet = p;
4776 } else { /* We won't send the ack, but don't panic. */
4777 return optionalPacket;
4781 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4782 /* We won't send the ack, but don't panic. */
4783 return optionalPacket;
4788 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4791 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4792 #ifndef RX_ENABLE_TSFPQ
4793 if (!optionalPacket)
4796 return optionalPacket;
4798 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4799 if (rx_Contiguous(p) < templ) {
4800 #ifndef RX_ENABLE_TSFPQ
4801 if (!optionalPacket)
4804 return optionalPacket;
4809 /* MTUXXX failing to send an ack is very serious. We should */
4810 /* try as hard as possible to send even a partial ack; it's */
4811 /* better than nothing. */
4812 ap = (struct rx_ackPacket *)rx_DataOf(p);
4813 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4814 ap->reason = reason;
4816 /* The skew computation used to be bogus, I think it's better now. */
4817 /* We should start paying attention to skew. XXX */
4818 ap->serial = htonl(serial);
4819 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4821 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4822 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4824 /* No fear of running out of ack packet here because there can only be at most
4825 * one window full of unacknowledged packets. The window size must be constrained
4826 * to be less than the maximum ack size, of course. Also, an ack should always
4827 * fit into a single packet -- it should not ever be fragmented. */
4828 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4829 if (!rqp || !call->rq.next
4830 || (rqp->header.seq > (call->rnext + call->rwind))) {
4831 #ifndef RX_ENABLE_TSFPQ
4832 if (!optionalPacket)
4835 rxi_CallError(call, RX_CALL_DEAD);
4836 return optionalPacket;
4839 while (rqp->header.seq > call->rnext + offset)
4840 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4841 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4843 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4844 #ifndef RX_ENABLE_TSFPQ
4845 if (!optionalPacket)
4848 rxi_CallError(call, RX_CALL_DEAD);
4849 return optionalPacket;
4854 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4856 /* these are new for AFS 3.3 */
4857 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4858 templ = htonl(templ);
4859 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4860 templ = htonl(call->conn->peer->ifMTU);
4861 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4862 sizeof(afs_int32), &templ);
4864 /* new for AFS 3.4 */
4865 templ = htonl(call->rwind);
4866 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4867 sizeof(afs_int32), &templ);
4869 /* new for AFS 3.5 */
4870 templ = htonl(call->conn->peer->ifDgramPackets);
4871 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4872 sizeof(afs_int32), &templ);
4874 p->header.serviceId = call->conn->serviceId;
4875 p->header.cid = (call->conn->cid | call->channel);
4876 p->header.callNumber = *call->callNumber;
4878 p->header.securityIndex = call->conn->securityIndex;
4879 p->header.epoch = call->conn->epoch;
4880 p->header.type = RX_PACKET_TYPE_ACK;
4881 p->header.flags = RX_SLOW_START_OK;
4882 if (reason == RX_ACK_PING) {
4883 p->header.flags |= RX_REQUEST_ACK;
4885 clock_GetTime(&call->pingRequestTime);
4888 if (call->conn->type == RX_CLIENT_CONNECTION)
4889 p->header.flags |= RX_CLIENT_INITIATED;
4893 if (rxdebug_active) {
4897 len = _snprintf(msg, sizeof(msg),
4898 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4899 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4900 ntohl(ap->serial), ntohl(ap->previousPacket),
4901 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
4902 ap->nAcks, ntohs(ap->bufferSpace) );
4906 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
4907 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4911 OutputDebugString(msg);
4913 #else /* AFS_NT40_ENV */
4915 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
4916 ap->reason, ntohl(ap->previousPacket),
4917 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
4919 for (offset = 0; offset < ap->nAcks; offset++)
4920 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4925 #endif /* AFS_NT40_ENV */
4928 register int i, nbytes = p->length;
4930 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
4931 if (nbytes <= p->wirevec[i].iov_len) {
4932 register int savelen, saven;
4934 savelen = p->wirevec[i].iov_len;
4936 p->wirevec[i].iov_len = nbytes;
4938 rxi_Send(call, p, istack);
4939 p->wirevec[i].iov_len = savelen;
4943 nbytes -= p->wirevec[i].iov_len;
4946 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
4947 #ifndef RX_ENABLE_TSFPQ
4948 if (!optionalPacket)
4951 return optionalPacket; /* Return packet for re-use by caller */
4954 /* Send all of the packets in the list in single datagram */
4956 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
4957 int istack, int moreFlag, struct clock *now,
4958 struct clock *retryTime, int resending)
4963 struct rx_connection *conn = call->conn;
4964 struct rx_peer *peer = conn->peer;
4966 MUTEX_ENTER(&peer->peer_lock);
4969 peer->reSends += len;
4970 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
4971 MUTEX_EXIT(&peer->peer_lock);
4973 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
4977 /* Set the packet flags and schedule the resend events */
4978 /* Only request an ack for the last packet in the list */
4979 for (i = 0; i < len; i++) {
4980 list[i]->retryTime = *retryTime;
4981 if (list[i]->header.serial) {
4982 /* Exponentially backoff retry times */
4983 if (list[i]->backoff < MAXBACKOFF) {
4984 /* so it can't stay == 0 */
4985 list[i]->backoff = (list[i]->backoff << 1) + 1;
4988 clock_Addmsec(&(list[i]->retryTime),
4989 ((afs_uint32) list[i]->backoff) << 8);
4992 /* Wait a little extra for the ack on the last packet */
4993 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
4994 clock_Addmsec(&(list[i]->retryTime), 400);
4997 /* Record the time sent */
4998 list[i]->timeSent = *now;
5000 /* Ask for an ack on retransmitted packets, on every other packet
5001 * if the peer doesn't support slow start. Ask for an ack on every
5002 * packet until the congestion window reaches the ack rate. */
5003 if (list[i]->header.serial) {
5005 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5007 /* improved RTO calculation- not Karn */
5008 list[i]->firstSent = *now;
5009 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5010 || (!(call->flags & RX_CALL_SLOW_START_OK)
5011 && (list[i]->header.seq & 1)))) {
5016 MUTEX_ENTER(&peer->peer_lock);
5020 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5021 MUTEX_EXIT(&peer->peer_lock);
5023 /* Tag this packet as not being the last in this group,
5024 * for the receiver's benefit */
5025 if (i < len - 1 || moreFlag) {
5026 list[i]->header.flags |= RX_MORE_PACKETS;
5029 /* Install the new retransmit time for the packet, and
5030 * record the time sent */
5031 list[i]->timeSent = *now;
5035 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5038 /* Since we're about to send a data packet to the peer, it's
5039 * safe to nuke any scheduled end-of-packets ack */
5040 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5042 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5043 MUTEX_EXIT(&call->lock);
5045 rxi_SendPacketList(call, conn, list, len, istack);
5047 rxi_SendPacket(call, conn, list[0], istack);
5049 MUTEX_ENTER(&call->lock);
5050 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5052 /* Update last send time for this call (for keep-alive
5053 * processing), and for the connection (so that we can discover
5054 * idle connections) */
5055 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5058 /* When sending packets we need to follow these rules:
5059 * 1. Never send more than maxDgramPackets in a jumbogram.
5060 * 2. Never send a packet with more than two iovecs in a jumbogram.
5061 * 3. Never send a retransmitted packet in a jumbogram.
5062 * 4. Never send more than cwind/4 packets in a jumbogram
5063 * We always keep the last list we should have sent so we
5064 * can set the RX_MORE_PACKETS flags correctly.
5067 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5068 int istack, struct clock *now, struct clock *retryTime,
5071 int i, cnt, lastCnt = 0;
5072 struct rx_packet **listP, **lastP = 0;
5073 struct rx_peer *peer = call->conn->peer;
5074 int morePackets = 0;
5076 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5077 /* Does the current packet force us to flush the current list? */
5079 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5080 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5082 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5084 /* If the call enters an error state stop sending, or if
5085 * we entered congestion recovery mode, stop sending */
5086 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5094 /* Add the current packet to the list if it hasn't been acked.
5095 * Otherwise adjust the list pointer to skip the current packet. */
5096 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5098 /* Do we need to flush the list? */
5099 if (cnt >= (int)peer->maxDgramPackets
5100 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5101 || list[i]->header.serial
5102 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5104 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5105 retryTime, resending);
5106 /* If the call enters an error state stop sending, or if
5107 * we entered congestion recovery mode, stop sending */
5109 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5114 listP = &list[i + 1];
5119 osi_Panic("rxi_SendList error");
5121 listP = &list[i + 1];
5125 /* Send the whole list when the call is in receive mode, when
5126 * the call is in eof mode, when we are in fast recovery mode,
5127 * and when we have the last packet */
5128 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5129 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5130 || (call->flags & RX_CALL_FAST_RECOVER)) {
5131 /* Check for the case where the current list contains
5132 * an acked packet. Since we always send retransmissions
5133 * in a separate packet, we only need to check the first
5134 * packet in the list */
5135 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5139 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5140 retryTime, resending);
5141 /* If the call enters an error state stop sending, or if
5142 * we entered congestion recovery mode, stop sending */
5143 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5147 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5150 } else if (lastCnt > 0) {
5151 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5156 #ifdef RX_ENABLE_LOCKS
5157 /* Call rxi_Start, below, but with the call lock held. */
5159 rxi_StartUnlocked(struct rxevent *event, register struct rx_call *call,
5160 void *arg1, int istack)
5162 MUTEX_ENTER(&call->lock);
5163 rxi_Start(event, call, arg1, istack);
5164 MUTEX_EXIT(&call->lock);
5166 #endif /* RX_ENABLE_LOCKS */
5168 /* This routine is called when new packets are readied for
5169 * transmission and when retransmission may be necessary, or when the
5170 * transmission window or burst count are favourable. This should be
5171 * better optimized for new packets, the usual case, now that we've
5172 * got rid of queues of send packets. XXXXXXXXXXX */
5174 rxi_Start(struct rxevent *event, register struct rx_call *call,
5175 void *arg1, int istack)
5177 struct rx_packet *p;
5178 register struct rx_packet *nxp; /* Next pointer for queue_Scan */
5179 struct rx_peer *peer = call->conn->peer;
5180 struct clock now, usenow, retryTime;
5184 struct rx_packet **xmitList;
5187 /* If rxi_Start is being called as a result of a resend event,
5188 * then make sure that the event pointer is removed from the call
5189 * structure, since there is no longer a per-call retransmission
5191 if (event && event == call->resendEvent) {
5192 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5193 call->resendEvent = NULL;
5195 if (queue_IsEmpty(&call->tq)) {
5199 /* Timeouts trigger congestion recovery */
5200 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5201 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5202 /* someone else is waiting to start recovery */
5205 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5206 rxi_WaitforTQBusy(call);
5207 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5208 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5209 call->flags |= RX_CALL_FAST_RECOVER;
5210 if (peer->maxDgramPackets > 1) {
5211 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5213 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5215 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5216 call->nDgramPackets = 1;
5218 call->nextCwind = 1;
5221 MUTEX_ENTER(&peer->peer_lock);
5222 peer->MTU = call->MTU;
5223 peer->cwind = call->cwind;
5224 peer->nDgramPackets = 1;
5226 call->congestSeq = peer->congestSeq;
5227 MUTEX_EXIT(&peer->peer_lock);
5228 /* Clear retry times on packets. Otherwise, it's possible for
5229 * some packets in the queue to force resends at rates faster
5230 * than recovery rates.
5232 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5233 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5234 clock_Zero(&p->retryTime);
5239 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5240 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5245 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5246 /* Get clock to compute the re-transmit time for any packets
5247 * in this burst. Note, if we back off, it's reasonable to
5248 * back off all of the packets in the same manner, even if
5249 * some of them have been retransmitted more times than more
5251 * Do a dance to avoid blocking after setting now. */
5252 clock_Zero(&retryTime);
5253 MUTEX_ENTER(&peer->peer_lock);
5254 clock_Add(&retryTime, &peer->timeout);
5255 MUTEX_EXIT(&peer->peer_lock);
5256 clock_GetTime(&now);
5257 clock_Add(&retryTime, &now);
5259 /* Send (or resend) any packets that need it, subject to
5260 * window restrictions and congestion burst control
5261 * restrictions. Ask for an ack on the last packet sent in
5262 * this burst. For now, we're relying upon the window being
5263 * considerably bigger than the largest number of packets that
5264 * are typically sent at once by one initial call to
5265 * rxi_Start. This is probably bogus (perhaps we should ask
5266 * for an ack when we're half way through the current
5267 * window?). Also, for non file transfer applications, this
5268 * may end up asking for an ack for every packet. Bogus. XXXX
5271 * But check whether we're here recursively, and let the other guy
5274 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5275 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5276 call->flags |= RX_CALL_TQ_BUSY;
5278 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5280 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5281 call->flags &= ~RX_CALL_NEED_START;
5282 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5284 maxXmitPackets = MIN(call->twind, call->cwind);
5285 xmitList = (struct rx_packet **)
5286 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5287 /* XXXX else we must drop any mtx we hold */
5288 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5290 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5292 if (xmitList == NULL)
5293 osi_Panic("rxi_Start, failed to allocate xmit list");
5294 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5295 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5296 /* We shouldn't be sending packets if a thread is waiting
5297 * to initiate congestion recovery */
5301 && (call->flags & RX_CALL_FAST_RECOVER)) {
5302 /* Only send one packet during fast recovery */
5305 if ((p->flags & RX_PKTFLAG_FREE)
5306 || (!queue_IsEnd(&call->tq, nxp)
5307 && (nxp->flags & RX_PKTFLAG_FREE))
5308 || (p == (struct rx_packet *)&rx_freePacketQueue)
5309 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5310 osi_Panic("rxi_Start: xmit queue clobbered");
5312 if (p->flags & RX_PKTFLAG_ACKED) {
5313 /* Since we may block, don't trust this */
5314 usenow.sec = usenow.usec = 0;
5315 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5316 continue; /* Ignore this packet if it has been acknowledged */
5319 /* Turn off all flags except these ones, which are the same
5320 * on each transmission */
5321 p->header.flags &= RX_PRESET_FLAGS;
5323 if (p->header.seq >=
5324 call->tfirst + MIN((int)call->twind,
5325 (int)(call->nSoftAcked +
5327 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5328 /* Note: if we're waiting for more window space, we can
5329 * still send retransmits; hence we don't return here, but
5330 * break out to schedule a retransmit event */
5331 dpf(("call %d waiting for window",
5332 *(call->callNumber)));
5336 /* Transmit the packet if it needs to be sent. */
5337 if (!clock_Lt(&now, &p->retryTime)) {
5338 if (nXmitPackets == maxXmitPackets) {
5339 rxi_SendXmitList(call, xmitList, nXmitPackets,
5340 istack, &now, &retryTime,
5342 osi_Free(xmitList, maxXmitPackets *
5343 sizeof(struct rx_packet *));
5346 xmitList[nXmitPackets++] = p;
5350 /* xmitList now hold pointers to all of the packets that are
5351 * ready to send. Now we loop to send the packets */
5352 if (nXmitPackets > 0) {
5353 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5354 &now, &retryTime, resending);
5357 maxXmitPackets * sizeof(struct rx_packet *));
5359 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5361 * TQ references no longer protected by this flag; they must remain
5362 * protected by the global lock.
5364 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5365 call->flags &= ~RX_CALL_TQ_BUSY;
5366 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5367 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5368 #ifdef RX_ENABLE_LOCKS
5369 osirx_AssertMine(&call->lock, "rxi_Start start");
5370 CV_BROADCAST(&call->cv_tq);
5371 #else /* RX_ENABLE_LOCKS */
5372 osi_rxWakeup(&call->tq);
5373 #endif /* RX_ENABLE_LOCKS */
5378 /* We went into the error state while sending packets. Now is
5379 * the time to reset the call. This will also inform the using
5380 * process that the call is in an error state.
5382 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5383 call->flags &= ~RX_CALL_TQ_BUSY;
5384 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5385 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5386 #ifdef RX_ENABLE_LOCKS
5387 osirx_AssertMine(&call->lock, "rxi_Start middle");
5388 CV_BROADCAST(&call->cv_tq);
5389 #else /* RX_ENABLE_LOCKS */
5390 osi_rxWakeup(&call->tq);
5391 #endif /* RX_ENABLE_LOCKS */
5393 rxi_CallError(call, call->error);
5396 #ifdef RX_ENABLE_LOCKS
5397 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5398 register int missing;
5399 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5400 /* Some packets have received acks. If they all have, we can clear
5401 * the transmit queue.
5404 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5405 if (p->header.seq < call->tfirst
5406 && (p->flags & RX_PKTFLAG_ACKED)) {
5413 call->flags |= RX_CALL_TQ_CLEARME;
5415 #endif /* RX_ENABLE_LOCKS */
5416 /* Don't bother doing retransmits if the TQ is cleared. */
5417 if (call->flags & RX_CALL_TQ_CLEARME) {
5418 rxi_ClearTransmitQueue(call, 1);
5420 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5423 /* Always post a resend event, if there is anything in the
5424 * queue, and resend is possible. There should be at least
5425 * one unacknowledged packet in the queue ... otherwise none
5426 * of these packets should be on the queue in the first place.
5428 if (call->resendEvent) {
5429 /* Cancel the existing event and post a new one */
5430 rxevent_Cancel(call->resendEvent, call,
5431 RX_CALL_REFCOUNT_RESEND);
5434 /* The retry time is the retry time on the first unacknowledged
5435 * packet inside the current window */
5437 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5438 /* Don't set timers for packets outside the window */
5439 if (p->header.seq >= call->tfirst + call->twind) {
5443 if (!(p->flags & RX_PKTFLAG_ACKED)
5444 && !clock_IsZero(&p->retryTime)) {
5446 retryTime = p->retryTime;
5451 /* Post a new event to re-run rxi_Start when retries may be needed */
5452 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5453 #ifdef RX_ENABLE_LOCKS
5454 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5456 rxevent_PostNow2(&retryTime, &usenow,
5458 (void *)call, 0, istack);
5459 #else /* RX_ENABLE_LOCKS */
5461 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5462 (void *)call, 0, istack);
5463 #endif /* RX_ENABLE_LOCKS */
5466 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5467 } while (call->flags & RX_CALL_NEED_START);
5469 * TQ references no longer protected by this flag; they must remain
5470 * protected by the global lock.
5472 call->flags &= ~RX_CALL_TQ_BUSY;
5473 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5474 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5475 #ifdef RX_ENABLE_LOCKS
5476 osirx_AssertMine(&call->lock, "rxi_Start end");
5477 CV_BROADCAST(&call->cv_tq);
5478 #else /* RX_ENABLE_LOCKS */
5479 osi_rxWakeup(&call->tq);
5480 #endif /* RX_ENABLE_LOCKS */
5483 call->flags |= RX_CALL_NEED_START;
5485 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5487 if (call->resendEvent) {
5488 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5493 /* Also adjusts the keep alive parameters for the call, to reflect
5494 * that we have just sent a packet (so keep alives aren't sent
5497 rxi_Send(register struct rx_call *call, register struct rx_packet *p,
5500 register struct rx_connection *conn = call->conn;
5502 /* Stamp each packet with the user supplied status */
5503 p->header.userStatus = call->localStatus;
5505 /* Allow the security object controlling this call's security to
5506 * make any last-minute changes to the packet */
5507 RXS_SendPacket(conn->securityObject, call, p);
5509 /* Since we're about to send SOME sort of packet to the peer, it's
5510 * safe to nuke any scheduled end-of-packets ack */
5511 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5513 /* Actually send the packet, filling in more connection-specific fields */
5514 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5515 MUTEX_EXIT(&call->lock);
5516 rxi_SendPacket(call, conn, p, istack);
5517 MUTEX_ENTER(&call->lock);
5518 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5520 /* Update last send time for this call (for keep-alive
5521 * processing), and for the connection (so that we can discover
5522 * idle connections) */
5523 conn->lastSendTime = call->lastSendTime = clock_Sec();
5524 /* Don't count keepalives here, so idleness can be tracked. */
5525 if (p->header.type != RX_PACKET_TYPE_ACK)
5526 call->lastSendData = call->lastSendTime;
5530 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5531 * that things are fine. Also called periodically to guarantee that nothing
5532 * falls through the cracks (e.g. (error + dally) connections have keepalive
5533 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5535 * haveCTLock Set if calling from rxi_ReapConnections
5537 #ifdef RX_ENABLE_LOCKS
5539 rxi_CheckCall(register struct rx_call *call, int haveCTLock)
5540 #else /* RX_ENABLE_LOCKS */
5542 rxi_CheckCall(register struct rx_call *call)
5543 #endif /* RX_ENABLE_LOCKS */
5545 register struct rx_connection *conn = call->conn;
5547 afs_uint32 deadTime;
5549 #ifdef RX_GLOBAL_RXLOCK_KERNEL
5550 if (call->flags & RX_CALL_TQ_BUSY) {
5551 /* Call is active and will be reset by rxi_Start if it's
5552 * in an error state.
5557 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5559 (((afs_uint32) conn->secondsUntilDead << 10) +
5560 ((afs_uint32) conn->peer->rtt >> 3) +
5561 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5563 /* These are computed to the second (+- 1 second). But that's
5564 * good enough for these values, which should be a significant
5565 * number of seconds. */
5566 if (now > (call->lastReceiveTime + deadTime)) {
5567 if (call->state == RX_STATE_ACTIVE) {
5569 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5571 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5572 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5573 ip_stack_t *ipst = ns->netstack_ip;
5575 ire = ire_cache_lookup(call->conn->peer->host
5576 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5578 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5580 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5587 if (ire && ire->ire_max_frag > 0)
5588 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5589 #if defined(GLOBAL_NETSTACKID)
5593 #endif /* ADAPT_PMTU */
5594 rxi_CallError(call, RX_CALL_DEAD);
5597 #ifdef RX_ENABLE_LOCKS
5598 /* Cancel pending events */
5599 rxevent_Cancel(call->delayedAckEvent, call,
5600 RX_CALL_REFCOUNT_DELAY);
5601 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5602 rxevent_Cancel(call->keepAliveEvent, call,
5603 RX_CALL_REFCOUNT_ALIVE);
5604 if (call->refCount == 0) {
5605 rxi_FreeCall(call, haveCTLock);
5609 #else /* RX_ENABLE_LOCKS */
5612 #endif /* RX_ENABLE_LOCKS */
5614 /* Non-active calls are destroyed if they are not responding
5615 * to pings; active calls are simply flagged in error, so the
5616 * attached process can die reasonably gracefully. */
5618 /* see if we have a non-activity timeout */
5619 if (call->startWait && conn->idleDeadTime
5620 && ((call->startWait + conn->idleDeadTime) < now)) {
5621 if (call->state == RX_STATE_ACTIVE) {
5622 rxi_CallError(call, RX_CALL_TIMEOUT);
5626 if (call->lastSendData && conn->idleDeadTime && (conn->idleDeadErr != 0)
5627 && ((call->lastSendData + conn->idleDeadTime) < now)) {
5628 if (call->state == RX_STATE_ACTIVE) {
5629 rxi_CallError(call, conn->idleDeadErr);
5633 /* see if we have a hard timeout */
5634 if (conn->hardDeadTime
5635 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5636 if (call->state == RX_STATE_ACTIVE)
5637 rxi_CallError(call, RX_CALL_TIMEOUT);
5644 /* When a call is in progress, this routine is called occasionally to
5645 * make sure that some traffic has arrived (or been sent to) the peer.
5646 * If nothing has arrived in a reasonable amount of time, the call is
5647 * declared dead; if nothing has been sent for a while, we send a
5648 * keep-alive packet (if we're actually trying to keep the call alive)
5651 rxi_KeepAliveEvent(struct rxevent *event, register struct rx_call *call,
5654 struct rx_connection *conn;
5657 MUTEX_ENTER(&call->lock);
5658 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5659 if (event == call->keepAliveEvent)
5660 call->keepAliveEvent = NULL;
5663 #ifdef RX_ENABLE_LOCKS
5664 if (rxi_CheckCall(call, 0)) {
5665 MUTEX_EXIT(&call->lock);
5668 #else /* RX_ENABLE_LOCKS */
5669 if (rxi_CheckCall(call))
5671 #endif /* RX_ENABLE_LOCKS */
5673 /* Don't try to keep alive dallying calls */
5674 if (call->state == RX_STATE_DALLY) {
5675 MUTEX_EXIT(&call->lock);
5680 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
5681 /* Don't try to send keepalives if there is unacknowledged data */
5682 /* the rexmit code should be good enough, this little hack
5683 * doesn't quite work XXX */
5684 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5686 rxi_ScheduleKeepAliveEvent(call);
5687 MUTEX_EXIT(&call->lock);
5692 rxi_ScheduleKeepAliveEvent(register struct rx_call *call)
5694 if (!call->keepAliveEvent) {
5695 struct clock when, now;
5696 clock_GetTime(&now);
5698 when.sec += call->conn->secondsUntilPing;
5699 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5700 call->keepAliveEvent =
5701 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5705 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5707 rxi_KeepAliveOn(register struct rx_call *call)
5709 /* Pretend last packet received was received now--i.e. if another
5710 * packet isn't received within the keep alive time, then the call
5711 * will die; Initialize last send time to the current time--even
5712 * if a packet hasn't been sent yet. This will guarantee that a
5713 * keep-alive is sent within the ping time */
5714 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5715 rxi_ScheduleKeepAliveEvent(call);
5718 /* This routine is called to send connection abort messages
5719 * that have been delayed to throttle looping clients. */
5721 rxi_SendDelayedConnAbort(struct rxevent *event,
5722 register struct rx_connection *conn, char *dummy)
5725 struct rx_packet *packet;
5727 MUTEX_ENTER(&conn->conn_data_lock);
5728 conn->delayedAbortEvent = NULL;
5729 error = htonl(conn->error);
5731 MUTEX_EXIT(&conn->conn_data_lock);
5732 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5735 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5736 RX_PACKET_TYPE_ABORT, (char *)&error,
5738 rxi_FreePacket(packet);
5742 /* This routine is called to send call abort messages
5743 * that have been delayed to throttle looping clients. */
5745 rxi_SendDelayedCallAbort(struct rxevent *event, register struct rx_call *call,
5749 struct rx_packet *packet;
5751 MUTEX_ENTER(&call->lock);
5752 call->delayedAbortEvent = NULL;
5753 error = htonl(call->error);
5755 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5758 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5759 (char *)&error, sizeof(error), 0);
5760 rxi_FreePacket(packet);
5762 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5763 MUTEX_EXIT(&call->lock);
5766 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5767 * seconds) to ask the client to authenticate itself. The routine
5768 * issues a challenge to the client, which is obtained from the
5769 * security object associated with the connection */
5771 rxi_ChallengeEvent(struct rxevent *event, register struct rx_connection *conn,
5772 void *arg1, int tries)
5774 conn->challengeEvent = NULL;
5775 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5776 register struct rx_packet *packet;
5777 struct clock when, now;
5780 /* We've failed to authenticate for too long.
5781 * Reset any calls waiting for authentication;
5782 * they are all in RX_STATE_PRECALL.
5786 MUTEX_ENTER(&conn->conn_call_lock);
5787 for (i = 0; i < RX_MAXCALLS; i++) {
5788 struct rx_call *call = conn->call[i];
5790 MUTEX_ENTER(&call->lock);
5791 if (call->state == RX_STATE_PRECALL) {
5792 rxi_CallError(call, RX_CALL_DEAD);
5793 rxi_SendCallAbort(call, NULL, 0, 0);
5795 MUTEX_EXIT(&call->lock);
5798 MUTEX_EXIT(&conn->conn_call_lock);
5802 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5804 /* If there's no packet available, do this later. */
5805 RXS_GetChallenge(conn->securityObject, conn, packet);
5806 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5807 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5808 rxi_FreePacket(packet);
5810 clock_GetTime(&now);
5812 when.sec += RX_CHALLENGE_TIMEOUT;
5813 conn->challengeEvent =
5814 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5819 /* Call this routine to start requesting the client to authenticate
5820 * itself. This will continue until authentication is established,
5821 * the call times out, or an invalid response is returned. The
5822 * security object associated with the connection is asked to create
5823 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5824 * defined earlier. */
5826 rxi_ChallengeOn(register struct rx_connection *conn)
5828 if (!conn->challengeEvent) {
5829 RXS_CreateChallenge(conn->securityObject, conn);
5830 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5835 /* Compute round trip time of the packet provided, in *rttp.
5838 /* rxi_ComputeRoundTripTime is called with peer locked. */
5839 /* sentp and/or peer may be null */
5841 rxi_ComputeRoundTripTime(register struct rx_packet *p,
5842 register struct clock *sentp,
5843 register struct rx_peer *peer)
5845 struct clock thisRtt, *rttp = &thisRtt;
5847 register int rtt_timeout;
5849 clock_GetTime(rttp);
5851 if (clock_Lt(rttp, sentp)) {
5853 return; /* somebody set the clock back, don't count this time. */
5855 clock_Sub(rttp, sentp);
5856 MUTEX_ENTER(&rx_stats_mutex);
5857 if (clock_Lt(rttp, &rx_stats.minRtt))
5858 rx_stats.minRtt = *rttp;
5859 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5860 if (rttp->sec > 60) {
5861 MUTEX_EXIT(&rx_stats_mutex);
5862 return; /* somebody set the clock ahead */
5864 rx_stats.maxRtt = *rttp;
5866 clock_Add(&rx_stats.totalRtt, rttp);
5867 rx_stats.nRttSamples++;
5868 MUTEX_EXIT(&rx_stats_mutex);
5870 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
5872 /* Apply VanJacobson round-trip estimations */
5877 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
5878 * srtt is stored as fixed point with 3 bits after the binary
5879 * point (i.e., scaled by 8). The following magic is
5880 * equivalent to the smoothing algorithm in rfc793 with an
5881 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
5882 * srtt*8 = srtt*8 + rtt - srtt
5883 * srtt = srtt + rtt/8 - srtt/8
5886 delta = MSEC(rttp) - (peer->rtt >> 3);
5890 * We accumulate a smoothed rtt variance (actually, a smoothed
5891 * mean difference), then set the retransmit timer to smoothed
5892 * rtt + 4 times the smoothed variance (was 2x in van's original
5893 * paper, but 4x works better for me, and apparently for him as
5895 * rttvar is stored as
5896 * fixed point with 2 bits after the binary point (scaled by
5897 * 4). The following is equivalent to rfc793 smoothing with
5898 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
5899 * replaces rfc793's wired-in beta.
5900 * dev*4 = dev*4 + (|actual - expected| - dev)
5906 delta -= (peer->rtt_dev >> 2);
5907 peer->rtt_dev += delta;
5909 /* I don't have a stored RTT so I start with this value. Since I'm
5910 * probably just starting a call, and will be pushing more data down
5911 * this, I expect congestion to increase rapidly. So I fudge a
5912 * little, and I set deviance to half the rtt. In practice,
5913 * deviance tends to approach something a little less than
5914 * half the smoothed rtt. */
5915 peer->rtt = (MSEC(rttp) << 3) + 8;
5916 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
5918 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
5919 * the other of these connections is usually in a user process, and can
5920 * be switched and/or swapped out. So on fast, reliable networks, the
5921 * timeout would otherwise be too short.
5923 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
5924 clock_Zero(&(peer->timeout));
5925 clock_Addmsec(&(peer->timeout), rtt_timeout);
5927 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)));
5931 /* Find all server connections that have not been active for a long time, and
5934 rxi_ReapConnections(void)
5936 struct clock now, when;
5937 clock_GetTime(&now);
5939 /* Find server connection structures that haven't been used for
5940 * greater than rx_idleConnectionTime */
5942 struct rx_connection **conn_ptr, **conn_end;
5943 int i, havecalls = 0;
5944 MUTEX_ENTER(&rx_connHashTable_lock);
5945 for (conn_ptr = &rx_connHashTable[0], conn_end =
5946 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
5948 struct rx_connection *conn, *next;
5949 struct rx_call *call;
5953 for (conn = *conn_ptr; conn; conn = next) {
5954 /* XXX -- Shouldn't the connection be locked? */
5957 for (i = 0; i < RX_MAXCALLS; i++) {
5958 call = conn->call[i];
5961 MUTEX_ENTER(&call->lock);
5962 #ifdef RX_ENABLE_LOCKS
5963 result = rxi_CheckCall(call, 1);
5964 #else /* RX_ENABLE_LOCKS */
5965 result = rxi_CheckCall(call);
5966 #endif /* RX_ENABLE_LOCKS */
5967 MUTEX_EXIT(&call->lock);
5969 /* If CheckCall freed the call, it might
5970 * have destroyed the connection as well,
5971 * which screws up the linked lists.
5977 if (conn->type == RX_SERVER_CONNECTION) {
5978 /* This only actually destroys the connection if
5979 * there are no outstanding calls */
5980 MUTEX_ENTER(&conn->conn_data_lock);
5981 if (!havecalls && !conn->refCount
5982 && ((conn->lastSendTime + rx_idleConnectionTime) <
5984 conn->refCount++; /* it will be decr in rx_DestroyConn */
5985 MUTEX_EXIT(&conn->conn_data_lock);
5986 #ifdef RX_ENABLE_LOCKS
5987 rxi_DestroyConnectionNoLock(conn);
5988 #else /* RX_ENABLE_LOCKS */
5989 rxi_DestroyConnection(conn);
5990 #endif /* RX_ENABLE_LOCKS */
5992 #ifdef RX_ENABLE_LOCKS
5994 MUTEX_EXIT(&conn->conn_data_lock);
5996 #endif /* RX_ENABLE_LOCKS */
6000 #ifdef RX_ENABLE_LOCKS
6001 while (rx_connCleanup_list) {
6002 struct rx_connection *conn;
6003 conn = rx_connCleanup_list;
6004 rx_connCleanup_list = rx_connCleanup_list->next;
6005 MUTEX_EXIT(&rx_connHashTable_lock);
6006 rxi_CleanupConnection(conn);
6007 MUTEX_ENTER(&rx_connHashTable_lock);
6009 MUTEX_EXIT(&rx_connHashTable_lock);
6010 #endif /* RX_ENABLE_LOCKS */
6013 /* Find any peer structures that haven't been used (haven't had an
6014 * associated connection) for greater than rx_idlePeerTime */
6016 struct rx_peer **peer_ptr, **peer_end;
6018 MUTEX_ENTER(&rx_rpc_stats);
6019 MUTEX_ENTER(&rx_peerHashTable_lock);
6020 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6021 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6023 struct rx_peer *peer, *next, *prev;
6024 for (prev = peer = *peer_ptr; peer; peer = next) {
6026 code = MUTEX_TRYENTER(&peer->peer_lock);
6027 if ((code) && (peer->refCount == 0)
6028 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6029 rx_interface_stat_p rpc_stat, nrpc_stat;
6031 MUTEX_EXIT(&peer->peer_lock);
6032 MUTEX_DESTROY(&peer->peer_lock);
6034 (&peer->rpcStats, rpc_stat, nrpc_stat,
6035 rx_interface_stat)) {
6036 unsigned int num_funcs;
6039 queue_Remove(&rpc_stat->queue_header);
6040 queue_Remove(&rpc_stat->all_peers);
6041 num_funcs = rpc_stat->stats[0].func_total;
6043 sizeof(rx_interface_stat_t) +
6044 rpc_stat->stats[0].func_total *
6045 sizeof(rx_function_entry_v1_t);
6047 rxi_Free(rpc_stat, space);
6048 rxi_rpc_peer_stat_cnt -= num_funcs;
6051 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6052 if (peer == *peer_ptr) {
6059 MUTEX_EXIT(&peer->peer_lock);
6065 MUTEX_EXIT(&rx_peerHashTable_lock);
6066 MUTEX_EXIT(&rx_rpc_stats);
6069 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6070 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6071 * GC, just below. Really, we shouldn't have to keep moving packets from
6072 * one place to another, but instead ought to always know if we can
6073 * afford to hold onto a packet in its particular use. */
6074 MUTEX_ENTER(&rx_freePktQ_lock);
6075 if (rx_waitingForPackets) {
6076 rx_waitingForPackets = 0;
6077 #ifdef RX_ENABLE_LOCKS
6078 CV_BROADCAST(&rx_waitingForPackets_cv);
6080 osi_rxWakeup(&rx_waitingForPackets);
6083 MUTEX_EXIT(&rx_freePktQ_lock);
6086 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6087 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6091 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6092 * rx.h is sort of strange this is better. This is called with a security
6093 * object before it is discarded. Each connection using a security object has
6094 * its own refcount to the object so it won't actually be freed until the last
6095 * connection is destroyed.
6097 * This is the only rxs module call. A hold could also be written but no one
6101 rxs_Release(struct rx_securityClass *aobj)
6103 return RXS_Close(aobj);
6107 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6108 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6109 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6110 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6112 /* Adjust our estimate of the transmission rate to this peer, given
6113 * that the packet p was just acked. We can adjust peer->timeout and
6114 * call->twind. Pragmatically, this is called
6115 * only with packets of maximal length.
6116 * Called with peer and call locked.
6120 rxi_ComputeRate(register struct rx_peer *peer, register struct rx_call *call,
6121 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6123 afs_int32 xferSize, xferMs;
6124 register afs_int32 minTime;
6127 /* Count down packets */
6128 if (peer->rateFlag > 0)
6130 /* Do nothing until we're enabled */
6131 if (peer->rateFlag != 0)
6136 /* Count only when the ack seems legitimate */
6137 switch (ackReason) {
6138 case RX_ACK_REQUESTED:
6140 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6144 case RX_ACK_PING_RESPONSE:
6145 if (p) /* want the response to ping-request, not data send */
6147 clock_GetTime(&newTO);
6148 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6149 clock_Sub(&newTO, &call->pingRequestTime);
6150 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6154 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6161 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));
6163 /* Track only packets that are big enough. */
6164 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6168 /* absorb RTT data (in milliseconds) for these big packets */
6169 if (peer->smRtt == 0) {
6170 peer->smRtt = xferMs;
6172 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6177 if (peer->countDown) {
6181 peer->countDown = 10; /* recalculate only every so often */
6183 /* In practice, we can measure only the RTT for full packets,
6184 * because of the way Rx acks the data that it receives. (If it's
6185 * smaller than a full packet, it often gets implicitly acked
6186 * either by the call response (from a server) or by the next call
6187 * (from a client), and either case confuses transmission times
6188 * with processing times.) Therefore, replace the above
6189 * more-sophisticated processing with a simpler version, where the
6190 * smoothed RTT is kept for full-size packets, and the time to
6191 * transmit a windowful of full-size packets is simply RTT *
6192 * windowSize. Again, we take two steps:
6193 - ensure the timeout is large enough for a single packet's RTT;
6194 - ensure that the window is small enough to fit in the desired timeout.*/
6196 /* First, the timeout check. */
6197 minTime = peer->smRtt;
6198 /* Get a reasonable estimate for a timeout period */
6200 newTO.sec = minTime / 1000;
6201 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6203 /* Increase the timeout period so that we can always do at least
6204 * one packet exchange */
6205 if (clock_Gt(&newTO, &peer->timeout)) {
6207 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));
6209 peer->timeout = newTO;
6212 /* Now, get an estimate for the transmit window size. */
6213 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6214 /* Now, convert to the number of full packets that could fit in a
6215 * reasonable fraction of that interval */
6216 minTime /= (peer->smRtt << 1);
6217 xferSize = minTime; /* (make a copy) */
6219 /* Now clamp the size to reasonable bounds. */
6222 else if (minTime > rx_Window)
6223 minTime = rx_Window;
6224 /* if (minTime != peer->maxWindow) {
6225 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6226 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6227 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6229 peer->maxWindow = minTime;
6230 elide... call->twind = minTime;
6234 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6235 * Discern this by calculating the timeout necessary for rx_Window
6237 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6238 /* calculate estimate for transmission interval in milliseconds */
6239 minTime = rx_Window * peer->smRtt;
6240 if (minTime < 1000) {
6241 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
6242 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6243 peer->timeout.usec, peer->smRtt, peer->packetSize));
6245 newTO.sec = 0; /* cut back on timeout by half a second */
6246 newTO.usec = 500000;
6247 clock_Sub(&peer->timeout, &newTO);
6252 } /* end of rxi_ComputeRate */
6253 #endif /* ADAPT_WINDOW */
6261 #define TRACE_OPTION_DEBUGLOG 4
6269 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6270 0, KEY_QUERY_VALUE, &parmKey);
6271 if (code != ERROR_SUCCESS)
6274 dummyLen = sizeof(TraceOption);
6275 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6276 (BYTE *) &TraceOption, &dummyLen);
6277 if (code == ERROR_SUCCESS) {
6278 rxdebug_active = (TraceOption & TRACE_OPTION_DEBUGLOG) ? 1 : 0;
6280 RegCloseKey (parmKey);
6281 #endif /* AFS_NT40_ENV */
6286 rx_DebugOnOff(int on)
6288 rxdebug_active = on;
6290 #endif /* AFS_NT40_ENV */
6293 /* Don't call this debugging routine directly; use dpf */
6295 rxi_DebugPrint(char *format, int a1, int a2, int a3, int a4, int a5, int a6,
6296 int a7, int a8, int a9, int a10, int a11, int a12, int a13,
6304 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6307 len = _snprintf(msg, sizeof(msg)-2,
6308 tformat, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
6309 a11, a12, a13, a14, a15);
6311 if (msg[len-1] != '\n') {
6315 OutputDebugString(msg);
6320 clock_GetTime(&now);
6321 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
6322 (unsigned int)now.usec / 1000);
6323 fprintf(rx_Log, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12,
6330 * This function is used to process the rx_stats structure that is local
6331 * to a process as well as an rx_stats structure received from a remote
6332 * process (via rxdebug). Therefore, it needs to do minimal version
6336 rx_PrintTheseStats(FILE * file, struct rx_stats *s, int size,
6337 afs_int32 freePackets, char version)
6341 if (size != sizeof(struct rx_stats)) {
6343 "Unexpected size of stats structure: was %d, expected %d\n",
6344 size, sizeof(struct rx_stats));
6347 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6350 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6351 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
6352 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6353 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6354 s->specialPktAllocFailures);
6356 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
6357 s->receivePktAllocFailures, s->sendPktAllocFailures,
6358 s->specialPktAllocFailures);
6362 " greedy %d, " "bogusReads %d (last from host %x), "
6363 "noPackets %d, " "noBuffers %d, " "selects %d, "
6364 "sendSelects %d\n", s->socketGreedy, s->bogusPacketOnRead,
6365 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6366 s->selects, s->sendSelects);
6368 fprintf(file, " packets read: ");
6369 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6370 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsRead[i]);
6372 fprintf(file, "\n");
6375 " other read counters: data %d, " "ack %d, " "dup %d "
6376 "spurious %d " "dally %d\n", s->dataPacketsRead,
6377 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6378 s->ignorePacketDally);
6380 fprintf(file, " packets sent: ");
6381 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6382 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsSent[i]);
6384 fprintf(file, "\n");
6387 " other send counters: ack %d, " "data %d (not resends), "
6388 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6389 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6390 s->dataPacketsPushed, s->ignoreAckedPacket);
6393 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6394 s->netSendFailures, (int)s->fatalErrors);
6396 if (s->nRttSamples) {
6397 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6398 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6400 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6401 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6405 " %d server connections, " "%d client connections, "
6406 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6407 s->nServerConns, s->nClientConns, s->nPeerStructs,
6408 s->nCallStructs, s->nFreeCallStructs);
6410 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6411 fprintf(file, " %d clock updates\n", clock_nUpdates);
6416 /* for backward compatibility */
6418 rx_PrintStats(FILE * file)
6420 MUTEX_ENTER(&rx_stats_mutex);
6421 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6423 MUTEX_EXIT(&rx_stats_mutex);
6427 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6429 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6430 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6431 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6434 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6435 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6436 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6439 " Packet size %d, " "max in packet skew %d, "
6440 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6441 (int)peer->outPacketSkew);
6444 #ifdef AFS_PTHREAD_ENV
6446 * This mutex protects the following static variables:
6450 #define LOCK_RX_DEBUG assert(pthread_mutex_lock(&rx_debug_mutex)==0)
6451 #define UNLOCK_RX_DEBUG assert(pthread_mutex_unlock(&rx_debug_mutex)==0)
6453 #define LOCK_RX_DEBUG
6454 #define UNLOCK_RX_DEBUG
6455 #endif /* AFS_PTHREAD_ENV */
6458 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6459 u_char type, void *inputData, size_t inputLength,
6460 void *outputData, size_t outputLength)
6462 static afs_int32 counter = 100;
6463 time_t waitTime, waitCount, startTime;
6464 struct rx_header theader;
6466 register afs_int32 code;
6467 struct timeval tv_now, tv_wake, tv_delta;
6468 struct sockaddr_in taddr, faddr;
6473 startTime = time(0);
6479 tp = &tbuffer[sizeof(struct rx_header)];
6480 taddr.sin_family = AF_INET;
6481 taddr.sin_port = remotePort;
6482 taddr.sin_addr.s_addr = remoteAddr;
6483 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6484 taddr.sin_len = sizeof(struct sockaddr_in);
6487 memset(&theader, 0, sizeof(theader));
6488 theader.epoch = htonl(999);
6490 theader.callNumber = htonl(counter);
6493 theader.type = type;
6494 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6495 theader.serviceId = 0;
6497 memcpy(tbuffer, &theader, sizeof(theader));
6498 memcpy(tp, inputData, inputLength);
6500 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6501 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6503 /* see if there's a packet available */
6504 gettimeofday(&tv_wake,0);
6505 tv_wake.tv_sec += waitTime;
6508 FD_SET(socket, &imask);
6509 tv_delta.tv_sec = tv_wake.tv_sec;
6510 tv_delta.tv_usec = tv_wake.tv_usec;
6511 gettimeofday(&tv_now, 0);
6513 if (tv_delta.tv_usec < tv_now.tv_usec) {
6515 tv_delta.tv_usec += 1000000;
6518 tv_delta.tv_usec -= tv_now.tv_usec;
6520 if (tv_delta.tv_sec < tv_now.tv_sec) {
6524 tv_delta.tv_sec -= tv_now.tv_sec;
6526 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6527 if (code == 1 && FD_ISSET(socket, &imask)) {
6528 /* now receive a packet */
6529 faddrLen = sizeof(struct sockaddr_in);
6531 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6532 (struct sockaddr *)&faddr, &faddrLen);
6535 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6536 if (counter == ntohl(theader.callNumber))
6544 /* see if we've timed out */
6552 code -= sizeof(struct rx_header);
6553 if (code > outputLength)
6554 code = outputLength;
6555 memcpy(outputData, tp, code);
6560 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6561 afs_uint16 remotePort, struct rx_debugStats * stat,
6562 afs_uint32 * supportedValues)
6564 struct rx_debugIn in;
6567 *supportedValues = 0;
6568 in.type = htonl(RX_DEBUGI_GETSTATS);
6571 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6572 &in, sizeof(in), stat, sizeof(*stat));
6575 * If the call was successful, fixup the version and indicate
6576 * what contents of the stat structure are valid.
6577 * Also do net to host conversion of fields here.
6581 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6582 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6584 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6585 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6587 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6588 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6590 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6591 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6593 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6594 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6596 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6597 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6599 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6600 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6602 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6603 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6606 stat->nFreePackets = ntohl(stat->nFreePackets);
6607 stat->packetReclaims = ntohl(stat->packetReclaims);
6608 stat->callsExecuted = ntohl(stat->callsExecuted);
6609 stat->nWaiting = ntohl(stat->nWaiting);
6610 stat->idleThreads = ntohl(stat->idleThreads);
6617 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6618 afs_uint16 remotePort, struct rx_stats * stat,
6619 afs_uint32 * supportedValues)
6621 struct rx_debugIn in;
6622 afs_int32 *lp = (afs_int32 *) stat;
6627 * supportedValues is currently unused, but added to allow future
6628 * versioning of this function.
6631 *supportedValues = 0;
6632 in.type = htonl(RX_DEBUGI_RXSTATS);
6634 memset(stat, 0, sizeof(*stat));
6636 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6637 &in, sizeof(in), stat, sizeof(*stat));
6642 * Do net to host conversion here
6645 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6654 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6655 afs_uint16 remotePort, size_t version_length,
6659 return MakeDebugCall(socket, remoteAddr, remotePort,
6660 RX_PACKET_TYPE_VERSION, a, 1, version,
6665 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6666 afs_uint16 remotePort, afs_int32 * nextConnection,
6667 int allConnections, afs_uint32 debugSupportedValues,
6668 struct rx_debugConn * conn,
6669 afs_uint32 * supportedValues)
6671 struct rx_debugIn in;
6676 * supportedValues is currently unused, but added to allow future
6677 * versioning of this function.
6680 *supportedValues = 0;
6681 if (allConnections) {
6682 in.type = htonl(RX_DEBUGI_GETALLCONN);
6684 in.type = htonl(RX_DEBUGI_GETCONN);
6686 in.index = htonl(*nextConnection);
6687 memset(conn, 0, sizeof(*conn));
6689 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6690 &in, sizeof(in), conn, sizeof(*conn));
6693 *nextConnection += 1;
6696 * Convert old connection format to new structure.
6699 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6700 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6701 #define MOVEvL(a) (conn->a = vL->a)
6703 /* any old or unrecognized version... */
6704 for (i = 0; i < RX_MAXCALLS; i++) {
6705 MOVEvL(callState[i]);
6706 MOVEvL(callMode[i]);
6707 MOVEvL(callFlags[i]);
6708 MOVEvL(callOther[i]);
6710 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6711 MOVEvL(secStats.type);
6712 MOVEvL(secStats.level);
6713 MOVEvL(secStats.flags);
6714 MOVEvL(secStats.expires);
6715 MOVEvL(secStats.packetsReceived);
6716 MOVEvL(secStats.packetsSent);
6717 MOVEvL(secStats.bytesReceived);
6718 MOVEvL(secStats.bytesSent);
6723 * Do net to host conversion here
6725 * I don't convert host or port since we are most likely
6726 * going to want these in NBO.
6728 conn->cid = ntohl(conn->cid);
6729 conn->serial = ntohl(conn->serial);
6730 for (i = 0; i < RX_MAXCALLS; i++) {
6731 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6733 conn->error = ntohl(conn->error);
6734 conn->secStats.flags = ntohl(conn->secStats.flags);
6735 conn->secStats.expires = ntohl(conn->secStats.expires);
6736 conn->secStats.packetsReceived =
6737 ntohl(conn->secStats.packetsReceived);
6738 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6739 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6740 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6741 conn->epoch = ntohl(conn->epoch);
6742 conn->natMTU = ntohl(conn->natMTU);
6749 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6750 afs_uint16 remotePort, afs_int32 * nextPeer,
6751 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6752 afs_uint32 * supportedValues)
6754 struct rx_debugIn in;
6758 * supportedValues is currently unused, but added to allow future
6759 * versioning of this function.
6762 *supportedValues = 0;
6763 in.type = htonl(RX_DEBUGI_GETPEER);
6764 in.index = htonl(*nextPeer);
6765 memset(peer, 0, sizeof(*peer));
6767 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6768 &in, sizeof(in), peer, sizeof(*peer));
6774 * Do net to host conversion here
6776 * I don't convert host or port since we are most likely
6777 * going to want these in NBO.
6779 peer->ifMTU = ntohs(peer->ifMTU);
6780 peer->idleWhen = ntohl(peer->idleWhen);
6781 peer->refCount = ntohs(peer->refCount);
6782 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6783 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6784 peer->rtt = ntohl(peer->rtt);
6785 peer->rtt_dev = ntohl(peer->rtt_dev);
6786 peer->timeout.sec = ntohl(peer->timeout.sec);
6787 peer->timeout.usec = ntohl(peer->timeout.usec);
6788 peer->nSent = ntohl(peer->nSent);
6789 peer->reSends = ntohl(peer->reSends);
6790 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6791 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6792 peer->rateFlag = ntohl(peer->rateFlag);
6793 peer->natMTU = ntohs(peer->natMTU);
6794 peer->maxMTU = ntohs(peer->maxMTU);
6795 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6796 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
6797 peer->MTU = ntohs(peer->MTU);
6798 peer->cwind = ntohs(peer->cwind);
6799 peer->nDgramPackets = ntohs(peer->nDgramPackets);
6800 peer->congestSeq = ntohs(peer->congestSeq);
6801 peer->bytesSent.high = ntohl(peer->bytesSent.high);
6802 peer->bytesSent.low = ntohl(peer->bytesSent.low);
6803 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
6804 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
6809 #endif /* RXDEBUG */
6814 struct rx_serverQueueEntry *np;
6817 register struct rx_call *call;
6818 register struct rx_serverQueueEntry *sq;
6822 if (rxinit_status == 1) {
6824 return; /* Already shutdown. */
6828 #ifndef AFS_PTHREAD_ENV
6829 FD_ZERO(&rx_selectMask);
6830 #endif /* AFS_PTHREAD_ENV */
6831 rxi_dataQuota = RX_MAX_QUOTA;
6832 #ifndef AFS_PTHREAD_ENV
6834 #endif /* AFS_PTHREAD_ENV */
6837 #ifndef AFS_PTHREAD_ENV
6838 #ifndef AFS_USE_GETTIMEOFDAY
6840 #endif /* AFS_USE_GETTIMEOFDAY */
6841 #endif /* AFS_PTHREAD_ENV */
6843 while (!queue_IsEmpty(&rx_freeCallQueue)) {
6844 call = queue_First(&rx_freeCallQueue, rx_call);
6846 rxi_Free(call, sizeof(struct rx_call));
6849 while (!queue_IsEmpty(&rx_idleServerQueue)) {
6850 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
6856 struct rx_peer **peer_ptr, **peer_end;
6857 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6858 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6860 struct rx_peer *peer, *next;
6861 for (peer = *peer_ptr; peer; peer = next) {
6862 rx_interface_stat_p rpc_stat, nrpc_stat;
6865 (&peer->rpcStats, rpc_stat, nrpc_stat,
6866 rx_interface_stat)) {
6867 unsigned int num_funcs;
6870 queue_Remove(&rpc_stat->queue_header);
6871 queue_Remove(&rpc_stat->all_peers);
6872 num_funcs = rpc_stat->stats[0].func_total;
6874 sizeof(rx_interface_stat_t) +
6875 rpc_stat->stats[0].func_total *
6876 sizeof(rx_function_entry_v1_t);
6878 rxi_Free(rpc_stat, space);
6879 MUTEX_ENTER(&rx_rpc_stats);
6880 rxi_rpc_peer_stat_cnt -= num_funcs;
6881 MUTEX_EXIT(&rx_rpc_stats);
6885 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6889 for (i = 0; i < RX_MAX_SERVICES; i++) {
6891 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
6893 for (i = 0; i < rx_hashTableSize; i++) {
6894 register struct rx_connection *tc, *ntc;
6895 MUTEX_ENTER(&rx_connHashTable_lock);
6896 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
6898 for (j = 0; j < RX_MAXCALLS; j++) {
6900 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
6903 rxi_Free(tc, sizeof(*tc));
6905 MUTEX_EXIT(&rx_connHashTable_lock);
6908 MUTEX_ENTER(&freeSQEList_lock);
6910 while ((np = rx_FreeSQEList)) {
6911 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
6912 MUTEX_DESTROY(&np->lock);
6913 rxi_Free(np, sizeof(*np));
6916 MUTEX_EXIT(&freeSQEList_lock);
6917 MUTEX_DESTROY(&freeSQEList_lock);
6918 MUTEX_DESTROY(&rx_freeCallQueue_lock);
6919 MUTEX_DESTROY(&rx_connHashTable_lock);
6920 MUTEX_DESTROY(&rx_peerHashTable_lock);
6921 MUTEX_DESTROY(&rx_serverPool_lock);
6923 osi_Free(rx_connHashTable,
6924 rx_hashTableSize * sizeof(struct rx_connection *));
6925 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
6927 UNPIN(rx_connHashTable,
6928 rx_hashTableSize * sizeof(struct rx_connection *));
6929 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
6931 rxi_FreeAllPackets();
6933 MUTEX_ENTER(&rx_stats_mutex);
6934 rxi_dataQuota = RX_MAX_QUOTA;
6935 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
6936 MUTEX_EXIT(&rx_stats_mutex);
6942 #ifdef RX_ENABLE_LOCKS
6944 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
6946 if (!MUTEX_ISMINE(lockaddr))
6947 osi_Panic("Lock not held: %s", msg);
6949 #endif /* RX_ENABLE_LOCKS */
6954 * Routines to implement connection specific data.
6958 rx_KeyCreate(rx_destructor_t rtn)
6961 MUTEX_ENTER(&rxi_keyCreate_lock);
6962 key = rxi_keyCreate_counter++;
6963 rxi_keyCreate_destructor = (rx_destructor_t *)
6964 realloc((void *)rxi_keyCreate_destructor,
6965 (key + 1) * sizeof(rx_destructor_t));
6966 rxi_keyCreate_destructor[key] = rtn;
6967 MUTEX_EXIT(&rxi_keyCreate_lock);
6972 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
6975 MUTEX_ENTER(&conn->conn_data_lock);
6976 if (!conn->specific) {
6977 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
6978 for (i = 0; i < key; i++)
6979 conn->specific[i] = NULL;
6980 conn->nSpecific = key + 1;
6981 conn->specific[key] = ptr;
6982 } else if (key >= conn->nSpecific) {
6983 conn->specific = (void **)
6984 realloc(conn->specific, (key + 1) * sizeof(void *));
6985 for (i = conn->nSpecific; i < key; i++)
6986 conn->specific[i] = NULL;
6987 conn->nSpecific = key + 1;
6988 conn->specific[key] = ptr;
6990 if (conn->specific[key] && rxi_keyCreate_destructor[key])
6991 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
6992 conn->specific[key] = ptr;
6994 MUTEX_EXIT(&conn->conn_data_lock);
6998 rx_GetSpecific(struct rx_connection *conn, int key)
7001 MUTEX_ENTER(&conn->conn_data_lock);
7002 if (key >= conn->nSpecific)
7005 ptr = conn->specific[key];
7006 MUTEX_EXIT(&conn->conn_data_lock);
7010 #endif /* !KERNEL */
7013 * processStats is a queue used to store the statistics for the local
7014 * process. Its contents are similar to the contents of the rpcStats
7015 * queue on a rx_peer structure, but the actual data stored within
7016 * this queue contains totals across the lifetime of the process (assuming
7017 * the stats have not been reset) - unlike the per peer structures
7018 * which can come and go based upon the peer lifetime.
7021 static struct rx_queue processStats = { &processStats, &processStats };
7024 * peerStats is a queue used to store the statistics for all peer structs.
7025 * Its contents are the union of all the peer rpcStats queues.
7028 static struct rx_queue peerStats = { &peerStats, &peerStats };
7031 * rxi_monitor_processStats is used to turn process wide stat collection
7035 static int rxi_monitor_processStats = 0;
7038 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7041 static int rxi_monitor_peerStats = 0;
7044 * rxi_AddRpcStat - given all of the information for a particular rpc
7045 * call, create (if needed) and update the stat totals for the rpc.
7049 * IN stats - the queue of stats that will be updated with the new value
7051 * IN rxInterface - a unique number that identifies the rpc interface
7053 * IN currentFunc - the index of the function being invoked
7055 * IN totalFunc - the total number of functions in this interface
7057 * IN queueTime - the amount of time this function waited for a thread
7059 * IN execTime - the amount of time this function invocation took to execute
7061 * IN bytesSent - the number bytes sent by this invocation
7063 * IN bytesRcvd - the number bytes received by this invocation
7065 * IN isServer - if true, this invocation was made to a server
7067 * IN remoteHost - the ip address of the remote host
7069 * IN remotePort - the port of the remote host
7071 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7073 * INOUT counter - if a new stats structure is allocated, the counter will
7074 * be updated with the new number of allocated stat structures
7082 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7083 afs_uint32 currentFunc, afs_uint32 totalFunc,
7084 struct clock *queueTime, struct clock *execTime,
7085 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7086 afs_uint32 remoteHost, afs_uint32 remotePort,
7087 int addToPeerList, unsigned int *counter)
7090 rx_interface_stat_p rpc_stat, nrpc_stat;
7093 * See if there's already a structure for this interface
7096 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7097 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7098 && (rpc_stat->stats[0].remote_is_server == isServer))
7103 * Didn't find a match so allocate a new structure and add it to the
7107 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7108 || (rpc_stat->stats[0].interfaceId != rxInterface)
7109 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7114 sizeof(rx_interface_stat_t) +
7115 totalFunc * sizeof(rx_function_entry_v1_t);
7117 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7118 if (rpc_stat == NULL) {
7122 *counter += totalFunc;
7123 for (i = 0; i < totalFunc; i++) {
7124 rpc_stat->stats[i].remote_peer = remoteHost;
7125 rpc_stat->stats[i].remote_port = remotePort;
7126 rpc_stat->stats[i].remote_is_server = isServer;
7127 rpc_stat->stats[i].interfaceId = rxInterface;
7128 rpc_stat->stats[i].func_total = totalFunc;
7129 rpc_stat->stats[i].func_index = i;
7130 hzero(rpc_stat->stats[i].invocations);
7131 hzero(rpc_stat->stats[i].bytes_sent);
7132 hzero(rpc_stat->stats[i].bytes_rcvd);
7133 rpc_stat->stats[i].queue_time_sum.sec = 0;
7134 rpc_stat->stats[i].queue_time_sum.usec = 0;
7135 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7136 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7137 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7138 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7139 rpc_stat->stats[i].queue_time_max.sec = 0;
7140 rpc_stat->stats[i].queue_time_max.usec = 0;
7141 rpc_stat->stats[i].execution_time_sum.sec = 0;
7142 rpc_stat->stats[i].execution_time_sum.usec = 0;
7143 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7144 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7145 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7146 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7147 rpc_stat->stats[i].execution_time_max.sec = 0;
7148 rpc_stat->stats[i].execution_time_max.usec = 0;
7150 queue_Prepend(stats, rpc_stat);
7151 if (addToPeerList) {
7152 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7157 * Increment the stats for this function
7160 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7161 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7162 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7163 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7164 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7165 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7166 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7168 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7169 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7171 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7172 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7174 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7175 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7177 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7178 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7186 * rx_IncrementTimeAndCount - increment the times and count for a particular
7191 * IN peer - the peer who invoked the rpc
7193 * IN rxInterface - a unique number that identifies the rpc interface
7195 * IN currentFunc - the index of the function being invoked
7197 * IN totalFunc - the total number of functions in this interface
7199 * IN queueTime - the amount of time this function waited for a thread
7201 * IN execTime - the amount of time this function invocation took to execute
7203 * IN bytesSent - the number bytes sent by this invocation
7205 * IN bytesRcvd - the number bytes received by this invocation
7207 * IN isServer - if true, this invocation was made to a server
7215 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7216 afs_uint32 currentFunc, afs_uint32 totalFunc,
7217 struct clock *queueTime, struct clock *execTime,
7218 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7222 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7225 MUTEX_ENTER(&rx_rpc_stats);
7226 MUTEX_ENTER(&peer->peer_lock);
7228 if (rxi_monitor_peerStats) {
7229 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7230 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7231 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7234 if (rxi_monitor_processStats) {
7235 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7236 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7237 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7240 MUTEX_EXIT(&peer->peer_lock);
7241 MUTEX_EXIT(&rx_rpc_stats);
7246 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7250 * IN callerVersion - the rpc stat version of the caller.
7252 * IN count - the number of entries to marshall.
7254 * IN stats - pointer to stats to be marshalled.
7256 * OUT ptr - Where to store the marshalled data.
7263 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7264 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7270 * We only support the first version
7272 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7273 *(ptr++) = stats->remote_peer;
7274 *(ptr++) = stats->remote_port;
7275 *(ptr++) = stats->remote_is_server;
7276 *(ptr++) = stats->interfaceId;
7277 *(ptr++) = stats->func_total;
7278 *(ptr++) = stats->func_index;
7279 *(ptr++) = hgethi(stats->invocations);
7280 *(ptr++) = hgetlo(stats->invocations);
7281 *(ptr++) = hgethi(stats->bytes_sent);
7282 *(ptr++) = hgetlo(stats->bytes_sent);
7283 *(ptr++) = hgethi(stats->bytes_rcvd);
7284 *(ptr++) = hgetlo(stats->bytes_rcvd);
7285 *(ptr++) = stats->queue_time_sum.sec;
7286 *(ptr++) = stats->queue_time_sum.usec;
7287 *(ptr++) = stats->queue_time_sum_sqr.sec;
7288 *(ptr++) = stats->queue_time_sum_sqr.usec;
7289 *(ptr++) = stats->queue_time_min.sec;
7290 *(ptr++) = stats->queue_time_min.usec;
7291 *(ptr++) = stats->queue_time_max.sec;
7292 *(ptr++) = stats->queue_time_max.usec;
7293 *(ptr++) = stats->execution_time_sum.sec;
7294 *(ptr++) = stats->execution_time_sum.usec;
7295 *(ptr++) = stats->execution_time_sum_sqr.sec;
7296 *(ptr++) = stats->execution_time_sum_sqr.usec;
7297 *(ptr++) = stats->execution_time_min.sec;
7298 *(ptr++) = stats->execution_time_min.usec;
7299 *(ptr++) = stats->execution_time_max.sec;
7300 *(ptr++) = stats->execution_time_max.usec;
7306 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7311 * IN callerVersion - the rpc stat version of the caller
7313 * OUT myVersion - the rpc stat version of this function
7315 * OUT clock_sec - local time seconds
7317 * OUT clock_usec - local time microseconds
7319 * OUT allocSize - the number of bytes allocated to contain stats
7321 * OUT statCount - the number stats retrieved from this process.
7323 * OUT stats - the actual stats retrieved from this process.
7327 * Returns void. If successful, stats will != NULL.
7331 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7332 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7333 size_t * allocSize, afs_uint32 * statCount,
7334 afs_uint32 ** stats)
7344 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7347 * Check to see if stats are enabled
7350 MUTEX_ENTER(&rx_rpc_stats);
7351 if (!rxi_monitor_processStats) {
7352 MUTEX_EXIT(&rx_rpc_stats);
7356 clock_GetTime(&now);
7357 *clock_sec = now.sec;
7358 *clock_usec = now.usec;
7361 * Allocate the space based upon the caller version
7363 * If the client is at an older version than we are,
7364 * we return the statistic data in the older data format, but
7365 * we still return our version number so the client knows we
7366 * are maintaining more data than it can retrieve.
7369 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7370 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7371 *statCount = rxi_rpc_process_stat_cnt;
7374 * This can't happen yet, but in the future version changes
7375 * can be handled by adding additional code here
7379 if (space > (size_t) 0) {
7381 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7384 rx_interface_stat_p rpc_stat, nrpc_stat;
7388 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7390 * Copy the data based upon the caller version
7392 rx_MarshallProcessRPCStats(callerVersion,
7393 rpc_stat->stats[0].func_total,
7394 rpc_stat->stats, &ptr);
7400 MUTEX_EXIT(&rx_rpc_stats);
7405 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7409 * IN callerVersion - the rpc stat version of the caller
7411 * OUT myVersion - the rpc stat version of this function
7413 * OUT clock_sec - local time seconds
7415 * OUT clock_usec - local time microseconds
7417 * OUT allocSize - the number of bytes allocated to contain stats
7419 * OUT statCount - the number of stats retrieved from the individual
7422 * OUT stats - the actual stats retrieved from the individual peer structures.
7426 * Returns void. If successful, stats will != NULL.
7430 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7431 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7432 size_t * allocSize, afs_uint32 * statCount,
7433 afs_uint32 ** stats)
7443 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7446 * Check to see if stats are enabled
7449 MUTEX_ENTER(&rx_rpc_stats);
7450 if (!rxi_monitor_peerStats) {
7451 MUTEX_EXIT(&rx_rpc_stats);
7455 clock_GetTime(&now);
7456 *clock_sec = now.sec;
7457 *clock_usec = now.usec;
7460 * Allocate the space based upon the caller version
7462 * If the client is at an older version than we are,
7463 * we return the statistic data in the older data format, but
7464 * we still return our version number so the client knows we
7465 * are maintaining more data than it can retrieve.
7468 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7469 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7470 *statCount = rxi_rpc_peer_stat_cnt;
7473 * This can't happen yet, but in the future version changes
7474 * can be handled by adding additional code here
7478 if (space > (size_t) 0) {
7480 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7483 rx_interface_stat_p rpc_stat, nrpc_stat;
7487 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7489 * We have to fix the offset of rpc_stat since we are
7490 * keeping this structure on two rx_queues. The rx_queue
7491 * package assumes that the rx_queue member is the first
7492 * member of the structure. That is, rx_queue assumes that
7493 * any one item is only on one queue at a time. We are
7494 * breaking that assumption and so we have to do a little
7495 * math to fix our pointers.
7498 fix_offset = (char *)rpc_stat;
7499 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7500 rpc_stat = (rx_interface_stat_p) fix_offset;
7503 * Copy the data based upon the caller version
7505 rx_MarshallProcessRPCStats(callerVersion,
7506 rpc_stat->stats[0].func_total,
7507 rpc_stat->stats, &ptr);
7513 MUTEX_EXIT(&rx_rpc_stats);
7518 * rx_FreeRPCStats - free memory allocated by
7519 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7523 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7524 * rx_RetrievePeerRPCStats
7526 * IN allocSize - the number of bytes in stats.
7534 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7536 rxi_Free(stats, allocSize);
7540 * rx_queryProcessRPCStats - see if process rpc stat collection is
7541 * currently enabled.
7547 * Returns 0 if stats are not enabled != 0 otherwise
7551 rx_queryProcessRPCStats(void)
7554 MUTEX_ENTER(&rx_rpc_stats);
7555 rc = rxi_monitor_processStats;
7556 MUTEX_EXIT(&rx_rpc_stats);
7561 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7567 * Returns 0 if stats are not enabled != 0 otherwise
7571 rx_queryPeerRPCStats(void)
7574 MUTEX_ENTER(&rx_rpc_stats);
7575 rc = rxi_monitor_peerStats;
7576 MUTEX_EXIT(&rx_rpc_stats);
7581 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7591 rx_enableProcessRPCStats(void)
7593 MUTEX_ENTER(&rx_rpc_stats);
7594 rx_enable_stats = 1;
7595 rxi_monitor_processStats = 1;
7596 MUTEX_EXIT(&rx_rpc_stats);
7600 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7610 rx_enablePeerRPCStats(void)
7612 MUTEX_ENTER(&rx_rpc_stats);
7613 rx_enable_stats = 1;
7614 rxi_monitor_peerStats = 1;
7615 MUTEX_EXIT(&rx_rpc_stats);
7619 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7629 rx_disableProcessRPCStats(void)
7631 rx_interface_stat_p rpc_stat, nrpc_stat;
7634 MUTEX_ENTER(&rx_rpc_stats);
7637 * Turn off process statistics and if peer stats is also off, turn
7641 rxi_monitor_processStats = 0;
7642 if (rxi_monitor_peerStats == 0) {
7643 rx_enable_stats = 0;
7646 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7647 unsigned int num_funcs = 0;
7650 queue_Remove(rpc_stat);
7651 num_funcs = rpc_stat->stats[0].func_total;
7653 sizeof(rx_interface_stat_t) +
7654 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7656 rxi_Free(rpc_stat, space);
7657 rxi_rpc_process_stat_cnt -= num_funcs;
7659 MUTEX_EXIT(&rx_rpc_stats);
7663 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7673 rx_disablePeerRPCStats(void)
7675 struct rx_peer **peer_ptr, **peer_end;
7678 MUTEX_ENTER(&rx_rpc_stats);
7681 * Turn off peer statistics and if process stats is also off, turn
7685 rxi_monitor_peerStats = 0;
7686 if (rxi_monitor_processStats == 0) {
7687 rx_enable_stats = 0;
7690 MUTEX_ENTER(&rx_peerHashTable_lock);
7691 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7692 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7694 struct rx_peer *peer, *next, *prev;
7695 for (prev = peer = *peer_ptr; peer; peer = next) {
7697 code = MUTEX_TRYENTER(&peer->peer_lock);
7699 rx_interface_stat_p rpc_stat, nrpc_stat;
7702 (&peer->rpcStats, rpc_stat, nrpc_stat,
7703 rx_interface_stat)) {
7704 unsigned int num_funcs = 0;
7707 queue_Remove(&rpc_stat->queue_header);
7708 queue_Remove(&rpc_stat->all_peers);
7709 num_funcs = rpc_stat->stats[0].func_total;
7711 sizeof(rx_interface_stat_t) +
7712 rpc_stat->stats[0].func_total *
7713 sizeof(rx_function_entry_v1_t);
7715 rxi_Free(rpc_stat, space);
7716 rxi_rpc_peer_stat_cnt -= num_funcs;
7718 MUTEX_EXIT(&peer->peer_lock);
7719 if (prev == *peer_ptr) {
7729 MUTEX_EXIT(&rx_peerHashTable_lock);
7730 MUTEX_EXIT(&rx_rpc_stats);
7734 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7739 * IN clearFlag - flag indicating which stats to clear
7747 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7749 rx_interface_stat_p rpc_stat, nrpc_stat;
7751 MUTEX_ENTER(&rx_rpc_stats);
7753 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7754 unsigned int num_funcs = 0, i;
7755 num_funcs = rpc_stat->stats[0].func_total;
7756 for (i = 0; i < num_funcs; i++) {
7757 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7758 hzero(rpc_stat->stats[i].invocations);
7760 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7761 hzero(rpc_stat->stats[i].bytes_sent);
7763 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7764 hzero(rpc_stat->stats[i].bytes_rcvd);
7766 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7767 rpc_stat->stats[i].queue_time_sum.sec = 0;
7768 rpc_stat->stats[i].queue_time_sum.usec = 0;
7770 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7771 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7772 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7774 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7775 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7776 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7778 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7779 rpc_stat->stats[i].queue_time_max.sec = 0;
7780 rpc_stat->stats[i].queue_time_max.usec = 0;
7782 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7783 rpc_stat->stats[i].execution_time_sum.sec = 0;
7784 rpc_stat->stats[i].execution_time_sum.usec = 0;
7786 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7787 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7788 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7790 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7791 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7792 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7794 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7795 rpc_stat->stats[i].execution_time_max.sec = 0;
7796 rpc_stat->stats[i].execution_time_max.usec = 0;
7801 MUTEX_EXIT(&rx_rpc_stats);
7805 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
7810 * IN clearFlag - flag indicating which stats to clear
7818 rx_clearPeerRPCStats(afs_uint32 clearFlag)
7820 rx_interface_stat_p rpc_stat, nrpc_stat;
7822 MUTEX_ENTER(&rx_rpc_stats);
7824 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7825 unsigned int num_funcs = 0, i;
7828 * We have to fix the offset of rpc_stat since we are
7829 * keeping this structure on two rx_queues. The rx_queue
7830 * package assumes that the rx_queue member is the first
7831 * member of the structure. That is, rx_queue assumes that
7832 * any one item is only on one queue at a time. We are
7833 * breaking that assumption and so we have to do a little
7834 * math to fix our pointers.
7837 fix_offset = (char *)rpc_stat;
7838 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7839 rpc_stat = (rx_interface_stat_p) fix_offset;
7841 num_funcs = rpc_stat->stats[0].func_total;
7842 for (i = 0; i < num_funcs; i++) {
7843 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7844 hzero(rpc_stat->stats[i].invocations);
7846 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7847 hzero(rpc_stat->stats[i].bytes_sent);
7849 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7850 hzero(rpc_stat->stats[i].bytes_rcvd);
7852 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7853 rpc_stat->stats[i].queue_time_sum.sec = 0;
7854 rpc_stat->stats[i].queue_time_sum.usec = 0;
7856 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7857 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7858 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7860 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7861 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7862 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7864 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7865 rpc_stat->stats[i].queue_time_max.sec = 0;
7866 rpc_stat->stats[i].queue_time_max.usec = 0;
7868 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7869 rpc_stat->stats[i].execution_time_sum.sec = 0;
7870 rpc_stat->stats[i].execution_time_sum.usec = 0;
7872 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7873 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7874 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7876 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7877 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7878 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7880 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7881 rpc_stat->stats[i].execution_time_max.sec = 0;
7882 rpc_stat->stats[i].execution_time_max.usec = 0;
7887 MUTEX_EXIT(&rx_rpc_stats);
7891 * rxi_rxstat_userok points to a routine that returns 1 if the caller
7892 * is authorized to enable/disable/clear RX statistics.
7894 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
7897 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
7899 rxi_rxstat_userok = proc;
7903 rx_RxStatUserOk(struct rx_call *call)
7905 if (!rxi_rxstat_userok)
7907 return rxi_rxstat_userok(call);
7912 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
7913 * function in the MSVC runtime DLL (msvcrt.dll).
7915 * Note: the system serializes calls to this function.
7918 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
7919 DWORD reason, /* reason function is being called */
7920 LPVOID reserved) /* reserved for future use */
7923 case DLL_PROCESS_ATTACH:
7924 /* library is being attached to a process */
7928 case DLL_PROCESS_DETACH: