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"
72 #include "rx_internal.h"
74 #include "rx_globals.h"
76 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
77 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
78 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
80 extern afs_int32 afs_termState;
82 #include "sys/lockl.h"
83 #include "sys/lock_def.h"
84 #endif /* AFS_AIX41_ENV */
85 # include "rxgen_consts.h"
87 # include <sys/types.h>
94 # include <afs/afsutil.h>
95 # include <WINNT\afsreg.h>
97 # include <sys/socket.h>
98 # include <sys/file.h>
100 # include <sys/stat.h>
101 # include <netinet/in.h>
102 # include <sys/time.h>
104 # include "rx_internal.h"
106 # include "rx_user.h"
107 # include "rx_clock.h"
108 # include "rx_queue.h"
109 # include "rx_globals.h"
110 # include "rx_trace.h"
111 # include <afs/rxgen_consts.h>
115 #ifdef AFS_PTHREAD_ENV
117 int (*registerProgram) (pid_t, char *) = 0;
118 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
121 int (*registerProgram) (PROCESS, char *) = 0;
122 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
126 /* Local static routines */
127 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
128 #ifdef RX_ENABLE_LOCKS
129 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
132 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
134 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
135 afs_int32 rxi_start_in_error;
137 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
140 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
141 * currently allocated within rx. This number is used to allocate the
142 * memory required to return the statistics when queried.
145 static unsigned int rxi_rpc_peer_stat_cnt;
148 * rxi_rpc_process_stat_cnt counts the total number of local process stat
149 * structures currently allocated within rx. The number is used to allocate
150 * the memory required to return the statistics when queried.
153 static unsigned int rxi_rpc_process_stat_cnt;
155 #if !defined(offsetof)
156 #include <stddef.h> /* for definition of offsetof() */
159 #ifdef AFS_PTHREAD_ENV
163 * Use procedural initialization of mutexes/condition variables
167 extern afs_kmutex_t rx_stats_mutex;
168 extern afs_kmutex_t rx_waiting_mutex;
169 extern afs_kmutex_t rx_quota_mutex;
170 extern afs_kmutex_t rx_pthread_mutex;
171 extern afs_kmutex_t rx_packets_mutex;
172 extern afs_kmutex_t des_init_mutex;
173 extern afs_kmutex_t des_random_mutex;
174 extern afs_kmutex_t rx_clock_mutex;
175 extern afs_kmutex_t rxi_connCacheMutex;
176 extern afs_kmutex_t rx_event_mutex;
177 extern afs_kmutex_t osi_malloc_mutex;
178 extern afs_kmutex_t event_handler_mutex;
179 extern afs_kmutex_t listener_mutex;
180 extern afs_kmutex_t rx_if_init_mutex;
181 extern afs_kmutex_t rx_if_mutex;
182 extern afs_kmutex_t rxkad_client_uid_mutex;
183 extern afs_kmutex_t rxkad_random_mutex;
185 extern afs_kcondvar_t rx_event_handler_cond;
186 extern afs_kcondvar_t rx_listener_cond;
188 static afs_kmutex_t epoch_mutex;
189 static afs_kmutex_t rx_init_mutex;
190 static afs_kmutex_t rx_debug_mutex;
191 static afs_kmutex_t rx_rpc_stats;
194 rxi_InitPthread(void)
196 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_waiting_mutex, "waiting", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
217 assert(pthread_cond_init
218 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
219 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
221 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
222 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
224 rxkad_global_stats_init();
226 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
228 #ifdef RX_ENABLE_LOCKS
231 #endif /* RX_LOCKS_DB */
232 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
233 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
235 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
237 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
239 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
241 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
242 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
243 #endif /* RX_ENABLE_LOCKS */
246 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
247 #define INIT_PTHREAD_LOCKS \
248 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
250 * The rx_stats_mutex mutex protects the following global variables:
251 * rxi_lowConnRefCount
252 * rxi_lowPeerRefCount
261 * The rx_quota_mutex mutex protects the following global variables:
269 * The rx_freePktQ_lock protects the following global variables:
274 * The rx_packets_mutex mutex protects the following global variables:
282 * The rx_pthread_mutex mutex protects the following global variables:
286 #define INIT_PTHREAD_LOCKS
290 /* Variables for handling the minProcs implementation. availProcs gives the
291 * number of threads available in the pool at this moment (not counting dudes
292 * executing right now). totalMin gives the total number of procs required
293 * for handling all minProcs requests. minDeficit is a dynamic variable
294 * tracking the # of procs required to satisfy all of the remaining minProcs
296 * For fine grain locking to work, the quota check and the reservation of
297 * a server thread has to come while rxi_availProcs and rxi_minDeficit
298 * are locked. To this end, the code has been modified under #ifdef
299 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
300 * same time. A new function, ReturnToServerPool() returns the allocation.
302 * A call can be on several queue's (but only one at a time). When
303 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
304 * that no one else is touching the queue. To this end, we store the address
305 * of the queue lock in the call structure (under the call lock) when we
306 * put the call on a queue, and we clear the call_queue_lock when the
307 * call is removed from a queue (once the call lock has been obtained).
308 * This allows rxi_ResetCall to safely synchronize with others wishing
309 * to manipulate the queue.
312 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
313 static afs_kmutex_t rx_rpc_stats;
314 void rxi_StartUnlocked(struct rxevent *event, void *call,
315 void *arg1, int istack);
318 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
319 ** pretty good that the next packet coming in is from the same connection
320 ** as the last packet, since we're send multiple packets in a transmit window.
322 struct rx_connection *rxLastConn = 0;
324 #ifdef RX_ENABLE_LOCKS
325 /* The locking hierarchy for rx fine grain locking is composed of these
328 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
329 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
330 * call->lock - locks call data fields.
331 * These are independent of each other:
332 * rx_freeCallQueue_lock
337 * serverQueueEntry->lock
339 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
340 * peer->lock - locks peer data fields.
341 * conn_data_lock - that more than one thread is not updating a conn data
342 * field at the same time.
350 * Do we need a lock to protect the peer field in the conn structure?
351 * conn->peer was previously a constant for all intents and so has no
352 * lock protecting this field. The multihomed client delta introduced
353 * a RX code change : change the peer field in the connection structure
354 * to that remote inetrface from which the last packet for this
355 * connection was sent out. This may become an issue if further changes
358 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
359 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
361 /* rxdb_fileID is used to identify the lock location, along with line#. */
362 static int rxdb_fileID = RXDB_FILE_RX;
363 #endif /* RX_LOCKS_DB */
364 #else /* RX_ENABLE_LOCKS */
365 #define SET_CALL_QUEUE_LOCK(C, L)
366 #define CLEAR_CALL_QUEUE_LOCK(C)
367 #endif /* RX_ENABLE_LOCKS */
368 struct rx_serverQueueEntry *rx_waitForPacket = 0;
369 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
371 /* ------------Exported Interfaces------------- */
373 /* This function allows rxkad to set the epoch to a suitably random number
374 * which rx_NewConnection will use in the future. The principle purpose is to
375 * get rxnull connections to use the same epoch as the rxkad connections do, at
376 * least once the first rxkad connection is established. This is important now
377 * that the host/port addresses aren't used in FindConnection: the uniqueness
378 * of epoch/cid matters and the start time won't do. */
380 #ifdef AFS_PTHREAD_ENV
382 * This mutex protects the following global variables:
386 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
387 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
391 #endif /* AFS_PTHREAD_ENV */
394 rx_SetEpoch(afs_uint32 epoch)
401 /* Initialize rx. A port number may be mentioned, in which case this
402 * becomes the default port number for any service installed later.
403 * If 0 is provided for the port number, a random port will be chosen
404 * by the kernel. Whether this will ever overlap anything in
405 * /etc/services is anybody's guess... Returns 0 on success, -1 on
410 int rxinit_status = 1;
411 #ifdef AFS_PTHREAD_ENV
413 * This mutex protects the following global variables:
417 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
418 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
421 #define UNLOCK_RX_INIT
425 rx_InitHost(u_int host, u_int port)
432 char *htable, *ptable;
439 if (rxinit_status == 0) {
440 tmp_status = rxinit_status;
442 return tmp_status; /* Already started; return previous error code. */
448 if (afs_winsockInit() < 0)
454 * Initialize anything necessary to provide a non-premptive threading
457 rxi_InitializeThreadSupport();
460 /* Allocate and initialize a socket for client and perhaps server
463 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
464 if (rx_socket == OSI_NULLSOCKET) {
468 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
471 #endif /* RX_LOCKS_DB */
472 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_waiting_mutex, "rx_waiting_mutex", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
477 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
478 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
479 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
480 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
482 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
484 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
486 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
488 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
489 #if defined(AFS_HPUX110_ENV)
491 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
492 #endif /* AFS_HPUX110_ENV */
493 #endif /* RX_ENABLE_LOCKS && KERNEL */
496 rx_connDeadTime = 12;
497 rx_tranquil = 0; /* reset flag */
498 memset((char *)&rx_stats, 0, sizeof(struct rx_statistics));
500 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
501 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
502 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
503 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
504 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
505 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
507 /* Malloc up a bunch of packets & buffers */
509 queue_Init(&rx_freePacketQueue);
510 rxi_NeedMorePackets = FALSE;
511 #ifdef RX_ENABLE_TSFPQ
512 rx_nPackets = 0; /* in TSFPQ version, rx_nPackets is managed by rxi_MorePackets* */
513 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
514 #else /* RX_ENABLE_TSFPQ */
515 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
516 rxi_MorePackets(rx_nPackets);
517 #endif /* RX_ENABLE_TSFPQ */
524 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
525 tv.tv_sec = clock_now.sec;
526 tv.tv_usec = clock_now.usec;
527 srand((unsigned int)tv.tv_usec);
534 #if defined(KERNEL) && !defined(UKERNEL)
535 /* Really, this should never happen in a real kernel */
538 struct sockaddr_in addr;
540 int addrlen = sizeof(addr);
542 socklen_t addrlen = sizeof(addr);
544 if (getsockname((int)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
548 rx_port = addr.sin_port;
551 rx_stats.minRtt.sec = 9999999;
553 rx_SetEpoch(tv.tv_sec | 0x80000000);
555 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
556 * will provide a randomer value. */
558 rx_MutexAdd(rxi_dataQuota, rx_extraQuota, rx_quota_mutex); /* + extra pkts caller asked to rsrv */
559 /* *Slightly* random start time for the cid. This is just to help
560 * out with the hashing function at the peer */
561 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
562 rx_connHashTable = (struct rx_connection **)htable;
563 rx_peerHashTable = (struct rx_peer **)ptable;
565 rx_lastAckDelay.sec = 0;
566 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
567 rx_hardAckDelay.sec = 0;
568 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
569 rx_softAckDelay.sec = 0;
570 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
572 rxevent_Init(20, rxi_ReScheduleEvents);
574 /* Initialize various global queues */
575 queue_Init(&rx_idleServerQueue);
576 queue_Init(&rx_incomingCallQueue);
577 queue_Init(&rx_freeCallQueue);
579 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
580 /* Initialize our list of usable IP addresses. */
584 /* Start listener process (exact function is dependent on the
585 * implementation environment--kernel or user space) */
589 tmp_status = rxinit_status = 0;
597 return rx_InitHost(htonl(INADDR_ANY), port);
600 /* called with unincremented nRequestsRunning to see if it is OK to start
601 * a new thread in this service. Could be "no" for two reasons: over the
602 * max quota, or would prevent others from reaching their min quota.
604 #ifdef RX_ENABLE_LOCKS
605 /* This verion of QuotaOK reserves quota if it's ok while the
606 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
609 QuotaOK(struct rx_service *aservice)
611 /* check if over max quota */
612 if (aservice->nRequestsRunning >= aservice->maxProcs) {
616 /* under min quota, we're OK */
617 /* otherwise, can use only if there are enough to allow everyone
618 * to go to their min quota after this guy starts.
621 MUTEX_ENTER(&rx_quota_mutex);
622 if ((aservice->nRequestsRunning < aservice->minProcs)
623 || (rxi_availProcs > rxi_minDeficit)) {
624 aservice->nRequestsRunning++;
625 /* just started call in minProcs pool, need fewer to maintain
627 if (aservice->nRequestsRunning <= aservice->minProcs)
630 MUTEX_EXIT(&rx_quota_mutex);
633 MUTEX_EXIT(&rx_quota_mutex);
639 ReturnToServerPool(struct rx_service *aservice)
641 aservice->nRequestsRunning--;
642 MUTEX_ENTER(&rx_quota_mutex);
643 if (aservice->nRequestsRunning < aservice->minProcs)
646 MUTEX_EXIT(&rx_quota_mutex);
649 #else /* RX_ENABLE_LOCKS */
651 QuotaOK(struct rx_service *aservice)
654 /* under min quota, we're OK */
655 if (aservice->nRequestsRunning < aservice->minProcs)
658 /* check if over max quota */
659 if (aservice->nRequestsRunning >= aservice->maxProcs)
662 /* otherwise, can use only if there are enough to allow everyone
663 * to go to their min quota after this guy starts.
665 if (rxi_availProcs > rxi_minDeficit)
669 #endif /* RX_ENABLE_LOCKS */
672 /* Called by rx_StartServer to start up lwp's to service calls.
673 NExistingProcs gives the number of procs already existing, and which
674 therefore needn't be created. */
676 rxi_StartServerProcs(int nExistingProcs)
678 struct rx_service *service;
683 /* For each service, reserve N processes, where N is the "minimum"
684 * number of processes that MUST be able to execute a request in parallel,
685 * at any time, for that process. Also compute the maximum difference
686 * between any service's maximum number of processes that can run
687 * (i.e. the maximum number that ever will be run, and a guarantee
688 * that this number will run if other services aren't running), and its
689 * minimum number. The result is the extra number of processes that
690 * we need in order to provide the latter guarantee */
691 for (i = 0; i < RX_MAX_SERVICES; i++) {
693 service = rx_services[i];
694 if (service == (struct rx_service *)0)
696 nProcs += service->minProcs;
697 diff = service->maxProcs - service->minProcs;
701 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
702 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
703 for (i = 0; i < nProcs; i++) {
704 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
710 /* This routine is only required on Windows */
712 rx_StartClientThread(void)
714 #ifdef AFS_PTHREAD_ENV
716 pid = pthread_self();
717 #endif /* AFS_PTHREAD_ENV */
719 #endif /* AFS_NT40_ENV */
721 /* This routine must be called if any services are exported. If the
722 * donateMe flag is set, the calling process is donated to the server
725 rx_StartServer(int donateMe)
727 struct rx_service *service;
733 /* Start server processes, if necessary (exact function is dependent
734 * on the implementation environment--kernel or user space). DonateMe
735 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
736 * case, one less new proc will be created rx_StartServerProcs.
738 rxi_StartServerProcs(donateMe);
740 /* count up the # of threads in minProcs, and add set the min deficit to
741 * be that value, too.
743 for (i = 0; i < RX_MAX_SERVICES; i++) {
744 service = rx_services[i];
745 if (service == (struct rx_service *)0)
747 MUTEX_ENTER(&rx_quota_mutex);
748 rxi_totalMin += service->minProcs;
749 /* below works even if a thread is running, since minDeficit would
750 * still have been decremented and later re-incremented.
752 rxi_minDeficit += service->minProcs;
753 MUTEX_EXIT(&rx_quota_mutex);
756 /* Turn on reaping of idle server connections */
757 rxi_ReapConnections(NULL, NULL, NULL);
766 #ifdef AFS_PTHREAD_ENV
768 pid = (pid_t) pthread_self();
769 #else /* AFS_PTHREAD_ENV */
771 LWP_CurrentProcess(&pid);
772 #endif /* AFS_PTHREAD_ENV */
774 sprintf(name, "srv_%d", ++nProcs);
776 (*registerProgram) (pid, name);
778 #endif /* AFS_NT40_ENV */
779 rx_ServerProc(NULL); /* Never returns */
781 #ifdef RX_ENABLE_TSFPQ
782 /* no use leaving packets around in this thread's local queue if
783 * it isn't getting donated to the server thread pool.
785 rxi_FlushLocalPacketsTSFPQ();
786 #endif /* RX_ENABLE_TSFPQ */
790 /* Create a new client connection to the specified service, using the
791 * specified security object to implement the security model for this
793 struct rx_connection *
794 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
795 struct rx_securityClass *securityObject,
796 int serviceSecurityIndex)
799 afs_int32 cix, nclones;
800 struct rx_connection *conn, *tconn, *ptconn;
805 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n", ntohl(shost), ntohs(sport), sservice, securityObject, serviceSecurityIndex));
808 MUTEX_ENTER(&rx_connHashTable_lock);
811 * allocate the connection and all of its clones.
812 * clones are flagged as such and have their
813 * parent set to the 0th connection object.
815 for (nclones = rx_max_clones_per_connection,
819 ++cix, ptconn = tconn) {
821 tconn = rxi_AllocConnection();
822 tconn->cid = (rx_nextCid += RX_MAXCALLS);
823 tconn->type = RX_CLIENT_CONNECTION;
824 tconn->epoch = rx_epoch;
825 tconn->peer = rxi_FindPeer(shost, sport, 0, 1);
826 tconn->serviceId = sservice;
827 tconn->securityObject = securityObject;
828 tconn->securityData = (void *) 0;
829 tconn->securityIndex = serviceSecurityIndex;
830 tconn->ackRate = RX_FAST_ACK_RATE;
831 tconn->nSpecific = 0;
832 tconn->specific = NULL;
833 tconn->challengeEvent = NULL;
834 tconn->delayedAbortEvent = NULL;
835 tconn->abortCount = 0;
838 for (i = 0; i < RX_MAXCALLS; i++) {
839 tconn->twind[i] = rx_initSendWindow;
840 tconn->rwind[i] = rx_initReceiveWindow;
845 conn->nclones = nclones;
847 conn->next_clone = 0;
848 rx_SetConnDeadTime(conn, rx_connDeadTime);
851 tconn->flags |= RX_CLONED_CONNECTION;
852 tconn->parent = conn;
853 ptconn->next_clone = tconn;
854 tconn->secondsUntilDead = 0;
855 tconn->secondsUntilPing = 0;
858 /* generic connection setup */
859 #ifdef RX_ENABLE_LOCKS
860 MUTEX_INIT(&tconn->conn_call_lock, "conn call lock", MUTEX_DEFAULT,
862 MUTEX_INIT(&tconn->conn_data_lock, "conn data lock", MUTEX_DEFAULT,
864 CV_INIT(&tconn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
866 RXS_NewConnection(securityObject, tconn);
868 CONN_HASH(shost, sport, tconn->cid, tconn->epoch,
869 RX_CLIENT_CONNECTION);
870 rx_AtomicIncrement_NL(tconn->refCount); /* no lock required since only this thread knows */
871 tconn->next = rx_connHashTable[hashindex];
872 rx_connHashTable[hashindex] = tconn;
874 rx_AtomicIncrement(rx_stats.nClientConns, rx_stats_mutex);
877 MUTEX_EXIT(&rx_connHashTable_lock);
883 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
885 /* The idea is to set the dead time to a value that allows several
886 * keepalives to be dropped without timing out the connection. */
887 struct rx_connection *tconn =
888 (rx_IsClonedConn(conn)) ? conn->parent : conn;
890 tconn->secondsUntilDead = MAX(seconds, 6);
891 tconn->secondsUntilPing = rx_ConnSecondsUntilDead(tconn) / 6;
894 rx_atomic_t rxi_lowPeerRefCount = 0;
895 rx_atomic_t rxi_lowConnRefCount = 0;
898 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
899 * NOTE: must not be called with rx_connHashTable_lock held.
902 rxi_CleanupConnection(struct rx_connection *conn)
904 /* Notify the service exporter, if requested, that this connection
905 * is being destroyed */
906 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
907 (*conn->service->destroyConnProc) (conn);
909 /* Notify the security module that this connection is being destroyed */
910 RXS_DestroyConnection(conn->securityObject, conn);
912 /* If this is the last connection using the rx_peer struct, set its
913 * idle time to now. rxi_ReapConnections will reap it if it's still
914 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
916 MUTEX_ENTER(&rx_peerHashTable_lock);
917 if (rx_AtomicDecrement_NL(conn->peer->refCount) < 1) {
918 conn->peer->idleWhen = clock_Sec();
919 if (rx_AtomicPeek_NL(conn->peer->refCount) < 0) {
920 rx_AtomicSwap_NL(&conn->peer->refCount, 0);
921 dpf(("UNDERCOUNT(peer %x)\n", conn->peer));
923 rx_AtomicIncrement(rxi_lowPeerRefCount, rx_stats_mutex);
926 MUTEX_EXIT(&rx_peerHashTable_lock);
930 if (conn->type == RX_SERVER_CONNECTION)
931 rx_AtomicDecrement(rx_stats.nServerConns, rx_stats_mutex);
933 rx_AtomicDecrement(rx_stats.nClientConns, rx_stats_mutex);
936 if (conn->specific) {
938 for (i = 0; i < conn->nSpecific; i++) {
939 if (conn->specific[i] && rxi_keyCreate_destructor[i])
940 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
941 conn->specific[i] = NULL;
943 free(conn->specific);
945 conn->specific = NULL;
949 MUTEX_DESTROY(&conn->conn_call_lock);
950 MUTEX_DESTROY(&conn->conn_data_lock);
951 CV_DESTROY(&conn->conn_call_cv);
953 rxi_FreeConnection(conn);
956 /* Destroy the specified connection */
958 rxi_DestroyConnection(struct rx_connection *conn)
960 struct rx_connection *tconn, *dtconn;
962 MUTEX_ENTER(&rx_connHashTable_lock);
964 /* destroy any clones that might exist */
965 if (!rx_IsClonedConn(conn)) {
966 tconn = conn->next_clone;
967 conn->next_clone = 0; /* once */
971 tconn = tconn->next_clone;
972 rxi_DestroyConnectionNoLock(dtconn);
974 * if destroyed dtconn will be the head of
975 * rx_connCleanup_list. Remove it and clean
976 * it up now as no one else is holding a
979 if (dtconn == rx_connCleanup_list) {
980 rx_connCleanup_list = rx_connCleanup_list->next;
981 MUTEX_EXIT(&rx_connHashTable_lock);
982 /* rxi_CleanupConnection will free dtconn */
983 rxi_CleanupConnection(dtconn);
984 MUTEX_ENTER(&rx_connHashTable_lock);
990 rxi_DestroyConnectionNoLock(conn);
991 /* conn should be at the head of the cleanup list */
992 if (conn == rx_connCleanup_list) {
993 rx_connCleanup_list = rx_connCleanup_list->next;
994 MUTEX_EXIT(&rx_connHashTable_lock);
995 rxi_CleanupConnection(conn);
997 #ifdef RX_ENABLE_LOCKS
999 MUTEX_EXIT(&rx_connHashTable_lock);
1001 #endif /* RX_ENABLE_LOCKS */
1005 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1007 struct rx_connection **conn_ptr;
1009 struct rx_packet *packet;
1016 MUTEX_ENTER(&conn->conn_data_lock);
1017 /* This requires the atomic type to be signed */
1018 if (rx_AtomicDecrement_NL(conn->refCount) < 0) {
1019 dpf(("UNDERCOUNT(conn %x)\n", conn));
1020 if (rx_stats_active) {
1021 rx_AtomicIncrement(rxi_lowConnRefCount, rx_stats_mutex);
1025 if ((rx_AtomicPeek_NL(conn->refCount) > 0) || (conn->flags & RX_CONN_BUSY)) {
1026 /* Busy; wait till the last guy before proceeding */
1027 MUTEX_EXIT(&conn->conn_data_lock);
1032 /* If the client previously called rx_NewCall, but it is still
1033 * waiting, treat this as a running call, and wait to destroy the
1034 * connection later when the call completes. */
1035 if ((conn->type == RX_CLIENT_CONNECTION)
1036 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
1037 conn->flags |= RX_CONN_DESTROY_ME;
1038 MUTEX_EXIT(&conn->conn_data_lock);
1042 MUTEX_EXIT(&conn->conn_data_lock);
1044 /* Check for extant references to this connection */
1045 for (i = 0; i < RX_MAXCALLS; i++) {
1046 struct rx_call *call = conn->call[i];
1049 if (conn->type == RX_CLIENT_CONNECTION) {
1050 MUTEX_ENTER(&call->lock);
1051 if (call->delayedAckEvent) {
1052 /* Push the final acknowledgment out now--there
1053 * won't be a subsequent call to acknowledge the
1054 * last reply packets */
1055 rxevent_Cancel(call->delayedAckEvent, call,
1056 RX_CALL_REFCOUNT_DELAY);
1057 if (call->state == RX_STATE_PRECALL
1058 || call->state == RX_STATE_ACTIVE) {
1059 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1061 rxi_AckAll(NULL, call, 0);
1064 MUTEX_EXIT(&call->lock);
1068 #ifdef RX_ENABLE_LOCKS
1070 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1071 MUTEX_EXIT(&conn->conn_data_lock);
1073 /* Someone is accessing a packet right now. */
1077 #endif /* RX_ENABLE_LOCKS */
1080 /* Don't destroy the connection if there are any call
1081 * structures still in use */
1082 rx_MutexOr(conn->flags, RX_CONN_DESTROY_ME, conn->conn_data_lock);
1087 if (conn->delayedAbortEvent) {
1088 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1089 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1091 MUTEX_ENTER(&conn->conn_data_lock);
1092 rxi_SendConnectionAbort(conn, packet, 0, 1);
1093 MUTEX_EXIT(&conn->conn_data_lock);
1094 rxi_FreePacket(packet);
1098 /* Remove from connection hash table before proceeding */
1100 &rx_connHashTable[CONN_HASH
1101 (peer->host, peer->port, conn->cid, conn->epoch,
1103 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1104 if (*conn_ptr == conn) {
1105 *conn_ptr = conn->next;
1109 /* if the conn that we are destroying was the last connection, then we
1110 * clear rxLastConn as well */
1111 if (rxLastConn == conn)
1114 /* Make sure the connection is completely reset before deleting it. */
1115 /* get rid of pending events that could zap us later */
1116 if (conn->challengeEvent)
1117 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1118 if (conn->checkReachEvent)
1119 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1121 /* Add the connection to the list of destroyed connections that
1122 * need to be cleaned up. This is necessary to avoid deadlocks
1123 * in the routines we call to inform others that this connection is
1124 * being destroyed. */
1125 conn->next = rx_connCleanup_list;
1126 rx_connCleanup_list = conn;
1129 /* Externally available version */
1131 rx_DestroyConnection(struct rx_connection *conn)
1136 rxi_DestroyConnection(conn);
1141 rx_GetConnection(struct rx_connection *conn)
1146 rx_AtomicIncrement(conn->refCount, conn->conn_data_lock);
1150 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1151 /* Wait for the transmit queue to no longer be busy.
1152 * requires the call->lock to be held */
1153 static void rxi_WaitforTQBusy(struct rx_call *call) {
1154 while (call->flags & RX_CALL_TQ_BUSY) {
1155 call->flags |= RX_CALL_TQ_WAIT;
1157 #ifdef RX_ENABLE_LOCKS
1158 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1159 CV_WAIT(&call->cv_tq, &call->lock);
1160 #else /* RX_ENABLE_LOCKS */
1161 osi_rxSleep(&call->tq);
1162 #endif /* RX_ENABLE_LOCKS */
1164 if (call->tqWaiters == 0) {
1165 call->flags &= ~RX_CALL_TQ_WAIT;
1171 /* Start a new rx remote procedure call, on the specified connection.
1172 * If wait is set to 1, wait for a free call channel; otherwise return
1173 * 0. Maxtime gives the maximum number of seconds this call may take,
1174 * after rx_NewCall returns. After this time interval, a call to any
1175 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1176 * For fine grain locking, we hold the conn_call_lock in order to
1177 * to ensure that we don't get signalle after we found a call in an active
1178 * state and before we go to sleep.
1181 rx_NewCall(struct rx_connection *conn)
1184 struct rx_call *call;
1185 struct clock queueTime;
1189 dpf(("rx_NewCall(conn %x)\n", conn));
1192 clock_GetTime(&queueTime);
1193 MUTEX_ENTER(&conn->conn_call_lock);
1196 * Check if there are others waiting for a new call.
1197 * If so, let them go first to avoid starving them.
1198 * This is a fairly simple scheme, and might not be
1199 * a complete solution for large numbers of waiters.
1201 * makeCallWaiters keeps track of the number of
1202 * threads waiting to make calls and the
1203 * RX_CONN_MAKECALL_WAITING flag bit is used to
1204 * indicate that there are indeed calls waiting.
1205 * The flag is set when the waiter is incremented.
1206 * It is only cleared in rx_EndCall when
1207 * makeCallWaiters is 0. This prevents us from
1208 * accidently destroying the connection while it
1209 * is potentially about to be used.
1211 MUTEX_ENTER(&conn->conn_data_lock);
1212 if (conn->makeCallWaiters) {
1213 conn->flags |= RX_CONN_MAKECALL_WAITING;
1214 conn->makeCallWaiters++;
1215 MUTEX_EXIT(&conn->conn_data_lock);
1217 #ifdef RX_ENABLE_LOCKS
1218 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1222 rx_MutexDecrement(conn->makeCallWaiters, conn->conn_data_lock);
1224 MUTEX_EXIT(&conn->conn_data_lock);
1227 /* search for next free call on this connection or
1228 * its clones, if any */
1230 struct rx_connection *tconn;
1232 for (tconn = conn; tconn; tconn = tconn->next_clone) {
1233 for (i = 0; i < RX_MAXCALLS; i++) {
1234 call = tconn->call[i];
1236 MUTEX_ENTER(&call->lock);
1237 if (call->state == RX_STATE_DALLY) {
1238 rxi_ResetCall(call, 0);
1239 (*call->callNumber)++;
1242 MUTEX_EXIT(&call->lock);
1244 call = rxi_NewCall(tconn, i);
1247 } /* for i < RX_MAXCALLS */
1251 * to be here, all available calls for this connection (and all
1252 * of its clones) must be in use
1255 MUTEX_ENTER(&conn->conn_data_lock);
1256 conn->flags |= RX_CONN_MAKECALL_WAITING;
1257 conn->makeCallWaiters++;
1258 MUTEX_EXIT(&conn->conn_data_lock);
1260 #ifdef RX_ENABLE_LOCKS
1261 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1265 rx_MutexDecrement(conn->makeCallWaiters, conn->conn_data_lock);
1270 * Wake up anyone else who might be giving us a chance to
1271 * run (see code above that avoids resource starvation).
1273 #ifdef RX_ENABLE_LOCKS
1274 CV_BROADCAST(&conn->conn_call_cv);
1279 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1281 /* Client is initially in send mode */
1282 call->state = RX_STATE_ACTIVE;
1283 call->error = rx_ConnError(conn);
1285 call->mode = RX_MODE_ERROR;
1287 call->mode = RX_MODE_SENDING;
1289 /* remember start time for call in case we have hard dead time limit */
1290 call->queueTime = queueTime;
1291 clock_GetTime(&call->startTime);
1292 hzero(call->bytesSent);
1293 hzero(call->bytesRcvd);
1295 /* Turn on busy protocol. */
1296 rxi_KeepAliveOn(call);
1298 MUTEX_EXIT(&call->lock);
1299 MUTEX_EXIT(&conn->conn_call_lock);
1302 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1303 /* Now, if TQ wasn't cleared earlier, do it now. */
1304 MUTEX_ENTER(&call->lock);
1305 rxi_WaitforTQBusy(call);
1306 if (call->flags & RX_CALL_TQ_CLEARME) {
1307 rxi_ClearTransmitQueue(call, 1);
1308 /*queue_Init(&call->tq);*/
1310 MUTEX_EXIT(&call->lock);
1311 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1313 dpf(("rx_NewCall(call %x)\n", call));
1318 rxi_HasActiveCalls(struct rx_connection *aconn)
1321 struct rx_call *tcall;
1325 for (i = 0; i < RX_MAXCALLS; i++) {
1326 if ((tcall = aconn->call[i])) {
1327 if ((tcall->state == RX_STATE_ACTIVE)
1328 || (tcall->state == RX_STATE_PRECALL)) {
1339 rxi_GetCallNumberVector(struct rx_connection *aconn,
1340 afs_int32 * aint32s)
1343 struct rx_call *tcall;
1347 for (i = 0; i < RX_MAXCALLS; i++) {
1348 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1349 aint32s[i] = aconn->callNumber[i] + 1;
1351 aint32s[i] = aconn->callNumber[i];
1358 rxi_SetCallNumberVector(struct rx_connection *aconn,
1359 afs_int32 * aint32s)
1362 struct rx_call *tcall;
1366 for (i = 0; i < RX_MAXCALLS; i++) {
1367 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1368 aconn->callNumber[i] = aint32s[i] - 1;
1370 aconn->callNumber[i] = aint32s[i];
1376 /* Advertise a new service. A service is named locally by a UDP port
1377 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1380 char *serviceName; Name for identification purposes (e.g. the
1381 service name might be used for probing for
1384 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1385 char *serviceName, struct rx_securityClass **securityObjects,
1386 int nSecurityObjects,
1387 afs_int32(*serviceProc) (struct rx_call * acall))
1389 osi_socket socket = OSI_NULLSOCKET;
1390 struct rx_service *tservice;
1396 if (serviceId == 0) {
1398 "rx_NewService: service id for service %s is not non-zero.\n",
1405 "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",
1413 tservice = rxi_AllocService();
1415 for (i = 0; i < RX_MAX_SERVICES; i++) {
1416 struct rx_service *service = rx_services[i];
1418 if (port == service->servicePort && host == service->serviceHost) {
1419 if (service->serviceId == serviceId) {
1420 /* The identical service has already been
1421 * installed; if the caller was intending to
1422 * change the security classes used by this
1423 * service, he/she loses. */
1425 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1426 serviceName, serviceId, service->serviceName);
1428 rxi_FreeService(tservice);
1431 /* Different service, same port: re-use the socket
1432 * which is bound to the same port */
1433 socket = service->socket;
1436 if (socket == OSI_NULLSOCKET) {
1437 /* If we don't already have a socket (from another
1438 * service on same port) get a new one */
1439 socket = rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
1440 if (socket == OSI_NULLSOCKET) {
1442 rxi_FreeService(tservice);
1447 service->socket = socket;
1448 service->serviceHost = host;
1449 service->servicePort = port;
1450 service->serviceId = serviceId;
1451 service->serviceName = serviceName;
1452 service->nSecurityObjects = nSecurityObjects;
1453 service->securityObjects = securityObjects;
1454 service->minProcs = 0;
1455 service->maxProcs = 1;
1456 service->idleDeadTime = 60;
1457 service->idleDeadErr = 0;
1458 service->connDeadTime = rx_connDeadTime;
1459 service->executeRequestProc = serviceProc;
1460 service->checkReach = 0;
1461 rx_services[i] = service; /* not visible until now */
1467 rxi_FreeService(tservice);
1468 (osi_Msg "rx_NewService: cannot support > %d services\n",
1473 /* Set configuration options for all of a service's security objects */
1476 rx_SetSecurityConfiguration(struct rx_service *service,
1477 rx_securityConfigVariables type,
1481 for (i = 0; i<service->nSecurityObjects; i++) {
1482 if (service->securityObjects[i]) {
1483 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1491 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1492 struct rx_securityClass **securityObjects, int nSecurityObjects,
1493 afs_int32(*serviceProc) (struct rx_call * acall))
1495 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1498 /* Generic request processing loop. This routine should be called
1499 * by the implementation dependent rx_ServerProc. If socketp is
1500 * non-null, it will be set to the file descriptor that this thread
1501 * is now listening on. If socketp is null, this routine will never
1504 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1506 struct rx_call *call;
1508 struct rx_service *tservice = NULL;
1515 call = rx_GetCall(threadID, tservice, socketp);
1516 if (socketp && *socketp != OSI_NULLSOCKET) {
1517 /* We are now a listener thread */
1522 /* if server is restarting( typically smooth shutdown) then do not
1523 * allow any new calls.
1526 if (rx_tranquil && (call != NULL)) {
1530 MUTEX_ENTER(&call->lock);
1532 rxi_CallError(call, RX_RESTARTING);
1533 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1535 MUTEX_EXIT(&call->lock);
1539 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1540 #ifdef RX_ENABLE_LOCKS
1542 #endif /* RX_ENABLE_LOCKS */
1543 afs_termState = AFSOP_STOP_AFS;
1544 afs_osi_Wakeup(&afs_termState);
1545 #ifdef RX_ENABLE_LOCKS
1547 #endif /* RX_ENABLE_LOCKS */
1552 tservice = call->conn->service;
1554 if (tservice->beforeProc)
1555 (*tservice->beforeProc) (call);
1557 code = call->conn->service->executeRequestProc(call);
1559 if (tservice->afterProc)
1560 (*tservice->afterProc) (call, code);
1562 rx_EndCall(call, code);
1563 if (rx_stats_active)
1564 rx_MutexIncrement(rxi_nCalls, rx_stats_mutex);
1570 rx_WakeupServerProcs(void)
1572 struct rx_serverQueueEntry *np, *tqp;
1576 MUTEX_ENTER(&rx_serverPool_lock);
1578 #ifdef RX_ENABLE_LOCKS
1579 if (rx_waitForPacket)
1580 CV_BROADCAST(&rx_waitForPacket->cv);
1581 #else /* RX_ENABLE_LOCKS */
1582 if (rx_waitForPacket)
1583 osi_rxWakeup(rx_waitForPacket);
1584 #endif /* RX_ENABLE_LOCKS */
1585 MUTEX_ENTER(&freeSQEList_lock);
1586 for (np = rx_FreeSQEList; np; np = tqp) {
1587 tqp = *(struct rx_serverQueueEntry **)np;
1588 #ifdef RX_ENABLE_LOCKS
1589 CV_BROADCAST(&np->cv);
1590 #else /* RX_ENABLE_LOCKS */
1592 #endif /* RX_ENABLE_LOCKS */
1594 MUTEX_EXIT(&freeSQEList_lock);
1595 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1596 #ifdef RX_ENABLE_LOCKS
1597 CV_BROADCAST(&np->cv);
1598 #else /* RX_ENABLE_LOCKS */
1600 #endif /* RX_ENABLE_LOCKS */
1602 MUTEX_EXIT(&rx_serverPool_lock);
1607 * One thing that seems to happen is that all the server threads get
1608 * tied up on some empty or slow call, and then a whole bunch of calls
1609 * arrive at once, using up the packet pool, so now there are more
1610 * empty calls. The most critical resources here are server threads
1611 * and the free packet pool. The "doreclaim" code seems to help in
1612 * general. I think that eventually we arrive in this state: there
1613 * are lots of pending calls which do have all their packets present,
1614 * so they won't be reclaimed, are multi-packet calls, so they won't
1615 * be scheduled until later, and thus are tying up most of the free
1616 * packet pool for a very long time.
1618 * 1. schedule multi-packet calls if all the packets are present.
1619 * Probably CPU-bound operation, useful to return packets to pool.
1620 * Do what if there is a full window, but the last packet isn't here?
1621 * 3. preserve one thread which *only* runs "best" calls, otherwise
1622 * it sleeps and waits for that type of call.
1623 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1624 * the current dataquota business is badly broken. The quota isn't adjusted
1625 * to reflect how many packets are presently queued for a running call.
1626 * So, when we schedule a queued call with a full window of packets queued
1627 * up for it, that *should* free up a window full of packets for other 2d-class
1628 * calls to be able to use from the packet pool. But it doesn't.
1630 * NB. Most of the time, this code doesn't run -- since idle server threads
1631 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1632 * as a new call arrives.
1634 /* Sleep until a call arrives. Returns a pointer to the call, ready
1635 * for an rx_Read. */
1636 #ifdef RX_ENABLE_LOCKS
1638 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1640 struct rx_serverQueueEntry *sq;
1641 struct rx_call *call = (struct rx_call *)0;
1642 struct rx_service *service = NULL;
1645 MUTEX_ENTER(&freeSQEList_lock);
1647 if ((sq = rx_FreeSQEList)) {
1648 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1649 MUTEX_EXIT(&freeSQEList_lock);
1650 } else { /* otherwise allocate a new one and return that */
1651 MUTEX_EXIT(&freeSQEList_lock);
1652 sq = (struct rx_serverQueueEntry *)
1653 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1654 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1655 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1658 MUTEX_ENTER(&rx_serverPool_lock);
1659 if (cur_service != NULL) {
1660 ReturnToServerPool(cur_service);
1663 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1664 struct rx_call *tcall, *ncall, *choice2 = NULL;
1666 /* Scan for eligible incoming calls. A call is not eligible
1667 * if the maximum number of calls for its service type are
1668 * already executing */
1669 /* One thread will process calls FCFS (to prevent starvation),
1670 * while the other threads may run ahead looking for calls which
1671 * have all their input data available immediately. This helps
1672 * keep threads from blocking, waiting for data from the client. */
1673 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1674 service = tcall->conn->service;
1675 if (!QuotaOK(service)) {
1678 MUTEX_ENTER(&rx_pthread_mutex);
1679 if (tno == rxi_fcfs_thread_num
1680 || !tcall->queue_item_header.next) {
1681 MUTEX_EXIT(&rx_pthread_mutex);
1682 /* If we're the fcfs thread , then we'll just use
1683 * this call. If we haven't been able to find an optimal
1684 * choice, and we're at the end of the list, then use a
1685 * 2d choice if one has been identified. Otherwise... */
1686 call = (choice2 ? choice2 : tcall);
1687 service = call->conn->service;
1689 MUTEX_EXIT(&rx_pthread_mutex);
1690 if (!queue_IsEmpty(&tcall->rq)) {
1691 struct rx_packet *rp;
1692 rp = queue_First(&tcall->rq, rx_packet);
1693 if (rp->header.seq == 1) {
1695 || (rp->header.flags & RX_LAST_PACKET)) {
1697 } else if (rxi_2dchoice && !choice2
1698 && !(tcall->flags & RX_CALL_CLEARED)
1699 && (tcall->rprev > rxi_HardAckRate)) {
1709 ReturnToServerPool(service);
1716 MUTEX_EXIT(&rx_serverPool_lock);
1717 MUTEX_ENTER(&call->lock);
1719 if (call->flags & RX_CALL_WAIT_PROC) {
1720 call->flags &= ~RX_CALL_WAIT_PROC;
1721 rx_MutexDecrement(rx_nWaiting, rx_waiting_mutex);
1724 if (call->state != RX_STATE_PRECALL || call->error) {
1725 MUTEX_EXIT(&call->lock);
1726 MUTEX_ENTER(&rx_serverPool_lock);
1727 ReturnToServerPool(service);
1732 if (queue_IsEmpty(&call->rq)
1733 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1734 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1736 CLEAR_CALL_QUEUE_LOCK(call);
1739 /* If there are no eligible incoming calls, add this process
1740 * to the idle server queue, to wait for one */
1744 *socketp = OSI_NULLSOCKET;
1746 sq->socketp = socketp;
1747 queue_Append(&rx_idleServerQueue, sq);
1748 #ifndef AFS_AIX41_ENV
1749 rx_waitForPacket = sq;
1751 rx_waitingForPacket = sq;
1752 #endif /* AFS_AIX41_ENV */
1754 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1756 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1757 MUTEX_EXIT(&rx_serverPool_lock);
1758 return (struct rx_call *)0;
1761 } while (!(call = sq->newcall)
1762 && !(socketp && *socketp != OSI_NULLSOCKET));
1763 MUTEX_EXIT(&rx_serverPool_lock);
1765 MUTEX_ENTER(&call->lock);
1771 MUTEX_ENTER(&freeSQEList_lock);
1772 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1773 rx_FreeSQEList = sq;
1774 MUTEX_EXIT(&freeSQEList_lock);
1777 clock_GetTime(&call->startTime);
1778 call->state = RX_STATE_ACTIVE;
1779 call->mode = RX_MODE_RECEIVING;
1780 #ifdef RX_KERNEL_TRACE
1781 if (ICL_SETACTIVE(afs_iclSetp)) {
1782 int glockOwner = ISAFS_GLOCK();
1785 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1786 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1793 rxi_calltrace(RX_CALL_START, call);
1794 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1795 call->conn->service->servicePort, call->conn->service->serviceId,
1798 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1799 MUTEX_EXIT(&call->lock);
1801 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1806 #else /* RX_ENABLE_LOCKS */
1808 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1810 struct rx_serverQueueEntry *sq;
1811 struct rx_call *call = (struct rx_call *)0, *choice2;
1812 struct rx_service *service = NULL;
1816 MUTEX_ENTER(&freeSQEList_lock);
1818 if ((sq = rx_FreeSQEList)) {
1819 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1820 MUTEX_EXIT(&freeSQEList_lock);
1821 } else { /* otherwise allocate a new one and return that */
1822 MUTEX_EXIT(&freeSQEList_lock);
1823 sq = (struct rx_serverQueueEntry *)
1824 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1825 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1826 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1828 MUTEX_ENTER(&sq->lock);
1830 if (cur_service != NULL) {
1831 cur_service->nRequestsRunning--;
1832 if (cur_service->nRequestsRunning < cur_service->minProcs)
1836 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1837 struct rx_call *tcall, *ncall;
1838 /* Scan for eligible incoming calls. A call is not eligible
1839 * if the maximum number of calls for its service type are
1840 * already executing */
1841 /* One thread will process calls FCFS (to prevent starvation),
1842 * while the other threads may run ahead looking for calls which
1843 * have all their input data available immediately. This helps
1844 * keep threads from blocking, waiting for data from the client. */
1845 choice2 = (struct rx_call *)0;
1846 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1847 service = tcall->conn->service;
1848 if (QuotaOK(service)) {
1849 MUTEX_ENTER(&rx_pthread_mutex);
1850 if (tno == rxi_fcfs_thread_num
1851 || !tcall->queue_item_header.next) {
1852 MUTEX_EXIT(&rx_pthread_mutex);
1853 /* If we're the fcfs thread, then we'll just use
1854 * this call. If we haven't been able to find an optimal
1855 * choice, and we're at the end of the list, then use a
1856 * 2d choice if one has been identified. Otherwise... */
1857 call = (choice2 ? choice2 : tcall);
1858 service = call->conn->service;
1860 MUTEX_EXIT(&rx_pthread_mutex);
1861 if (!queue_IsEmpty(&tcall->rq)) {
1862 struct rx_packet *rp;
1863 rp = queue_First(&tcall->rq, rx_packet);
1864 if (rp->header.seq == 1
1866 || (rp->header.flags & RX_LAST_PACKET))) {
1868 } else if (rxi_2dchoice && !choice2
1869 && !(tcall->flags & RX_CALL_CLEARED)
1870 && (tcall->rprev > rxi_HardAckRate)) {
1884 /* we can't schedule a call if there's no data!!! */
1885 /* send an ack if there's no data, if we're missing the
1886 * first packet, or we're missing something between first
1887 * and last -- there's a "hole" in the incoming data. */
1888 if (queue_IsEmpty(&call->rq)
1889 || queue_First(&call->rq, rx_packet)->header.seq != 1
1890 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1891 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1893 call->flags &= (~RX_CALL_WAIT_PROC);
1894 service->nRequestsRunning++;
1895 /* just started call in minProcs pool, need fewer to maintain
1897 if (service->nRequestsRunning <= service->minProcs)
1901 /* MUTEX_EXIT(&call->lock); */
1903 /* If there are no eligible incoming calls, add this process
1904 * to the idle server queue, to wait for one */
1907 *socketp = OSI_NULLSOCKET;
1909 sq->socketp = socketp;
1910 queue_Append(&rx_idleServerQueue, sq);
1914 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1916 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1917 return (struct rx_call *)0;
1920 } while (!(call = sq->newcall)
1921 && !(socketp && *socketp != OSI_NULLSOCKET));
1923 MUTEX_EXIT(&sq->lock);
1925 MUTEX_ENTER(&freeSQEList_lock);
1926 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1927 rx_FreeSQEList = sq;
1928 MUTEX_EXIT(&freeSQEList_lock);
1931 clock_GetTime(&call->startTime);
1932 call->state = RX_STATE_ACTIVE;
1933 call->mode = RX_MODE_RECEIVING;
1934 #ifdef RX_KERNEL_TRACE
1935 if (ICL_SETACTIVE(afs_iclSetp)) {
1936 int glockOwner = ISAFS_GLOCK();
1939 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1940 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1947 rxi_calltrace(RX_CALL_START, call);
1948 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1949 call->conn->service->servicePort, call->conn->service->serviceId,
1952 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1959 #endif /* RX_ENABLE_LOCKS */
1963 /* Establish a procedure to be called when a packet arrives for a
1964 * call. This routine will be called at most once after each call,
1965 * and will also be called if there is an error condition on the or
1966 * the call is complete. Used by multi rx to build a selection
1967 * function which determines which of several calls is likely to be a
1968 * good one to read from.
1969 * NOTE: the way this is currently implemented it is probably only a
1970 * good idea to (1) use it immediately after a newcall (clients only)
1971 * and (2) only use it once. Other uses currently void your warranty
1974 rx_SetArrivalProc(struct rx_call *call,
1975 void (*proc) (struct rx_call * call,
1978 void * handle, int arg)
1980 call->arrivalProc = proc;
1981 call->arrivalProcHandle = handle;
1982 call->arrivalProcArg = arg;
1985 /* Call is finished (possibly prematurely). Return rc to the peer, if
1986 * appropriate, and return the final error code from the conversation
1990 rx_EndCall(struct rx_call *call, afs_int32 rc)
1992 struct rx_connection *conn = call->conn;
1993 struct rx_service *service;
1999 dpf(("rx_EndCall(call %x rc %d error %d abortCode %d)\n", call, rc, call->error, call->abortCode));
2002 MUTEX_ENTER(&call->lock);
2004 if (rc == 0 && call->error == 0) {
2005 call->abortCode = 0;
2006 call->abortCount = 0;
2009 call->arrivalProc = (void (*)())0;
2010 if (rc && call->error == 0) {
2011 rxi_CallError(call, rc);
2012 /* Send an abort message to the peer if this error code has
2013 * only just been set. If it was set previously, assume the
2014 * peer has already been sent the error code or will request it
2016 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2018 if (conn->type == RX_SERVER_CONNECTION) {
2019 /* Make sure reply or at least dummy reply is sent */
2020 if (call->mode == RX_MODE_RECEIVING) {
2021 rxi_WriteProc(call, 0, 0);
2023 if (call->mode == RX_MODE_SENDING) {
2024 rxi_FlushWrite(call);
2026 service = conn->service;
2027 rxi_calltrace(RX_CALL_END, call);
2028 /* Call goes to hold state until reply packets are acknowledged */
2029 if (call->tfirst + call->nSoftAcked < call->tnext) {
2030 call->state = RX_STATE_HOLD;
2032 call->state = RX_STATE_DALLY;
2033 rxi_ClearTransmitQueue(call, 0);
2034 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2035 rxevent_Cancel(call->keepAliveEvent, call,
2036 RX_CALL_REFCOUNT_ALIVE);
2038 } else { /* Client connection */
2040 /* Make sure server receives input packets, in the case where
2041 * no reply arguments are expected */
2042 if ((call->mode == RX_MODE_SENDING)
2043 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2044 (void)rxi_ReadProc(call, &dummy, 1);
2047 /* If we had an outstanding delayed ack, be nice to the server
2048 * and force-send it now.
2050 if (call->delayedAckEvent) {
2051 rxevent_Cancel(call->delayedAckEvent, call,
2052 RX_CALL_REFCOUNT_DELAY);
2053 call->delayedAckEvent = NULL;
2054 rxi_SendDelayedAck(NULL, call, NULL);
2057 /* We need to release the call lock since it's lower than the
2058 * conn_call_lock and we don't want to hold the conn_call_lock
2059 * over the rx_ReadProc call. The conn_call_lock needs to be held
2060 * here for the case where rx_NewCall is perusing the calls on
2061 * the connection structure. We don't want to signal until
2062 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2063 * have checked this call, found it active and by the time it
2064 * goes to sleep, will have missed the signal.
2066 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2067 * there are threads waiting to use the conn object.
2069 MUTEX_EXIT(&call->lock);
2070 MUTEX_ENTER(&conn->conn_call_lock);
2071 MUTEX_ENTER(&call->lock);
2072 MUTEX_ENTER(&conn->conn_data_lock);
2073 conn->flags |= RX_CONN_BUSY;
2074 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2075 if (conn->makeCallWaiters == 0)
2076 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2077 MUTEX_EXIT(&conn->conn_data_lock);
2078 #ifdef RX_ENABLE_LOCKS
2079 CV_BROADCAST(&conn->conn_call_cv);
2084 #ifdef RX_ENABLE_LOCKS
2086 MUTEX_EXIT(&conn->conn_data_lock);
2088 #endif /* RX_ENABLE_LOCKS */
2089 call->state = RX_STATE_DALLY;
2091 error = call->error;
2093 /* currentPacket, nLeft, and NFree must be zeroed here, because
2094 * ResetCall cannot: ResetCall may be called at splnet(), in the
2095 * kernel version, and may interrupt the macros rx_Read or
2096 * rx_Write, which run at normal priority for efficiency. */
2097 if (call->currentPacket) {
2098 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2099 rxi_FreePacket(call->currentPacket);
2100 call->currentPacket = (struct rx_packet *)0;
2103 call->nLeft = call->nFree = call->curlen = 0;
2105 /* Free any packets from the last call to ReadvProc/WritevProc */
2106 #ifdef RXDEBUG_PACKET
2108 #endif /* RXDEBUG_PACKET */
2109 rxi_FreePackets(0, &call->iovq);
2111 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2112 MUTEX_EXIT(&call->lock);
2113 if (conn->type == RX_CLIENT_CONNECTION) {
2114 MUTEX_EXIT(&conn->conn_call_lock);
2115 conn->flags &= ~RX_CONN_BUSY;
2119 * Map errors to the local host's errno.h format.
2121 error = ntoh_syserr_conv(error);
2125 #if !defined(KERNEL)
2127 /* Call this routine when shutting down a server or client (especially
2128 * clients). This will allow Rx to gracefully garbage collect server
2129 * connections, and reduce the number of retries that a server might
2130 * make to a dead client.
2131 * This is not quite right, since some calls may still be ongoing and
2132 * we can't lock them to destroy them. */
2136 struct rx_connection **conn_ptr, **conn_end;
2140 if (rxinit_status == 1) {
2142 return; /* Already shutdown. */
2144 rxi_DeleteCachedConnections();
2145 if (rx_connHashTable) {
2146 MUTEX_ENTER(&rx_connHashTable_lock);
2147 for (conn_ptr = &rx_connHashTable[0], conn_end =
2148 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2150 struct rx_connection *conn, *next;
2151 for (conn = *conn_ptr; conn; conn = next) {
2153 if (conn->type == RX_CLIENT_CONNECTION) {
2154 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2155 rx_AtomicIncrement(conn->refCount, conn->conn_data_lock);
2156 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2157 #ifdef RX_ENABLE_LOCKS
2158 rxi_DestroyConnectionNoLock(conn);
2159 #else /* RX_ENABLE_LOCKS */
2160 rxi_DestroyConnection(conn);
2161 #endif /* RX_ENABLE_LOCKS */
2165 #ifdef RX_ENABLE_LOCKS
2166 while (rx_connCleanup_list) {
2167 struct rx_connection *conn;
2168 conn = rx_connCleanup_list;
2169 rx_connCleanup_list = rx_connCleanup_list->next;
2170 MUTEX_EXIT(&rx_connHashTable_lock);
2171 rxi_CleanupConnection(conn);
2172 MUTEX_ENTER(&rx_connHashTable_lock);
2174 MUTEX_EXIT(&rx_connHashTable_lock);
2175 #endif /* RX_ENABLE_LOCKS */
2180 afs_winsockCleanup();
2188 /* if we wakeup packet waiter too often, can get in loop with two
2189 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2191 rxi_PacketsUnWait(void)
2193 if (!rx_waitingForPackets) {
2197 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2198 return; /* still over quota */
2201 rx_waitingForPackets = 0;
2202 #ifdef RX_ENABLE_LOCKS
2203 CV_BROADCAST(&rx_waitingForPackets_cv);
2205 osi_rxWakeup(&rx_waitingForPackets);
2211 /* ------------------Internal interfaces------------------------- */
2213 /* Return this process's service structure for the
2214 * specified socket and service */
2216 rxi_FindService(osi_socket socket, u_short serviceId)
2218 struct rx_service **sp;
2219 for (sp = &rx_services[0]; *sp; sp++) {
2220 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2227 #ifdef KDUMP_RX_LOCK
2228 static struct rx_call_rx_lock *rx_allCallsp = 0;
2230 static struct rx_call *rx_allCallsp = 0;
2234 /* Allocate a call structure, for the indicated channel of the
2235 * supplied connection. The mode and state of the call must be set by
2236 * the caller. Returns the call with mutex locked. */
2238 rxi_NewCall(struct rx_connection *conn, int channel)
2240 struct rx_call *call;
2241 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2242 struct rx_call *cp; /* Call pointer temp */
2243 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2244 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2246 dpf(("rxi_NewCall(conn %x, channel %d)\n", conn, channel));
2248 /* Grab an existing call structure, or allocate a new one.
2249 * Existing call structures are assumed to have been left reset by
2251 MUTEX_ENTER(&rx_freeCallQueue_lock);
2253 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2255 * EXCEPT that the TQ might not yet be cleared out.
2256 * Skip over those with in-use TQs.
2259 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2260 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2266 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2267 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2268 call = queue_First(&rx_freeCallQueue, rx_call);
2269 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2271 if (rx_stats_active)
2272 rx_AtomicDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2273 MUTEX_EXIT(&rx_freeCallQueue_lock);
2274 MUTEX_ENTER(&call->lock);
2275 CLEAR_CALL_QUEUE_LOCK(call);
2276 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2277 /* Now, if TQ wasn't cleared earlier, do it now. */
2278 if (call->flags & RX_CALL_TQ_CLEARME) {
2279 rxi_ClearTransmitQueue(call, 1);
2280 /*queue_Init(&call->tq);*/
2282 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2283 /* Bind the call to its connection structure */
2285 rxi_ResetCall(call, 1);
2288 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2289 #ifdef RXDEBUG_PACKET
2290 call->allNextp = rx_allCallsp;
2291 rx_allCallsp = call;
2293 #endif /* RXDEBUG_PACKET */
2294 rx_AtomicIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2296 MUTEX_EXIT(&rx_freeCallQueue_lock);
2297 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2298 MUTEX_ENTER(&call->lock);
2299 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2300 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2301 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2303 /* Initialize once-only items */
2304 queue_Init(&call->tq);
2305 queue_Init(&call->rq);
2306 queue_Init(&call->iovq);
2307 #ifdef RXDEBUG_PACKET
2308 call->rqc = call->tqc = call->iovqc = 0;
2309 #endif /* RXDEBUG_PACKET */
2310 /* Bind the call to its connection structure (prereq for reset) */
2312 rxi_ResetCall(call, 1);
2314 call->channel = channel;
2315 call->callNumber = &conn->callNumber[channel];
2316 call->rwind = conn->rwind[channel];
2317 call->twind = conn->twind[channel];
2318 /* Note that the next expected call number is retained (in
2319 * conn->callNumber[i]), even if we reallocate the call structure
2321 conn->call[channel] = call;
2322 /* if the channel's never been used (== 0), we should start at 1, otherwise
2323 * the call number is valid from the last time this channel was used */
2324 if (*call->callNumber == 0)
2325 *call->callNumber = 1;
2330 /* A call has been inactive long enough that so we can throw away
2331 * state, including the call structure, which is placed on the call
2333 * Call is locked upon entry.
2334 * haveCTLock set if called from rxi_ReapConnections
2336 #ifdef RX_ENABLE_LOCKS
2338 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2339 #else /* RX_ENABLE_LOCKS */
2341 rxi_FreeCall(struct rx_call *call)
2342 #endif /* RX_ENABLE_LOCKS */
2344 int channel = call->channel;
2345 struct rx_connection *conn = call->conn;
2348 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2349 (*call->callNumber)++;
2350 rxi_ResetCall(call, 0);
2351 call->conn->call[channel] = (struct rx_call *)0;
2353 MUTEX_ENTER(&rx_freeCallQueue_lock);
2354 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2355 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2356 /* A call may be free even though its transmit queue is still in use.
2357 * Since we search the call list from head to tail, put busy calls at
2358 * the head of the list, and idle calls at the tail.
2360 if (call->flags & RX_CALL_TQ_BUSY)
2361 queue_Prepend(&rx_freeCallQueue, call);
2363 queue_Append(&rx_freeCallQueue, call);
2364 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2365 queue_Append(&rx_freeCallQueue, call);
2366 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2367 if (rx_stats_active)
2368 rx_AtomicIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2369 MUTEX_EXIT(&rx_freeCallQueue_lock);
2371 /* Destroy the connection if it was previously slated for
2372 * destruction, i.e. the Rx client code previously called
2373 * rx_DestroyConnection (client connections), or
2374 * rxi_ReapConnections called the same routine (server
2375 * connections). Only do this, however, if there are no
2376 * outstanding calls. Note that for fine grain locking, there appears
2377 * to be a deadlock in that rxi_FreeCall has a call locked and
2378 * DestroyConnectionNoLock locks each call in the conn. But note a
2379 * few lines up where we have removed this call from the conn.
2380 * If someone else destroys a connection, they either have no
2381 * call lock held or are going through this section of code.
2383 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2384 rx_AtomicIncrement(conn->refCount, conn->conn_data_lock);
2385 #ifdef RX_ENABLE_LOCKS
2387 rxi_DestroyConnectionNoLock(conn);
2389 rxi_DestroyConnection(conn);
2390 #else /* RX_ENABLE_LOCKS */
2391 rxi_DestroyConnection(conn);
2392 #endif /* RX_ENABLE_LOCKS */
2396 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2398 rxi_Alloc(size_t size)
2402 if (rx_stats_active)
2403 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2406 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2407 afs_osi_Alloc_NoSleep(size);
2412 osi_Panic("rxi_Alloc error");
2418 rxi_Free(void *addr, size_t size)
2420 if (rx_stats_active)
2421 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2422 osi_Free(addr, size);
2426 rxi_SetPeerMtu(afs_uint32 host, afs_uint32 port, int mtu)
2428 struct rx_peer **peer_ptr, **peer_end;
2431 MUTEX_ENTER(&rx_peerHashTable_lock);
2433 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2434 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2436 struct rx_peer *peer, *next;
2437 for (peer = *peer_ptr; peer; peer = next) {
2439 if (host == peer->host) {
2440 MUTEX_ENTER(&peer->peer_lock);
2441 peer->ifMTU=MIN(mtu, peer->ifMTU);
2442 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2443 MUTEX_EXIT(&peer->peer_lock);
2448 struct rx_peer *peer;
2449 hashIndex = PEER_HASH(host, port);
2450 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2451 if ((peer->host == host) && (peer->port == port)) {
2452 MUTEX_ENTER(&peer->peer_lock);
2453 peer->ifMTU=MIN(mtu, peer->ifMTU);
2454 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2455 MUTEX_EXIT(&peer->peer_lock);
2459 MUTEX_EXIT(&rx_peerHashTable_lock);
2462 /* Find the peer process represented by the supplied (host,port)
2463 * combination. If there is no appropriate active peer structure, a
2464 * new one will be allocated and initialized
2465 * The origPeer, if set, is a pointer to a peer structure on which the
2466 * refcount will be be decremented. This is used to replace the peer
2467 * structure hanging off a connection structure */
2469 rxi_FindPeer(afs_uint32 host, u_short port,
2470 struct rx_peer *origPeer, int create)
2474 hashIndex = PEER_HASH(host, port);
2475 MUTEX_ENTER(&rx_peerHashTable_lock);
2476 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2477 if ((pp->host == host) && (pp->port == port))
2482 pp = rxi_AllocPeer(); /* This bzero's *pp */
2483 pp->host = host; /* set here or in InitPeerParams is zero */
2485 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2486 queue_Init(&pp->congestionQueue);
2487 queue_Init(&pp->rpcStats);
2488 pp->next = rx_peerHashTable[hashIndex];
2489 rx_peerHashTable[hashIndex] = pp;
2490 rxi_InitPeerParams(pp);
2491 if (rx_stats_active)
2492 rx_AtomicIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2496 rx_AtomicIncrement_NL(pp->refCount);
2499 rx_AtomicDecrement_NL(origPeer->refCount);
2500 MUTEX_EXIT(&rx_peerHashTable_lock);
2505 /* Find the connection at (host, port) started at epoch, and with the
2506 * given connection id. Creates the server connection if necessary.
2507 * The type specifies whether a client connection or a server
2508 * connection is desired. In both cases, (host, port) specify the
2509 * peer's (host, pair) pair. Client connections are not made
2510 * automatically by this routine. The parameter socket gives the
2511 * socket descriptor on which the packet was received. This is used,
2512 * in the case of server connections, to check that *new* connections
2513 * come via a valid (port, serviceId). Finally, the securityIndex
2514 * parameter must match the existing index for the connection. If a
2515 * server connection is created, it will be created using the supplied
2516 * index, if the index is valid for this service */
2517 struct rx_connection *
2518 rxi_FindConnection(osi_socket socket, afs_int32 host,
2519 u_short port, u_short serviceId, afs_uint32 cid,
2520 afs_uint32 epoch, int type, u_int securityIndex)
2522 int hashindex, flag, i;
2523 struct rx_connection *conn;
2524 hashindex = CONN_HASH(host, port, cid, epoch, type);
2525 MUTEX_ENTER(&rx_connHashTable_lock);
2526 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2527 rx_connHashTable[hashindex],
2530 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2531 && (epoch == conn->epoch)) {
2532 struct rx_peer *pp = conn->peer;
2533 if (securityIndex != conn->securityIndex) {
2534 /* this isn't supposed to happen, but someone could forge a packet
2535 * like this, and there seems to be some CM bug that makes this
2536 * happen from time to time -- in which case, the fileserver
2538 MUTEX_EXIT(&rx_connHashTable_lock);
2539 return (struct rx_connection *)0;
2541 if (pp->host == host && pp->port == port)
2543 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2545 /* So what happens when it's a callback connection? */
2546 if ( /*type == RX_CLIENT_CONNECTION && */
2547 (conn->epoch & 0x80000000))
2551 /* the connection rxLastConn that was used the last time is not the
2552 ** one we are looking for now. Hence, start searching in the hash */
2554 conn = rx_connHashTable[hashindex];
2559 struct rx_service *service;
2560 if (type == RX_CLIENT_CONNECTION) {
2561 MUTEX_EXIT(&rx_connHashTable_lock);
2562 return (struct rx_connection *)0;
2564 service = rxi_FindService(socket, serviceId);
2565 if (!service || (securityIndex >= service->nSecurityObjects)
2566 || (service->securityObjects[securityIndex] == 0)) {
2567 MUTEX_EXIT(&rx_connHashTable_lock);
2568 return (struct rx_connection *)0;
2570 conn = rxi_AllocConnection(); /* This bzero's the connection */
2571 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2572 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2573 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2574 conn->next = rx_connHashTable[hashindex];
2575 rx_connHashTable[hashindex] = conn;
2576 conn->peer = rxi_FindPeer(host, port, 0, 1);
2577 conn->type = RX_SERVER_CONNECTION;
2578 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2579 conn->epoch = epoch;
2580 conn->cid = cid & RX_CIDMASK;
2581 /* conn->serial = conn->lastSerial = 0; */
2582 /* conn->timeout = 0; */
2583 conn->ackRate = RX_FAST_ACK_RATE;
2584 conn->service = service;
2585 conn->serviceId = serviceId;
2586 conn->securityIndex = securityIndex;
2587 conn->securityObject = service->securityObjects[securityIndex];
2588 conn->nSpecific = 0;
2589 conn->specific = NULL;
2590 rx_SetConnDeadTime(conn, service->connDeadTime);
2591 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2592 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2593 for (i = 0; i < RX_MAXCALLS; i++) {
2594 conn->twind[i] = rx_initSendWindow;
2595 conn->rwind[i] = rx_initReceiveWindow;
2597 /* Notify security object of the new connection */
2598 RXS_NewConnection(conn->securityObject, conn);
2599 /* XXXX Connection timeout? */
2600 if (service->newConnProc)
2601 (*service->newConnProc) (conn);
2602 if (rx_stats_active)
2603 rx_AtomicIncrement(rx_stats.nServerConns, rx_stats_mutex);
2606 rx_AtomicIncrement(conn->refCount, conn->conn_data_lock);
2608 rxLastConn = conn; /* store this connection as the last conn used */
2609 MUTEX_EXIT(&rx_connHashTable_lock);
2613 /* There are two packet tracing routines available for testing and monitoring
2614 * Rx. One is called just after every packet is received and the other is
2615 * called just before every packet is sent. Received packets, have had their
2616 * headers decoded, and packets to be sent have not yet had their headers
2617 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2618 * containing the network address. Both can be modified. The return value, if
2619 * non-zero, indicates that the packet should be dropped. */
2621 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2622 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2624 /* A packet has been received off the interface. Np is the packet, socket is
2625 * the socket number it was received from (useful in determining which service
2626 * this packet corresponds to), and (host, port) reflect the host,port of the
2627 * sender. This call returns the packet to the caller if it is finished with
2628 * it, rather than de-allocating it, just as a small performance hack */
2631 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2632 afs_uint32 host, u_short port, int *tnop,
2633 struct rx_call **newcallp)
2635 struct rx_call *call;
2636 struct rx_connection *conn;
2638 afs_uint32 currentCallNumber;
2644 struct rx_packet *tnp;
2647 /* We don't print out the packet until now because (1) the time may not be
2648 * accurate enough until now in the lwp implementation (rx_Listener only gets
2649 * the time after the packet is read) and (2) from a protocol point of view,
2650 * this is the first time the packet has been seen */
2651 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2652 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2653 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2654 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2655 np->header.epoch, np->header.cid, np->header.callNumber,
2656 np->header.seq, np->header.flags, np));
2659 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2660 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2663 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2664 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2667 /* If an input tracer function is defined, call it with the packet and
2668 * network address. Note this function may modify its arguments. */
2669 if (rx_justReceived) {
2670 struct sockaddr_in addr;
2672 addr.sin_family = AF_INET;
2673 addr.sin_port = port;
2674 addr.sin_addr.s_addr = host;
2675 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2676 addr.sin_len = sizeof(addr);
2677 #endif /* AFS_OSF_ENV */
2678 drop = (*rx_justReceived) (np, &addr);
2679 /* drop packet if return value is non-zero */
2682 port = addr.sin_port; /* in case fcn changed addr */
2683 host = addr.sin_addr.s_addr;
2687 /* If packet was not sent by the client, then *we* must be the client */
2688 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2689 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2691 /* Find the connection (or fabricate one, if we're the server & if
2692 * necessary) associated with this packet */
2694 rxi_FindConnection(socket, host, port, np->header.serviceId,
2695 np->header.cid, np->header.epoch, type,
2696 np->header.securityIndex);
2699 /* If no connection found or fabricated, just ignore the packet.
2700 * (An argument could be made for sending an abort packet for
2705 MUTEX_ENTER(&conn->conn_data_lock);
2706 if (conn->maxSerial < np->header.serial)
2707 conn->maxSerial = np->header.serial;
2708 MUTEX_EXIT(&conn->conn_data_lock);
2710 /* If the connection is in an error state, send an abort packet and ignore
2711 * the incoming packet */
2712 if (rx_ConnError(conn)) {
2713 /* Don't respond to an abort packet--we don't want loops! */
2714 MUTEX_ENTER(&conn->conn_data_lock);
2715 if (np->header.type != RX_PACKET_TYPE_ABORT)
2716 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2717 rx_AtomicDecrement_NL(conn->refCount);
2718 MUTEX_EXIT(&conn->conn_data_lock);
2722 /* Check for connection-only requests (i.e. not call specific). */
2723 if (np->header.callNumber == 0) {
2724 switch (np->header.type) {
2725 case RX_PACKET_TYPE_ABORT: {
2726 /* What if the supplied error is zero? */
2727 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2728 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2729 rxi_ConnectionError(conn, errcode);
2730 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2733 case RX_PACKET_TYPE_CHALLENGE:
2734 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2735 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2737 case RX_PACKET_TYPE_RESPONSE:
2738 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2739 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2741 case RX_PACKET_TYPE_PARAMS:
2742 case RX_PACKET_TYPE_PARAMS + 1:
2743 case RX_PACKET_TYPE_PARAMS + 2:
2744 /* ignore these packet types for now */
2745 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2750 /* Should not reach here, unless the peer is broken: send an
2752 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2753 MUTEX_ENTER(&conn->conn_data_lock);
2754 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2755 rx_AtomicDecrement_NL(conn->refCount);
2756 MUTEX_EXIT(&conn->conn_data_lock);
2761 channel = np->header.cid & RX_CHANNELMASK;
2762 call = conn->call[channel];
2763 #ifdef RX_ENABLE_LOCKS
2765 MUTEX_ENTER(&call->lock);
2766 /* Test to see if call struct is still attached to conn. */
2767 if (call != conn->call[channel]) {
2769 MUTEX_EXIT(&call->lock);
2770 if (type == RX_SERVER_CONNECTION) {
2771 call = conn->call[channel];
2772 /* If we started with no call attached and there is one now,
2773 * another thread is also running this routine and has gotten
2774 * the connection channel. We should drop this packet in the tests
2775 * below. If there was a call on this connection and it's now
2776 * gone, then we'll be making a new call below.
2777 * If there was previously a call and it's now different then
2778 * the old call was freed and another thread running this routine
2779 * has created a call on this channel. One of these two threads
2780 * has a packet for the old call and the code below handles those
2784 MUTEX_ENTER(&call->lock);
2786 /* This packet can't be for this call. If the new call address is
2787 * 0 then no call is running on this channel. If there is a call
2788 * then, since this is a client connection we're getting data for
2789 * it must be for the previous call.
2791 if (rx_stats_active)
2792 rx_AtomicIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2793 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2798 currentCallNumber = conn->callNumber[channel];
2800 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2801 if (np->header.callNumber < currentCallNumber) {
2802 if (rx_stats_active)
2803 rx_AtomicIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2804 #ifdef RX_ENABLE_LOCKS
2806 MUTEX_EXIT(&call->lock);
2808 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2812 MUTEX_ENTER(&conn->conn_call_lock);
2813 call = rxi_NewCall(conn, channel);
2814 MUTEX_EXIT(&conn->conn_call_lock);
2815 *call->callNumber = np->header.callNumber;
2817 if (np->header.callNumber == 0)
2818 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));
2820 call->state = RX_STATE_PRECALL;
2821 clock_GetTime(&call->queueTime);
2822 hzero(call->bytesSent);
2823 hzero(call->bytesRcvd);
2825 * If the number of queued calls exceeds the overload
2826 * threshold then abort this call.
2828 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2829 struct rx_packet *tp;
2831 rxi_CallError(call, rx_BusyError);
2832 tp = rxi_SendCallAbort(call, np, 1, 0);
2833 MUTEX_EXIT(&call->lock);
2834 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2835 if (rx_stats_active)
2836 rx_AtomicIncrement(rx_stats.nBusies, rx_stats_mutex);
2839 rxi_KeepAliveOn(call);
2840 } else if (np->header.callNumber != currentCallNumber) {
2841 /* Wait until the transmit queue is idle before deciding
2842 * whether to reset the current call. Chances are that the
2843 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2846 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2847 while ((call->state == RX_STATE_ACTIVE)
2848 && (call->flags & RX_CALL_TQ_BUSY)) {
2849 call->flags |= RX_CALL_TQ_WAIT;
2851 #ifdef RX_ENABLE_LOCKS
2852 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2853 CV_WAIT(&call->cv_tq, &call->lock);
2854 #else /* RX_ENABLE_LOCKS */
2855 osi_rxSleep(&call->tq);
2856 #endif /* RX_ENABLE_LOCKS */
2858 if (call->tqWaiters == 0)
2859 call->flags &= ~RX_CALL_TQ_WAIT;
2861 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2862 /* If the new call cannot be taken right now send a busy and set
2863 * the error condition in this call, so that it terminates as
2864 * quickly as possible */
2865 if (call->state == RX_STATE_ACTIVE) {
2866 struct rx_packet *tp;
2868 rxi_CallError(call, RX_CALL_DEAD);
2869 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2871 MUTEX_EXIT(&call->lock);
2872 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2875 rxi_ResetCall(call, 0);
2876 *call->callNumber = np->header.callNumber;
2878 if (np->header.callNumber == 0)
2879 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));
2881 call->state = RX_STATE_PRECALL;
2882 clock_GetTime(&call->queueTime);
2883 hzero(call->bytesSent);
2884 hzero(call->bytesRcvd);
2886 * If the number of queued calls exceeds the overload
2887 * threshold then abort this call.
2889 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2890 struct rx_packet *tp;
2892 rxi_CallError(call, rx_BusyError);
2893 tp = rxi_SendCallAbort(call, np, 1, 0);
2894 MUTEX_EXIT(&call->lock);
2895 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2896 if (rx_stats_active)
2897 rx_AtomicIncrement(rx_stats.nBusies, rx_stats_mutex);
2900 rxi_KeepAliveOn(call);
2902 /* Continuing call; do nothing here. */
2904 } else { /* we're the client */
2905 /* Ignore all incoming acknowledgements for calls in DALLY state */
2906 if (call && (call->state == RX_STATE_DALLY)
2907 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2908 if (rx_stats_active)
2909 rx_AtomicIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2910 #ifdef RX_ENABLE_LOCKS
2912 MUTEX_EXIT(&call->lock);
2915 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2919 /* Ignore anything that's not relevant to the current call. If there
2920 * isn't a current call, then no packet is relevant. */
2921 if (!call || (np->header.callNumber != currentCallNumber)) {
2922 if (rx_stats_active)
2923 rx_AtomicIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2924 #ifdef RX_ENABLE_LOCKS
2926 MUTEX_EXIT(&call->lock);
2929 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2932 /* If the service security object index stamped in the packet does not
2933 * match the connection's security index, ignore the packet */
2934 if (np->header.securityIndex != conn->securityIndex) {
2935 #ifdef RX_ENABLE_LOCKS
2936 MUTEX_EXIT(&call->lock);
2938 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2942 /* If we're receiving the response, then all transmit packets are
2943 * implicitly acknowledged. Get rid of them. */
2944 if (np->header.type == RX_PACKET_TYPE_DATA) {
2945 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2946 /* XXX Hack. Because we must release the global rx lock when
2947 * sending packets (osi_NetSend) we drop all acks while we're
2948 * traversing the tq in rxi_Start sending packets out because
2949 * packets may move to the freePacketQueue as result of being here!
2950 * So we drop these packets until we're safely out of the
2951 * traversing. Really ugly!
2952 * For fine grain RX locking, we set the acked field in the
2953 * packets and let rxi_Start remove them from the transmit queue.
2955 if (call->flags & RX_CALL_TQ_BUSY) {
2956 #ifdef RX_ENABLE_LOCKS
2957 rxi_SetAcksInTransmitQueue(call);
2960 return np; /* xmitting; drop packet */
2963 rxi_ClearTransmitQueue(call, 0);
2965 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2966 rxi_ClearTransmitQueue(call, 0);
2967 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2969 if (np->header.type == RX_PACKET_TYPE_ACK) {
2970 /* now check to see if this is an ack packet acknowledging that the
2971 * server actually *lost* some hard-acked data. If this happens we
2972 * ignore this packet, as it may indicate that the server restarted in
2973 * the middle of a call. It is also possible that this is an old ack
2974 * packet. We don't abort the connection in this case, because this
2975 * *might* just be an old ack packet. The right way to detect a server
2976 * restart in the midst of a call is to notice that the server epoch
2978 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2979 * XXX unacknowledged. I think that this is off-by-one, but
2980 * XXX I don't dare change it just yet, since it will
2981 * XXX interact badly with the server-restart detection
2982 * XXX code in receiveackpacket. */
2983 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2984 if (rx_stats_active)
2985 rx_AtomicIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2986 MUTEX_EXIT(&call->lock);
2987 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
2991 } /* else not a data packet */
2994 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2995 /* Set remote user defined status from packet */
2996 call->remoteStatus = np->header.userStatus;
2998 /* Note the gap between the expected next packet and the actual
2999 * packet that arrived, when the new packet has a smaller serial number
3000 * than expected. Rioses frequently reorder packets all by themselves,
3001 * so this will be quite important with very large window sizes.
3002 * Skew is checked against 0 here to avoid any dependence on the type of
3003 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3005 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3006 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3007 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3009 MUTEX_ENTER(&conn->conn_data_lock);
3010 skew = conn->lastSerial - np->header.serial;
3011 conn->lastSerial = np->header.serial;
3012 MUTEX_EXIT(&conn->conn_data_lock);
3014 struct rx_peer *peer;
3016 if (skew > peer->inPacketSkew) {
3017 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
3019 peer->inPacketSkew = skew;
3023 /* Now do packet type-specific processing */
3024 switch (np->header.type) {
3025 case RX_PACKET_TYPE_DATA:
3026 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3029 case RX_PACKET_TYPE_ACK:
3030 /* Respond immediately to ack packets requesting acknowledgement
3032 if (np->header.flags & RX_REQUEST_ACK) {
3034 (void)rxi_SendCallAbort(call, 0, 1, 0);
3036 (void)rxi_SendAck(call, 0, np->header.serial,
3037 RX_ACK_PING_RESPONSE, 1);
3039 np = rxi_ReceiveAckPacket(call, np, 1);
3041 case RX_PACKET_TYPE_ABORT: {
3042 /* An abort packet: reset the call, passing the error up to the user. */
3043 /* What if error is zero? */
3044 /* What if the error is -1? the application will treat it as a timeout. */
3045 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3046 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3047 rxi_CallError(call, errdata);
3048 MUTEX_EXIT(&call->lock);
3049 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
3050 return np; /* xmitting; drop packet */
3052 case RX_PACKET_TYPE_BUSY:
3055 case RX_PACKET_TYPE_ACKALL:
3056 /* All packets acknowledged, so we can drop all packets previously
3057 * readied for sending */
3058 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3059 /* XXX Hack. We because we can't release the global rx lock when
3060 * sending packets (osi_NetSend) we drop all ack pkts while we're
3061 * traversing the tq in rxi_Start sending packets out because
3062 * packets may move to the freePacketQueue as result of being
3063 * here! So we drop these packets until we're safely out of the
3064 * traversing. Really ugly!
3065 * For fine grain RX locking, we set the acked field in the packets
3066 * and let rxi_Start remove the packets from the transmit queue.
3068 if (call->flags & RX_CALL_TQ_BUSY) {
3069 #ifdef RX_ENABLE_LOCKS
3070 rxi_SetAcksInTransmitQueue(call);
3072 #else /* RX_ENABLE_LOCKS */
3073 MUTEX_EXIT(&call->lock);
3074 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3075 return np; /* xmitting; drop packet */
3076 #endif /* RX_ENABLE_LOCKS */
3078 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3079 rxi_ClearTransmitQueue(call, 0);
3080 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3083 /* Should not reach here, unless the peer is broken: send an abort
3085 rxi_CallError(call, RX_PROTOCOL_ERROR);
3086 np = rxi_SendCallAbort(call, np, 1, 0);
3089 /* Note when this last legitimate packet was received, for keep-alive
3090 * processing. Note, we delay getting the time until now in the hope that
3091 * the packet will be delivered to the user before any get time is required
3092 * (if not, then the time won't actually be re-evaluated here). */
3093 call->lastReceiveTime = clock_Sec();
3094 MUTEX_EXIT(&call->lock);
3095 rx_AtomicDecrement(conn->refCount, conn->conn_data_lock);
3099 /* return true if this is an "interesting" connection from the point of view
3100 of someone trying to debug the system */
3102 rxi_IsConnInteresting(struct rx_connection *aconn)
3105 struct rx_call *tcall;
3107 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3109 for (i = 0; i < RX_MAXCALLS; i++) {
3110 tcall = aconn->call[i];
3112 if ((tcall->state == RX_STATE_PRECALL)
3113 || (tcall->state == RX_STATE_ACTIVE))
3115 if ((tcall->mode == RX_MODE_SENDING)
3116 || (tcall->mode == RX_MODE_RECEIVING))
3124 /* if this is one of the last few packets AND it wouldn't be used by the
3125 receiving call to immediately satisfy a read request, then drop it on
3126 the floor, since accepting it might prevent a lock-holding thread from
3127 making progress in its reading. If a call has been cleared while in
3128 the precall state then ignore all subsequent packets until the call
3129 is assigned to a thread. */
3132 TooLow(struct rx_packet *ap, struct rx_call *acall)
3136 MUTEX_ENTER(&rx_quota_mutex);
3137 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3138 && (acall->state == RX_STATE_PRECALL))
3139 || ((rx_nFreePackets < rxi_dataQuota + 2)
3140 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3141 && (acall->flags & RX_CALL_READER_WAIT)))) {
3144 MUTEX_EXIT(&rx_quota_mutex);
3150 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3152 struct rx_connection *conn = arg1;
3153 struct rx_call *acall = arg2;
3154 struct rx_call *call = acall;
3155 struct clock when, now;
3158 MUTEX_ENTER(&conn->conn_data_lock);
3159 conn->checkReachEvent = NULL;
3160 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3162 rx_AtomicDecrement_NL(conn->refCount);
3163 MUTEX_EXIT(&conn->conn_data_lock);
3167 MUTEX_ENTER(&conn->conn_call_lock);
3168 MUTEX_ENTER(&conn->conn_data_lock);
3169 for (i = 0; i < RX_MAXCALLS; i++) {
3170 struct rx_call *tc = conn->call[i];
3171 if (tc && tc->state == RX_STATE_PRECALL) {
3177 /* Indicate that rxi_CheckReachEvent is no longer running by
3178 * clearing the flag. Must be atomic under conn_data_lock to
3179 * avoid a new call slipping by: rxi_CheckConnReach holds
3180 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3182 conn->flags &= ~RX_CONN_ATTACHWAIT;
3183 MUTEX_EXIT(&conn->conn_data_lock);
3184 MUTEX_EXIT(&conn->conn_call_lock);
3189 MUTEX_ENTER(&call->lock);
3190 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3192 MUTEX_EXIT(&call->lock);
3194 clock_GetTime(&now);
3196 when.sec += RX_CHECKREACH_TIMEOUT;
3197 MUTEX_ENTER(&conn->conn_data_lock);
3198 if (!conn->checkReachEvent) {
3199 rx_AtomicIncrement_NL(conn->refCount);
3200 conn->checkReachEvent =
3201 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3204 MUTEX_EXIT(&conn->conn_data_lock);
3210 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3212 struct rx_service *service = conn->service;
3213 struct rx_peer *peer = conn->peer;
3214 afs_uint32 now, lastReach;
3216 if (service->checkReach == 0)
3220 MUTEX_ENTER(&peer->peer_lock);
3221 lastReach = peer->lastReachTime;
3222 MUTEX_EXIT(&peer->peer_lock);
3223 if (now - lastReach < RX_CHECKREACH_TTL)
3226 MUTEX_ENTER(&conn->conn_data_lock);
3227 if (conn->flags & RX_CONN_ATTACHWAIT) {
3228 MUTEX_EXIT(&conn->conn_data_lock);
3231 conn->flags |= RX_CONN_ATTACHWAIT;
3232 MUTEX_EXIT(&conn->conn_data_lock);
3233 if (!conn->checkReachEvent)
3234 rxi_CheckReachEvent(NULL, conn, call);
3239 /* try to attach call, if authentication is complete */
3241 TryAttach(struct rx_call *acall, osi_socket socket,
3242 int *tnop, struct rx_call **newcallp,
3245 struct rx_connection *conn = acall->conn;
3247 if (conn->type == RX_SERVER_CONNECTION
3248 && acall->state == RX_STATE_PRECALL) {
3249 /* Don't attach until we have any req'd. authentication. */
3250 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3251 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3252 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3253 /* Note: this does not necessarily succeed; there
3254 * may not any proc available
3257 rxi_ChallengeOn(acall->conn);
3262 /* A data packet has been received off the interface. This packet is
3263 * appropriate to the call (the call is in the right state, etc.). This
3264 * routine can return a packet to the caller, for re-use */
3267 rxi_ReceiveDataPacket(struct rx_call *call,
3268 struct rx_packet *np, int istack,
3269 osi_socket socket, afs_uint32 host, u_short port,
3270 int *tnop, struct rx_call **newcallp)
3272 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3277 afs_uint32 serial=0, flags=0;
3279 struct rx_packet *tnp;
3280 struct clock when, now;
3281 if (rx_stats_active)
3282 rx_AtomicIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3285 /* If there are no packet buffers, drop this new packet, unless we can find
3286 * packet buffers from inactive calls */
3288 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3289 MUTEX_ENTER(&rx_freePktQ_lock);
3290 rxi_NeedMorePackets = TRUE;
3291 MUTEX_EXIT(&rx_freePktQ_lock);
3292 if (rx_stats_active)
3293 rx_AtomicIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3294 call->rprev = np->header.serial;
3295 rxi_calltrace(RX_TRACE_DROP, call);
3296 dpf(("packet %x dropped on receipt - quota problems", np));
3298 rxi_ClearReceiveQueue(call);
3299 clock_GetTime(&now);
3301 clock_Add(&when, &rx_softAckDelay);
3302 if (!call->delayedAckEvent
3303 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3304 rxevent_Cancel(call->delayedAckEvent, call,
3305 RX_CALL_REFCOUNT_DELAY);
3306 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3307 call->delayedAckEvent =
3308 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3310 /* we've damaged this call already, might as well do it in. */
3316 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3317 * packet is one of several packets transmitted as a single
3318 * datagram. Do not send any soft or hard acks until all packets
3319 * in a jumbogram have been processed. Send negative acks right away.
3321 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3322 /* tnp is non-null when there are more packets in the
3323 * current jumbo gram */
3330 seq = np->header.seq;
3331 serial = np->header.serial;
3332 flags = np->header.flags;
3334 /* If the call is in an error state, send an abort message */
3336 return rxi_SendCallAbort(call, np, istack, 0);
3338 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3339 * AFS 3.5 jumbogram. */
3340 if (flags & RX_JUMBO_PACKET) {
3341 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3346 if (np->header.spare != 0) {
3347 MUTEX_ENTER(&call->conn->conn_data_lock);
3348 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3349 MUTEX_EXIT(&call->conn->conn_data_lock);
3352 /* The usual case is that this is the expected next packet */
3353 if (seq == call->rnext) {
3355 /* Check to make sure it is not a duplicate of one already queued */
3356 if (queue_IsNotEmpty(&call->rq)
3357 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3358 if (rx_stats_active)
3359 rx_AtomicIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3360 dpf(("packet %x dropped on receipt - duplicate", np));
3361 rxevent_Cancel(call->delayedAckEvent, call,
3362 RX_CALL_REFCOUNT_DELAY);
3363 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3369 /* It's the next packet. Stick it on the receive queue
3370 * for this call. Set newPackets to make sure we wake
3371 * the reader once all packets have been processed */
3372 np->flags |= RX_PKTFLAG_RQ;
3373 queue_Prepend(&call->rq, np);
3374 #ifdef RXDEBUG_PACKET
3376 #endif /* RXDEBUG_PACKET */
3378 np = NULL; /* We can't use this anymore */
3381 /* If an ack is requested then set a flag to make sure we
3382 * send an acknowledgement for this packet */
3383 if (flags & RX_REQUEST_ACK) {
3384 ackNeeded = RX_ACK_REQUESTED;
3387 /* Keep track of whether we have received the last packet */
3388 if (flags & RX_LAST_PACKET) {
3389 call->flags |= RX_CALL_HAVE_LAST;
3393 /* Check whether we have all of the packets for this call */
3394 if (call->flags & RX_CALL_HAVE_LAST) {
3395 afs_uint32 tseq; /* temporary sequence number */
3396 struct rx_packet *tp; /* Temporary packet pointer */
3397 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3399 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3400 if (tseq != tp->header.seq)
3402 if (tp->header.flags & RX_LAST_PACKET) {
3403 call->flags |= RX_CALL_RECEIVE_DONE;
3410 /* Provide asynchronous notification for those who want it
3411 * (e.g. multi rx) */
3412 if (call->arrivalProc) {
3413 (*call->arrivalProc) (call, call->arrivalProcHandle,
3414 call->arrivalProcArg);
3415 call->arrivalProc = (void (*)())0;
3418 /* Update last packet received */
3421 /* If there is no server process serving this call, grab
3422 * one, if available. We only need to do this once. If a
3423 * server thread is available, this thread becomes a server
3424 * thread and the server thread becomes a listener thread. */
3426 TryAttach(call, socket, tnop, newcallp, 0);
3429 /* This is not the expected next packet. */
3431 /* Determine whether this is a new or old packet, and if it's
3432 * a new one, whether it fits into the current receive window.
3433 * Also figure out whether the packet was delivered in sequence.
3434 * We use the prev variable to determine whether the new packet
3435 * is the successor of its immediate predecessor in the
3436 * receive queue, and the missing flag to determine whether
3437 * any of this packets predecessors are missing. */
3439 afs_uint32 prev; /* "Previous packet" sequence number */
3440 struct rx_packet *tp; /* Temporary packet pointer */
3441 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3442 int missing; /* Are any predecessors missing? */
3444 /* If the new packet's sequence number has been sent to the
3445 * application already, then this is a duplicate */
3446 if (seq < call->rnext) {
3447 if (rx_stats_active)
3448 rx_AtomicIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3449 rxevent_Cancel(call->delayedAckEvent, call,
3450 RX_CALL_REFCOUNT_DELAY);
3451 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3457 /* If the sequence number is greater than what can be
3458 * accomodated by the current window, then send a negative
3459 * acknowledge and drop the packet */
3460 if ((call->rnext + call->rwind) <= seq) {
3461 rxevent_Cancel(call->delayedAckEvent, call,
3462 RX_CALL_REFCOUNT_DELAY);
3463 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3470 /* Look for the packet in the queue of old received packets */
3471 for (prev = call->rnext - 1, missing =
3472 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3473 /*Check for duplicate packet */
3474 if (seq == tp->header.seq) {
3475 if (rx_stats_active)
3476 rx_AtomicIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3477 rxevent_Cancel(call->delayedAckEvent, call,
3478 RX_CALL_REFCOUNT_DELAY);
3479 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3485 /* If we find a higher sequence packet, break out and
3486 * insert the new packet here. */
3487 if (seq < tp->header.seq)
3489 /* Check for missing packet */
3490 if (tp->header.seq != prev + 1) {
3494 prev = tp->header.seq;
3497 /* Keep track of whether we have received the last packet. */
3498 if (flags & RX_LAST_PACKET) {
3499 call->flags |= RX_CALL_HAVE_LAST;
3502 /* It's within the window: add it to the the receive queue.
3503 * tp is left by the previous loop either pointing at the
3504 * packet before which to insert the new packet, or at the
3505 * queue head if the queue is empty or the packet should be
3507 np->flags |= RX_PKTFLAG_RQ;
3508 #ifdef RXDEBUG_PACKET
3510 #endif /* RXDEBUG_PACKET */
3511 queue_InsertBefore(tp, np);
3515 /* Check whether we have all of the packets for this call */
3516 if ((call->flags & RX_CALL_HAVE_LAST)
3517 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3518 afs_uint32 tseq; /* temporary sequence number */
3521 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3522 if (tseq != tp->header.seq)
3524 if (tp->header.flags & RX_LAST_PACKET) {
3525 call->flags |= RX_CALL_RECEIVE_DONE;
3532 /* We need to send an ack of the packet is out of sequence,
3533 * or if an ack was requested by the peer. */
3534 if (seq != prev + 1 || missing) {
3535 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3536 } else if (flags & RX_REQUEST_ACK) {
3537 ackNeeded = RX_ACK_REQUESTED;
3540 /* Acknowledge the last packet for each call */
3541 if (flags & RX_LAST_PACKET) {
3552 * If the receiver is waiting for an iovec, fill the iovec
3553 * using the data from the receive queue */
3554 if (call->flags & RX_CALL_IOVEC_WAIT) {
3555 didHardAck = rxi_FillReadVec(call, serial);
3556 /* the call may have been aborted */
3565 /* Wakeup the reader if any */
3566 if ((call->flags & RX_CALL_READER_WAIT)
3567 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3568 || (call->iovNext >= call->iovMax)
3569 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3570 call->flags &= ~RX_CALL_READER_WAIT;
3571 #ifdef RX_ENABLE_LOCKS
3572 CV_BROADCAST(&call->cv_rq);
3574 osi_rxWakeup(&call->rq);
3580 * Send an ack when requested by the peer, or once every
3581 * rxi_SoftAckRate packets until the last packet has been
3582 * received. Always send a soft ack for the last packet in
3583 * the server's reply. */
3585 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3586 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3587 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3588 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3589 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3590 } else if (call->nSoftAcks) {
3591 clock_GetTime(&now);
3593 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3594 clock_Add(&when, &rx_lastAckDelay);
3596 clock_Add(&when, &rx_softAckDelay);
3598 if (!call->delayedAckEvent
3599 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3600 rxevent_Cancel(call->delayedAckEvent, call,
3601 RX_CALL_REFCOUNT_DELAY);
3602 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3603 call->delayedAckEvent =
3604 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3606 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3607 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3614 static void rxi_ComputeRate();
3618 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3620 struct rx_peer *peer = conn->peer;
3622 MUTEX_ENTER(&peer->peer_lock);
3623 peer->lastReachTime = clock_Sec();
3624 MUTEX_EXIT(&peer->peer_lock);
3626 MUTEX_ENTER(&conn->conn_data_lock);
3627 if (conn->flags & RX_CONN_ATTACHWAIT) {
3630 conn->flags &= ~RX_CONN_ATTACHWAIT;
3631 MUTEX_EXIT(&conn->conn_data_lock);
3633 for (i = 0; i < RX_MAXCALLS; i++) {
3634 struct rx_call *call = conn->call[i];
3637 MUTEX_ENTER(&call->lock);
3638 /* tnop can be null if newcallp is null */
3639 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3641 MUTEX_EXIT(&call->lock);
3645 MUTEX_EXIT(&conn->conn_data_lock);
3649 rx_ack_reason(int reason)
3652 case RX_ACK_REQUESTED:
3654 case RX_ACK_DUPLICATE:
3656 case RX_ACK_OUT_OF_SEQUENCE:
3658 case RX_ACK_EXCEEDS_WINDOW:
3660 case RX_ACK_NOSPACE:
3664 case RX_ACK_PING_RESPONSE:
3676 /* rxi_ComputePeerNetStats
3678 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3679 * estimates (like RTT and throughput) based on ack packets. Caller
3680 * must ensure that the packet in question is the right one (i.e.
3681 * serial number matches).
3684 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3685 struct rx_ackPacket *ap, struct rx_packet *np)
3687 struct rx_peer *peer = call->conn->peer;
3689 /* Use RTT if not delayed by client. */
3690 if (ap->reason != RX_ACK_DELAY)
3691 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3693 rxi_ComputeRate(peer, call, p, np, ap->reason);
3697 /* The real smarts of the whole thing. */
3699 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3702 struct rx_ackPacket *ap;
3704 struct rx_packet *tp;
3705 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3706 struct rx_connection *conn = call->conn;
3707 struct rx_peer *peer = conn->peer;
3710 /* because there are CM's that are bogus, sending weird values for this. */
3711 afs_uint32 skew = 0;
3716 int newAckCount = 0;
3717 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3718 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3720 if (rx_stats_active)
3721 rx_AtomicIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3722 ap = (struct rx_ackPacket *)rx_DataOf(np);
3723 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3725 return np; /* truncated ack packet */
3727 /* depends on ack packet struct */
3728 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3729 first = ntohl(ap->firstPacket);
3730 serial = ntohl(ap->serial);
3731 /* temporarily disabled -- needs to degrade over time
3732 * skew = ntohs(ap->maxSkew); */
3734 /* Ignore ack packets received out of order */
3735 if (first < call->tfirst) {
3739 if (np->header.flags & RX_SLOW_START_OK) {
3740 call->flags |= RX_CALL_SLOW_START_OK;
3743 if (ap->reason == RX_ACK_PING_RESPONSE)
3744 rxi_UpdatePeerReach(conn, call);
3748 if (rxdebug_active) {
3752 len = _snprintf(msg, sizeof(msg),
3753 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3754 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3755 ntohl(ap->serial), ntohl(ap->previousPacket),
3756 (unsigned int)np->header.seq, (unsigned int)skew,
3757 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3761 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3762 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3766 OutputDebugString(msg);
3768 #else /* AFS_NT40_ENV */
3771 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3772 ap->reason, ntohl(ap->previousPacket),
3773 (unsigned int)np->header.seq, (unsigned int)serial,
3774 (unsigned int)skew, ntohl(ap->firstPacket));
3777 for (offset = 0; offset < nAcks; offset++)
3778 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3783 #endif /* AFS_NT40_ENV */
3786 /* Update the outgoing packet skew value to the latest value of
3787 * the peer's incoming packet skew value. The ack packet, of
3788 * course, could arrive out of order, but that won't affect things
3790 MUTEX_ENTER(&peer->peer_lock);
3791 peer->outPacketSkew = skew;
3793 /* Check for packets that no longer need to be transmitted, and
3794 * discard them. This only applies to packets positively
3795 * acknowledged as having been sent to the peer's upper level.
3796 * All other packets must be retained. So only packets with
3797 * sequence numbers < ap->firstPacket are candidates. */
3798 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3799 if (tp->header.seq >= first)
3801 call->tfirst = tp->header.seq + 1;
3803 && (tp->header.serial == serial || tp->firstSerial == serial))
3804 rxi_ComputePeerNetStats(call, tp, ap, np);
3805 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3808 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3809 /* XXX Hack. Because we have to release the global rx lock when sending
3810 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3811 * in rxi_Start sending packets out because packets may move to the
3812 * freePacketQueue as result of being here! So we drop these packets until
3813 * we're safely out of the traversing. Really ugly!
3814 * To make it even uglier, if we're using fine grain locking, we can
3815 * set the ack bits in the packets and have rxi_Start remove the packets
3816 * when it's done transmitting.
3818 if (call->flags & RX_CALL_TQ_BUSY) {
3819 #ifdef RX_ENABLE_LOCKS
3820 tp->flags |= RX_PKTFLAG_ACKED;
3821 call->flags |= RX_CALL_TQ_SOME_ACKED;
3822 #else /* RX_ENABLE_LOCKS */
3824 #endif /* RX_ENABLE_LOCKS */
3826 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3829 tp->flags &= ~RX_PKTFLAG_TQ;
3830 #ifdef RXDEBUG_PACKET
3832 #endif /* RXDEBUG_PACKET */
3833 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3838 /* Give rate detector a chance to respond to ping requests */
3839 if (ap->reason == RX_ACK_PING_RESPONSE) {
3840 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3844 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3846 /* Now go through explicit acks/nacks and record the results in
3847 * the waiting packets. These are packets that can't be released
3848 * yet, even with a positive acknowledge. This positive
3849 * acknowledge only means the packet has been received by the
3850 * peer, not that it will be retained long enough to be sent to
3851 * the peer's upper level. In addition, reset the transmit timers
3852 * of any missing packets (those packets that must be missing
3853 * because this packet was out of sequence) */
3855 call->nSoftAcked = 0;
3856 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3857 /* Update round trip time if the ack was stimulated on receipt
3859 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3860 #ifdef RX_ENABLE_LOCKS
3861 if (tp->header.seq >= first)
3862 #endif /* RX_ENABLE_LOCKS */
3863 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3865 && (tp->header.serial == serial || tp->firstSerial == serial))
3866 rxi_ComputePeerNetStats(call, tp, ap, np);
3868 /* Set the acknowledge flag per packet based on the
3869 * information in the ack packet. An acknowlegded packet can
3870 * be downgraded when the server has discarded a packet it
3871 * soacked previously, or when an ack packet is received
3872 * out of sequence. */
3873 if (tp->header.seq < first) {
3874 /* Implicit ack information */
3875 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3878 tp->flags |= RX_PKTFLAG_ACKED;
3879 } else if (tp->header.seq < first + nAcks) {
3880 /* Explicit ack information: set it in the packet appropriately */
3881 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3882 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3884 tp->flags |= RX_PKTFLAG_ACKED;
3891 } else /* RX_ACK_TYPE_NACK */ {
3892 tp->flags &= ~RX_PKTFLAG_ACKED;
3896 tp->flags &= ~RX_PKTFLAG_ACKED;
3900 /* If packet isn't yet acked, and it has been transmitted at least
3901 * once, reset retransmit time using latest timeout
3902 * ie, this should readjust the retransmit timer for all outstanding
3903 * packets... So we don't just retransmit when we should know better*/
3905 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3906 tp->retryTime = tp->timeSent;
3907 clock_Add(&tp->retryTime, &peer->timeout);
3908 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3909 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3913 /* If the window has been extended by this acknowledge packet,
3914 * then wakeup a sender waiting in alloc for window space, or try
3915 * sending packets now, if he's been sitting on packets due to
3916 * lack of window space */
3917 if (call->tnext < (call->tfirst + call->twind)) {
3918 #ifdef RX_ENABLE_LOCKS
3919 CV_SIGNAL(&call->cv_twind);
3921 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3922 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3923 osi_rxWakeup(&call->twind);
3926 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3927 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3931 /* if the ack packet has a receivelen field hanging off it,
3932 * update our state */
3933 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3936 /* If the ack packet has a "recommended" size that is less than
3937 * what I am using now, reduce my size to match */
3938 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3939 (int)sizeof(afs_int32), &tSize);
3940 tSize = (afs_uint32) ntohl(tSize);
3941 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3943 /* Get the maximum packet size to send to this peer */
3944 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3946 tSize = (afs_uint32) ntohl(tSize);
3947 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3948 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3950 /* sanity check - peer might have restarted with different params.
3951 * If peer says "send less", dammit, send less... Peer should never
3952 * be unable to accept packets of the size that prior AFS versions would
3953 * send without asking. */
3954 if (peer->maxMTU != tSize) {
3955 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3957 peer->maxMTU = tSize;
3958 peer->MTU = MIN(tSize, peer->MTU);
3959 call->MTU = MIN(call->MTU, tSize);
3962 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3965 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3966 (int)sizeof(afs_int32), &tSize);
3967 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3968 if (tSize < call->twind) { /* smaller than our send */
3969 call->twind = tSize; /* window, we must send less... */
3970 call->ssthresh = MIN(call->twind, call->ssthresh);
3971 call->conn->twind[call->channel] = call->twind;
3974 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3975 * network MTU confused with the loopback MTU. Calculate the
3976 * maximum MTU here for use in the slow start code below.
3978 maxMTU = peer->maxMTU;
3979 /* Did peer restart with older RX version? */
3980 if (peer->maxDgramPackets > 1) {
3981 peer->maxDgramPackets = 1;
3983 } else if (np->length >=
3984 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3987 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3988 sizeof(afs_int32), &tSize);
3989 tSize = (afs_uint32) ntohl(tSize);
3991 * As of AFS 3.5 we set the send window to match the receive window.
3993 if (tSize < call->twind) {
3994 call->twind = tSize;
3995 call->conn->twind[call->channel] = call->twind;
3996 call->ssthresh = MIN(call->twind, call->ssthresh);
3997 } else if (tSize > call->twind) {
3998 call->twind = tSize;
3999 call->conn->twind[call->channel] = call->twind;
4003 * As of AFS 3.5, a jumbogram is more than one fixed size
4004 * packet transmitted in a single UDP datagram. If the remote
4005 * MTU is smaller than our local MTU then never send a datagram
4006 * larger than the natural MTU.
4009 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
4010 sizeof(afs_int32), &tSize);
4011 maxDgramPackets = (afs_uint32) ntohl(tSize);
4012 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4013 maxDgramPackets = MIN(maxDgramPackets, peer->ifDgramPackets);
4014 if (peer->natMTU < peer->ifMTU)
4015 maxDgramPackets = MIN(maxDgramPackets, rxi_AdjustDgramPackets(1, peer->natMTU));
4016 if (maxDgramPackets > 1) {
4017 peer->maxDgramPackets = maxDgramPackets;
4018 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4020 peer->maxDgramPackets = 1;
4021 call->MTU = peer->natMTU;
4023 } else if (peer->maxDgramPackets > 1) {
4024 /* Restarted with lower version of RX */
4025 peer->maxDgramPackets = 1;
4027 } else if (peer->maxDgramPackets > 1
4028 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4029 /* Restarted with lower version of RX */
4030 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4031 peer->natMTU = OLD_MAX_PACKET_SIZE;
4032 peer->MTU = OLD_MAX_PACKET_SIZE;
4033 peer->maxDgramPackets = 1;
4034 peer->nDgramPackets = 1;
4036 call->MTU = OLD_MAX_PACKET_SIZE;
4041 * Calculate how many datagrams were successfully received after
4042 * the first missing packet and adjust the negative ack counter
4047 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4048 if (call->nNacks < nNacked) {
4049 call->nNacks = nNacked;
4052 call->nAcks += newAckCount;
4056 if (call->flags & RX_CALL_FAST_RECOVER) {
4058 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4060 call->flags &= ~RX_CALL_FAST_RECOVER;
4061 call->cwind = call->nextCwind;
4062 call->nextCwind = 0;
4065 call->nCwindAcks = 0;
4066 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4067 /* Three negative acks in a row trigger congestion recovery */
4068 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4069 MUTEX_EXIT(&peer->peer_lock);
4070 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4071 /* someone else is waiting to start recovery */
4074 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4075 rxi_WaitforTQBusy(call);
4076 MUTEX_ENTER(&peer->peer_lock);
4077 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4078 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4079 call->flags |= RX_CALL_FAST_RECOVER;
4080 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4082 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4083 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4084 call->nextCwind = call->ssthresh;
4087 peer->MTU = call->MTU;
4088 peer->cwind = call->nextCwind;
4089 peer->nDgramPackets = call->nDgramPackets;
4091 call->congestSeq = peer->congestSeq;
4092 /* Reset the resend times on the packets that were nacked
4093 * so we will retransmit as soon as the window permits*/
4094 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4096 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4097 clock_Zero(&tp->retryTime);
4099 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4104 /* If cwind is smaller than ssthresh, then increase
4105 * the window one packet for each ack we receive (exponential
4107 * If cwind is greater than or equal to ssthresh then increase
4108 * the congestion window by one packet for each cwind acks we
4109 * receive (linear growth). */
4110 if (call->cwind < call->ssthresh) {
4112 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4113 call->nCwindAcks = 0;
4115 call->nCwindAcks += newAckCount;
4116 if (call->nCwindAcks >= call->cwind) {
4117 call->nCwindAcks = 0;
4118 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4122 * If we have received several acknowledgements in a row then
4123 * it is time to increase the size of our datagrams
4125 if ((int)call->nAcks > rx_nDgramThreshold) {
4126 if (peer->maxDgramPackets > 1) {
4127 if (call->nDgramPackets < peer->maxDgramPackets) {
4128 call->nDgramPackets++;
4130 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4131 } else if (call->MTU < peer->maxMTU) {
4132 call->MTU += peer->natMTU;
4133 call->MTU = MIN(call->MTU, peer->maxMTU);
4139 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4141 /* Servers need to hold the call until all response packets have
4142 * been acknowledged. Soft acks are good enough since clients
4143 * are not allowed to clear their receive queues. */
4144 if (call->state == RX_STATE_HOLD
4145 && call->tfirst + call->nSoftAcked >= call->tnext) {
4146 call->state = RX_STATE_DALLY;
4147 rxi_ClearTransmitQueue(call, 0);
4148 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4149 } else if (!queue_IsEmpty(&call->tq)) {
4150 rxi_Start(0, call, 0, istack);
4155 /* Received a response to a challenge packet */
4157 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4158 struct rx_packet *np, int istack)
4162 /* Ignore the packet if we're the client */
4163 if (conn->type == RX_CLIENT_CONNECTION)
4166 /* If already authenticated, ignore the packet (it's probably a retry) */
4167 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4170 /* Otherwise, have the security object evaluate the response packet */
4171 error = RXS_CheckResponse(conn->securityObject, conn, np);
4173 /* If the response is invalid, reset the connection, sending
4174 * an abort to the peer */
4178 rxi_ConnectionError(conn, error);
4179 MUTEX_ENTER(&conn->conn_data_lock);
4180 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4181 MUTEX_EXIT(&conn->conn_data_lock);
4184 /* If the response is valid, any calls waiting to attach
4185 * servers can now do so */
4188 for (i = 0; i < RX_MAXCALLS; i++) {
4189 struct rx_call *call = conn->call[i];
4191 MUTEX_ENTER(&call->lock);
4192 if (call->state == RX_STATE_PRECALL)
4193 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4194 /* tnop can be null if newcallp is null */
4195 MUTEX_EXIT(&call->lock);
4199 /* Update the peer reachability information, just in case
4200 * some calls went into attach-wait while we were waiting
4201 * for authentication..
4203 rxi_UpdatePeerReach(conn, NULL);
4208 /* A client has received an authentication challenge: the security
4209 * object is asked to cough up a respectable response packet to send
4210 * back to the server. The server is responsible for retrying the
4211 * challenge if it fails to get a response. */
4214 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4215 struct rx_packet *np, int istack)
4219 /* Ignore the challenge if we're the server */
4220 if (conn->type == RX_SERVER_CONNECTION)
4223 /* Ignore the challenge if the connection is otherwise idle; someone's
4224 * trying to use us as an oracle. */
4225 if (!rxi_HasActiveCalls(conn))
4228 /* Send the security object the challenge packet. It is expected to fill
4229 * in the response. */
4230 error = RXS_GetResponse(conn->securityObject, conn, np);
4232 /* If the security object is unable to return a valid response, reset the
4233 * connection and send an abort to the peer. Otherwise send the response
4234 * packet to the peer connection. */
4236 rxi_ConnectionError(conn, error);
4237 MUTEX_ENTER(&conn->conn_data_lock);
4238 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4239 MUTEX_EXIT(&conn->conn_data_lock);
4241 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4242 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4248 /* Find an available server process to service the current request in
4249 * the given call structure. If one isn't available, queue up this
4250 * call so it eventually gets one */
4252 rxi_AttachServerProc(struct rx_call *call,
4253 osi_socket socket, int *tnop,
4254 struct rx_call **newcallp)
4256 struct rx_serverQueueEntry *sq;
4257 struct rx_service *service = call->conn->service;
4260 /* May already be attached */
4261 if (call->state == RX_STATE_ACTIVE)
4264 MUTEX_ENTER(&rx_serverPool_lock);
4266 haveQuota = QuotaOK(service);
4267 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4268 /* If there are no processes available to service this call,
4269 * put the call on the incoming call queue (unless it's
4270 * already on the queue).
4272 #ifdef RX_ENABLE_LOCKS
4274 ReturnToServerPool(service);
4275 #endif /* RX_ENABLE_LOCKS */
4277 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4278 call->flags |= RX_CALL_WAIT_PROC;
4279 MUTEX_ENTER(&rx_waiting_mutex);
4282 MUTEX_EXIT(&rx_waiting_mutex);
4283 rxi_calltrace(RX_CALL_ARRIVAL, call);
4284 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4285 queue_Append(&rx_incomingCallQueue, call);
4288 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4290 /* If hot threads are enabled, and both newcallp and sq->socketp
4291 * are non-null, then this thread will process the call, and the
4292 * idle server thread will start listening on this threads socket.
4295 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4298 *sq->socketp = socket;
4299 clock_GetTime(&call->startTime);
4300 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4304 if (call->flags & RX_CALL_WAIT_PROC) {
4305 /* Conservative: I don't think this should happen */
4306 call->flags &= ~RX_CALL_WAIT_PROC;
4307 if (queue_IsOnQueue(call)) {
4310 MUTEX_ENTER(&rx_waiting_mutex);
4312 MUTEX_EXIT(&rx_waiting_mutex);
4315 call->state = RX_STATE_ACTIVE;
4316 call->mode = RX_MODE_RECEIVING;
4317 #ifdef RX_KERNEL_TRACE
4319 int glockOwner = ISAFS_GLOCK();
4322 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4323 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4329 if (call->flags & RX_CALL_CLEARED) {
4330 /* send an ack now to start the packet flow up again */
4331 call->flags &= ~RX_CALL_CLEARED;
4332 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4334 #ifdef RX_ENABLE_LOCKS
4337 service->nRequestsRunning++;
4338 if (service->nRequestsRunning <= service->minProcs)
4344 MUTEX_EXIT(&rx_serverPool_lock);
4347 /* Delay the sending of an acknowledge event for a short while, while
4348 * a new call is being prepared (in the case of a client) or a reply
4349 * is being prepared (in the case of a server). Rather than sending
4350 * an ack packet, an ACKALL packet is sent. */
4352 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4354 #ifdef RX_ENABLE_LOCKS
4356 MUTEX_ENTER(&call->lock);
4357 call->delayedAckEvent = NULL;
4358 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4360 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4361 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4363 MUTEX_EXIT(&call->lock);
4364 #else /* RX_ENABLE_LOCKS */
4366 call->delayedAckEvent = NULL;
4367 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4368 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4369 #endif /* RX_ENABLE_LOCKS */
4373 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4375 struct rx_call *call = arg1;
4376 #ifdef RX_ENABLE_LOCKS
4378 MUTEX_ENTER(&call->lock);
4379 if (event == call->delayedAckEvent)
4380 call->delayedAckEvent = NULL;
4381 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4383 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4385 MUTEX_EXIT(&call->lock);
4386 #else /* RX_ENABLE_LOCKS */
4388 call->delayedAckEvent = NULL;
4389 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4390 #endif /* RX_ENABLE_LOCKS */
4394 #ifdef RX_ENABLE_LOCKS
4395 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4396 * clearing them out.
4399 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4401 struct rx_packet *p, *tp;
4404 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4405 p->flags |= RX_PKTFLAG_ACKED;
4409 call->flags |= RX_CALL_TQ_CLEARME;
4410 call->flags |= RX_CALL_TQ_SOME_ACKED;
4413 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4414 call->tfirst = call->tnext;
4415 call->nSoftAcked = 0;
4417 if (call->flags & RX_CALL_FAST_RECOVER) {
4418 call->flags &= ~RX_CALL_FAST_RECOVER;
4419 call->cwind = call->nextCwind;
4420 call->nextCwind = 0;
4423 CV_SIGNAL(&call->cv_twind);
4425 #endif /* RX_ENABLE_LOCKS */
4427 /* Clear out the transmit queue for the current call (all packets have
4428 * been received by peer) */
4430 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4432 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4433 struct rx_packet *p, *tp;
4435 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4437 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4438 p->flags |= RX_PKTFLAG_ACKED;
4442 call->flags |= RX_CALL_TQ_CLEARME;
4443 call->flags |= RX_CALL_TQ_SOME_ACKED;
4446 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4447 #ifdef RXDEBUG_PACKET
4449 #endif /* RXDEBUG_PACKET */
4450 rxi_FreePackets(0, &call->tq);
4451 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4452 call->flags &= ~RX_CALL_TQ_CLEARME;
4454 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4456 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4457 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4458 call->nSoftAcked = 0;
4460 if (call->flags & RX_CALL_FAST_RECOVER) {
4461 call->flags &= ~RX_CALL_FAST_RECOVER;
4462 call->cwind = call->nextCwind;
4464 #ifdef RX_ENABLE_LOCKS
4465 CV_SIGNAL(&call->cv_twind);
4467 osi_rxWakeup(&call->twind);
4472 rxi_ClearReceiveQueue(struct rx_call *call)
4474 if (queue_IsNotEmpty(&call->rq)) {
4477 count = rxi_FreePackets(0, &call->rq);
4478 rx_packetReclaims += count;
4479 #ifdef RXDEBUG_PACKET
4481 if ( call->rqc != 0 )
4482 dpf(("rxi_ClearReceiveQueue call %x rqc %u != 0", call, call->rqc));
4484 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4486 if (call->state == RX_STATE_PRECALL) {
4487 call->flags |= RX_CALL_CLEARED;
4491 /* Send an abort packet for the specified call */
4493 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4494 int istack, int force)
4497 struct clock when, now;
4502 /* Clients should never delay abort messages */
4503 if (rx_IsClientConn(call->conn))
4506 if (call->abortCode != call->error) {
4507 call->abortCode = call->error;
4508 call->abortCount = 0;
4511 if (force || rxi_callAbortThreshhold == 0
4512 || call->abortCount < rxi_callAbortThreshhold) {
4513 if (call->delayedAbortEvent) {
4514 rxevent_Cancel(call->delayedAbortEvent, call,
4515 RX_CALL_REFCOUNT_ABORT);
4517 error = htonl(call->error);
4520 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4521 (char *)&error, sizeof(error), istack);
4522 } else if (!call->delayedAbortEvent) {
4523 clock_GetTime(&now);
4525 clock_Addmsec(&when, rxi_callAbortDelay);
4526 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4527 call->delayedAbortEvent =
4528 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4533 /* Send an abort packet for the specified connection. Packet is an
4534 * optional pointer to a packet that can be used to send the abort.
4535 * Once the number of abort messages reaches the threshhold, an
4536 * event is scheduled to send the abort. Setting the force flag
4537 * overrides sending delayed abort messages.
4539 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4540 * to send the abort packet.
4543 rxi_SendConnectionAbort(struct rx_connection *conn,
4544 struct rx_packet *packet, int istack, int force)
4547 struct clock when, now;
4549 if (!rx_ConnError(conn))
4552 /* Clients should never delay abort messages */
4553 if (rx_IsClientConn(conn))
4556 if (force || rxi_connAbortThreshhold == 0
4557 || conn->abortCount < rxi_connAbortThreshhold) {
4558 if (conn->delayedAbortEvent) {
4559 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4561 error = htonl(rx_ConnError(conn));
4563 MUTEX_EXIT(&conn->conn_data_lock);
4565 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4566 RX_PACKET_TYPE_ABORT, (char *)&error,
4567 sizeof(error), istack);
4568 MUTEX_ENTER(&conn->conn_data_lock);
4569 } else if (!conn->delayedAbortEvent) {
4570 clock_GetTime(&now);
4572 clock_Addmsec(&when, rxi_connAbortDelay);
4573 conn->delayedAbortEvent =
4574 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4580 * Associate an error all of the calls owned by a connection. Called
4581 * with error non-zero. This is only for really fatal things, like
4582 * bad authentication responses. The connection itself is set in
4583 * error at this point, so that future packets received will be
4587 rxi_ConnectionError(struct rx_connection *conn,
4592 struct rx_connection *tconn;
4594 dpf(("rxi_ConnectionError conn %x error %d", conn, error));
4596 MUTEX_ENTER(&conn->conn_data_lock);
4597 if (conn->challengeEvent)
4598 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4599 if (conn->checkReachEvent) {
4600 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4601 conn->checkReachEvent = 0;
4602 conn->flags &= ~RX_CONN_ATTACHWAIT;
4603 rx_AtomicDecrement_NL(conn->refCount);
4605 MUTEX_EXIT(&conn->conn_data_lock);
4607 for ( tconn = rx_IsClonedConn(conn) ? conn->parent : conn;
4609 tconn = tconn->next_clone) {
4610 for (i = 0; i < RX_MAXCALLS; i++) {
4611 struct rx_call *call = tconn->call[i];
4613 MUTEX_ENTER(&call->lock);
4614 rxi_CallError(call, error);
4615 MUTEX_EXIT(&call->lock);
4619 rx_SetConnError(conn, error);
4620 if (rx_stats_active)
4621 rx_AtomicIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4626 rxi_CallError(struct rx_call *call, afs_int32 error)
4629 osirx_AssertMine(&call->lock, "rxi_CallError");
4631 dpf(("rxi_CallError call %x error %d call->error %d", call, error, call->error));
4633 error = call->error;
4635 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4636 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4637 rxi_ResetCall(call, 0);
4640 rxi_ResetCall(call, 0);
4642 call->error = error;
4643 call->mode = RX_MODE_ERROR;
4646 /* Reset various fields in a call structure, and wakeup waiting
4647 * processes. Some fields aren't changed: state & mode are not
4648 * touched (these must be set by the caller), and bufptr, nLeft, and
4649 * nFree are not reset, since these fields are manipulated by
4650 * unprotected macros, and may only be reset by non-interrupting code.
4653 /* this code requires that call->conn be set properly as a pre-condition. */
4654 #endif /* ADAPT_WINDOW */
4657 rxi_ResetCall(struct rx_call *call, int newcall)
4660 struct rx_peer *peer;
4661 struct rx_packet *packet;
4663 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4665 dpf(("rxi_ResetCall(call %x, newcall %d)\n", call, newcall));
4667 /* Notify anyone who is waiting for asynchronous packet arrival */
4668 if (call->arrivalProc) {
4669 (*call->arrivalProc) (call, call->arrivalProcHandle,
4670 call->arrivalProcArg);
4671 call->arrivalProc = (void (*)())0;
4674 if (call->delayedAbortEvent) {
4675 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4676 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4678 rxi_SendCallAbort(call, packet, 0, 1);
4679 rxi_FreePacket(packet);
4684 * Update the peer with the congestion information in this call
4685 * so other calls on this connection can pick up where this call
4686 * left off. If the congestion sequence numbers don't match then
4687 * another call experienced a retransmission.
4689 peer = call->conn->peer;
4690 MUTEX_ENTER(&peer->peer_lock);
4692 if (call->congestSeq == peer->congestSeq) {
4693 peer->cwind = MAX(peer->cwind, call->cwind);
4694 peer->MTU = MAX(peer->MTU, call->MTU);
4695 peer->nDgramPackets =
4696 MAX(peer->nDgramPackets, call->nDgramPackets);
4699 call->abortCode = 0;
4700 call->abortCount = 0;
4702 if (peer->maxDgramPackets > 1) {
4703 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4705 call->MTU = peer->MTU;
4707 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4708 call->ssthresh = rx_maxSendWindow;
4709 call->nDgramPackets = peer->nDgramPackets;
4710 call->congestSeq = peer->congestSeq;
4711 MUTEX_EXIT(&peer->peer_lock);
4713 flags = call->flags;
4714 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4715 if (flags & RX_CALL_TQ_BUSY) {
4716 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4717 call->flags |= (flags & RX_CALL_TQ_WAIT);
4719 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4721 rxi_ClearTransmitQueue(call, 1);
4722 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4723 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4724 dpf(("rcall %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4727 while (call->tqWaiters) {
4728 #ifdef RX_ENABLE_LOCKS
4729 CV_BROADCAST(&call->cv_tq);
4730 #else /* RX_ENABLE_LOCKS */
4731 osi_rxWakeup(&call->tq);
4732 #endif /* RX_ENABLE_LOCKS */
4737 rxi_ClearReceiveQueue(call);
4738 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4740 if (call->currentPacket) {
4741 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4742 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4743 queue_Prepend(&call->iovq, call->currentPacket);
4744 #ifdef RXDEBUG_PACKET
4746 #endif /* RXDEBUG_PACKET */
4747 call->currentPacket = (struct rx_packet *)0;
4749 call->curlen = call->nLeft = call->nFree = 0;
4751 #ifdef RXDEBUG_PACKET
4754 rxi_FreePackets(0, &call->iovq);
4757 call->twind = call->conn->twind[call->channel];
4758 call->rwind = call->conn->rwind[call->channel];
4759 call->nSoftAcked = 0;
4760 call->nextCwind = 0;
4763 call->nCwindAcks = 0;
4764 call->nSoftAcks = 0;
4765 call->nHardAcks = 0;
4767 call->tfirst = call->rnext = call->tnext = 1;
4769 call->lastAcked = 0;
4770 call->localStatus = call->remoteStatus = 0;
4772 if (flags & RX_CALL_READER_WAIT) {
4773 #ifdef RX_ENABLE_LOCKS
4774 CV_BROADCAST(&call->cv_rq);
4776 osi_rxWakeup(&call->rq);
4779 if (flags & RX_CALL_WAIT_PACKETS) {
4780 MUTEX_ENTER(&rx_freePktQ_lock);
4781 rxi_PacketsUnWait(); /* XXX */
4782 MUTEX_EXIT(&rx_freePktQ_lock);
4784 #ifdef RX_ENABLE_LOCKS
4785 CV_SIGNAL(&call->cv_twind);
4787 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4788 osi_rxWakeup(&call->twind);
4791 #ifdef RX_ENABLE_LOCKS
4792 /* The following ensures that we don't mess with any queue while some
4793 * other thread might also be doing so. The call_queue_lock field is
4794 * is only modified under the call lock. If the call is in the process
4795 * of being removed from a queue, the call is not locked until the
4796 * the queue lock is dropped and only then is the call_queue_lock field
4797 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4798 * Note that any other routine which removes a call from a queue has to
4799 * obtain the queue lock before examing the queue and removing the call.
4801 if (call->call_queue_lock) {
4802 MUTEX_ENTER(call->call_queue_lock);
4803 if (queue_IsOnQueue(call)) {
4805 if (flags & RX_CALL_WAIT_PROC) {
4807 MUTEX_ENTER(&rx_waiting_mutex);
4809 MUTEX_EXIT(&rx_waiting_mutex);
4812 MUTEX_EXIT(call->call_queue_lock);
4813 CLEAR_CALL_QUEUE_LOCK(call);
4815 #else /* RX_ENABLE_LOCKS */
4816 if (queue_IsOnQueue(call)) {
4818 if (flags & RX_CALL_WAIT_PROC)
4821 #endif /* RX_ENABLE_LOCKS */
4823 rxi_KeepAliveOff(call);
4824 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4827 /* Send an acknowledge for the indicated packet (seq,serial) of the
4828 * indicated call, for the indicated reason (reason). This
4829 * acknowledge will specifically acknowledge receiving the packet, and
4830 * will also specify which other packets for this call have been
4831 * received. This routine returns the packet that was used to the
4832 * caller. The caller is responsible for freeing it or re-using it.
4833 * This acknowledgement also returns the highest sequence number
4834 * actually read out by the higher level to the sender; the sender
4835 * promises to keep around packets that have not been read by the
4836 * higher level yet (unless, of course, the sender decides to abort
4837 * the call altogether). Any of p, seq, serial, pflags, or reason may
4838 * be set to zero without ill effect. That is, if they are zero, they
4839 * will not convey any information.
4840 * NOW there is a trailer field, after the ack where it will safely be
4841 * ignored by mundanes, which indicates the maximum size packet this
4842 * host can swallow. */
4844 struct rx_packet *optionalPacket; use to send ack (or null)
4845 int seq; Sequence number of the packet we are acking
4846 int serial; Serial number of the packet
4847 int pflags; Flags field from packet header
4848 int reason; Reason an acknowledge was prompted
4852 rxi_SendAck(struct rx_call *call,
4853 struct rx_packet *optionalPacket, int serial, int reason,
4856 struct rx_ackPacket *ap;
4857 struct rx_packet *rqp;
4858 struct rx_packet *nxp; /* For queue_Scan */
4859 struct rx_packet *p;
4862 #ifdef RX_ENABLE_TSFPQ
4863 struct rx_ts_info_t * rx_ts_info;
4867 * Open the receive window once a thread starts reading packets
4869 if (call->rnext > 1) {
4870 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4873 call->nHardAcks = 0;
4874 call->nSoftAcks = 0;
4875 if (call->rnext > call->lastAcked)
4876 call->lastAcked = call->rnext;
4880 rx_computelen(p, p->length); /* reset length, you never know */
4881 } /* where that's been... */
4882 #ifdef RX_ENABLE_TSFPQ
4884 RX_TS_INFO_GET(rx_ts_info);
4885 if ((p = rx_ts_info->local_special_packet)) {
4886 rx_computelen(p, p->length);
4887 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4888 rx_ts_info->local_special_packet = p;
4889 } else { /* We won't send the ack, but don't panic. */
4890 return optionalPacket;
4894 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4895 /* We won't send the ack, but don't panic. */
4896 return optionalPacket;
4901 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4904 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4905 #ifndef RX_ENABLE_TSFPQ
4906 if (!optionalPacket)
4909 return optionalPacket;
4911 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4912 if (rx_Contiguous(p) < templ) {
4913 #ifndef RX_ENABLE_TSFPQ
4914 if (!optionalPacket)
4917 return optionalPacket;
4922 /* MTUXXX failing to send an ack is very serious. We should */
4923 /* try as hard as possible to send even a partial ack; it's */
4924 /* better than nothing. */
4925 ap = (struct rx_ackPacket *)rx_DataOf(p);
4926 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4927 ap->reason = reason;
4929 /* The skew computation used to be bogus, I think it's better now. */
4930 /* We should start paying attention to skew. XXX */
4931 ap->serial = htonl(serial);
4932 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4934 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4935 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4937 /* No fear of running out of ack packet here because there can only be at most
4938 * one window full of unacknowledged packets. The window size must be constrained
4939 * to be less than the maximum ack size, of course. Also, an ack should always
4940 * fit into a single packet -- it should not ever be fragmented. */
4941 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4942 if (!rqp || !call->rq.next
4943 || (rqp->header.seq > (call->rnext + call->rwind))) {
4944 #ifndef RX_ENABLE_TSFPQ
4945 if (!optionalPacket)
4948 rxi_CallError(call, RX_CALL_DEAD);
4949 return optionalPacket;
4952 while (rqp->header.seq > call->rnext + offset)
4953 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4954 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4956 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4957 #ifndef RX_ENABLE_TSFPQ
4958 if (!optionalPacket)
4961 rxi_CallError(call, RX_CALL_DEAD);
4962 return optionalPacket;
4967 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4969 /* these are new for AFS 3.3 */
4970 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4971 templ = htonl(templ);
4972 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4973 templ = htonl(call->conn->peer->ifMTU);
4974 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4975 sizeof(afs_int32), &templ);
4977 /* new for AFS 3.4 */
4978 templ = htonl(call->rwind);
4979 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4980 sizeof(afs_int32), &templ);
4982 /* new for AFS 3.5 */
4983 templ = htonl(call->conn->peer->ifDgramPackets);
4984 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4985 sizeof(afs_int32), &templ);
4987 p->header.serviceId = call->conn->serviceId;
4988 p->header.cid = (call->conn->cid | call->channel);
4989 p->header.callNumber = *call->callNumber;
4991 p->header.securityIndex = call->conn->securityIndex;
4992 p->header.epoch = call->conn->epoch;
4993 p->header.type = RX_PACKET_TYPE_ACK;
4994 p->header.flags = RX_SLOW_START_OK;
4995 if (reason == RX_ACK_PING) {
4996 p->header.flags |= RX_REQUEST_ACK;
4998 clock_GetTime(&call->pingRequestTime);
5001 if (call->conn->type == RX_CLIENT_CONNECTION)
5002 p->header.flags |= RX_CLIENT_INITIATED;
5006 if (rxdebug_active) {
5010 len = _snprintf(msg, sizeof(msg),
5011 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5012 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5013 ntohl(ap->serial), ntohl(ap->previousPacket),
5014 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5015 ap->nAcks, ntohs(ap->bufferSpace) );
5019 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5020 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5024 OutputDebugString(msg);
5026 #else /* AFS_NT40_ENV */
5028 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5029 ap->reason, ntohl(ap->previousPacket),
5030 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5032 for (offset = 0; offset < ap->nAcks; offset++)
5033 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5038 #endif /* AFS_NT40_ENV */
5041 int i, nbytes = p->length;
5043 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5044 if (nbytes <= p->wirevec[i].iov_len) {
5047 savelen = p->wirevec[i].iov_len;
5049 p->wirevec[i].iov_len = nbytes;
5051 rxi_Send(call, p, istack);
5052 p->wirevec[i].iov_len = savelen;
5056 nbytes -= p->wirevec[i].iov_len;
5059 if (rx_stats_active)
5060 rx_AtomicIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5061 #ifndef RX_ENABLE_TSFPQ
5062 if (!optionalPacket)
5065 return optionalPacket; /* Return packet for re-use by caller */
5068 /* Send all of the packets in the list in single datagram */
5070 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5071 int istack, int moreFlag, struct clock *now,
5072 struct clock *retryTime, int resending)
5077 struct rx_connection *conn = call->conn;
5078 struct rx_peer *peer = conn->peer;
5080 MUTEX_ENTER(&peer->peer_lock);
5083 peer->reSends += len;
5084 if (rx_stats_active)
5085 rx_AtomicIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5086 MUTEX_EXIT(&peer->peer_lock);
5088 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5092 /* Set the packet flags and schedule the resend events */
5093 /* Only request an ack for the last packet in the list */
5094 for (i = 0; i < len; i++) {
5095 list[i]->retryTime = *retryTime;
5096 if (list[i]->header.serial) {
5097 /* Exponentially backoff retry times */
5098 if (list[i]->backoff < MAXBACKOFF) {
5099 /* so it can't stay == 0 */
5100 list[i]->backoff = (list[i]->backoff << 1) + 1;
5103 clock_Addmsec(&(list[i]->retryTime),
5104 ((afs_uint32) list[i]->backoff) << 8);
5107 /* Wait a little extra for the ack on the last packet */
5108 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5109 clock_Addmsec(&(list[i]->retryTime), 400);
5112 /* Record the time sent */
5113 list[i]->timeSent = *now;
5115 /* Ask for an ack on retransmitted packets, on every other packet
5116 * if the peer doesn't support slow start. Ask for an ack on every
5117 * packet until the congestion window reaches the ack rate. */
5118 if (list[i]->header.serial) {
5120 if (rx_stats_active)
5121 rx_AtomicIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5123 /* improved RTO calculation- not Karn */
5124 list[i]->firstSent = *now;
5125 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5126 || (!(call->flags & RX_CALL_SLOW_START_OK)
5127 && (list[i]->header.seq & 1)))) {
5132 MUTEX_ENTER(&peer->peer_lock);
5136 if (rx_stats_active)
5137 rx_AtomicIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5138 MUTEX_EXIT(&peer->peer_lock);
5140 /* Tag this packet as not being the last in this group,
5141 * for the receiver's benefit */
5142 if (i < len - 1 || moreFlag) {
5143 list[i]->header.flags |= RX_MORE_PACKETS;
5146 /* Install the new retransmit time for the packet, and
5147 * record the time sent */
5148 list[i]->timeSent = *now;
5152 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5155 /* Since we're about to send a data packet to the peer, it's
5156 * safe to nuke any scheduled end-of-packets ack */
5157 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5159 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5160 MUTEX_EXIT(&call->lock);
5162 rxi_SendPacketList(call, conn, list, len, istack);
5164 rxi_SendPacket(call, conn, list[0], istack);
5166 MUTEX_ENTER(&call->lock);
5167 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5169 /* Update last send time for this call (for keep-alive
5170 * processing), and for the connection (so that we can discover
5171 * idle connections) */
5172 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5175 /* When sending packets we need to follow these rules:
5176 * 1. Never send more than maxDgramPackets in a jumbogram.
5177 * 2. Never send a packet with more than two iovecs in a jumbogram.
5178 * 3. Never send a retransmitted packet in a jumbogram.
5179 * 4. Never send more than cwind/4 packets in a jumbogram
5180 * We always keep the last list we should have sent so we
5181 * can set the RX_MORE_PACKETS flags correctly.
5184 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5185 int istack, struct clock *now, struct clock *retryTime,
5188 int i, cnt, lastCnt = 0;
5189 struct rx_packet **listP, **lastP = 0;
5190 struct rx_peer *peer = call->conn->peer;
5191 int morePackets = 0;
5193 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5194 /* Does the current packet force us to flush the current list? */
5196 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5197 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5199 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5201 /* If the call enters an error state stop sending, or if
5202 * we entered congestion recovery mode, stop sending */
5203 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5211 /* Add the current packet to the list if it hasn't been acked.
5212 * Otherwise adjust the list pointer to skip the current packet. */
5213 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5215 /* Do we need to flush the list? */
5216 if (cnt >= (int)peer->maxDgramPackets
5217 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5218 || list[i]->header.serial
5219 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5221 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5222 retryTime, resending);
5223 /* If the call enters an error state stop sending, or if
5224 * we entered congestion recovery mode, stop sending */
5226 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5231 listP = &list[i + 1];
5236 osi_Panic("rxi_SendList error");
5238 listP = &list[i + 1];
5242 /* Send the whole list when the call is in receive mode, when
5243 * the call is in eof mode, when we are in fast recovery mode,
5244 * and when we have the last packet */
5245 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5246 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5247 || (call->flags & RX_CALL_FAST_RECOVER)) {
5248 /* Check for the case where the current list contains
5249 * an acked packet. Since we always send retransmissions
5250 * in a separate packet, we only need to check the first
5251 * packet in the list */
5252 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5256 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5257 retryTime, resending);
5258 /* If the call enters an error state stop sending, or if
5259 * we entered congestion recovery mode, stop sending */
5260 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5264 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5267 } else if (lastCnt > 0) {
5268 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5273 #ifdef RX_ENABLE_LOCKS
5274 /* Call rxi_Start, below, but with the call lock held. */
5276 rxi_StartUnlocked(struct rxevent *event,
5277 void *arg0, void *arg1, int istack)
5279 struct rx_call *call = arg0;
5281 MUTEX_ENTER(&call->lock);
5282 rxi_Start(event, call, arg1, istack);
5283 MUTEX_EXIT(&call->lock);
5285 #endif /* RX_ENABLE_LOCKS */
5287 /* This routine is called when new packets are readied for
5288 * transmission and when retransmission may be necessary, or when the
5289 * transmission window or burst count are favourable. This should be
5290 * better optimized for new packets, the usual case, now that we've
5291 * got rid of queues of send packets. XXXXXXXXXXX */
5293 rxi_Start(struct rxevent *event,
5294 void *arg0, void *arg1, int istack)
5296 struct rx_call *call = arg0;
5298 struct rx_packet *p;
5299 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5300 struct rx_peer *peer = call->conn->peer;
5301 struct clock now, usenow, retryTime;
5305 struct rx_packet **xmitList;
5308 /* If rxi_Start is being called as a result of a resend event,
5309 * then make sure that the event pointer is removed from the call
5310 * structure, since there is no longer a per-call retransmission
5312 if (event && event == call->resendEvent) {
5313 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5314 call->resendEvent = NULL;
5316 if (queue_IsEmpty(&call->tq)) {
5320 /* Timeouts trigger congestion recovery */
5321 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5322 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5323 /* someone else is waiting to start recovery */
5326 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5327 rxi_WaitforTQBusy(call);
5328 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5329 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5330 call->flags |= RX_CALL_FAST_RECOVER;
5331 if (peer->maxDgramPackets > 1) {
5332 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5334 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5336 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5337 call->nDgramPackets = 1;
5339 call->nextCwind = 1;
5342 MUTEX_ENTER(&peer->peer_lock);
5343 peer->MTU = call->MTU;
5344 peer->cwind = call->cwind;
5345 peer->nDgramPackets = 1;
5347 call->congestSeq = peer->congestSeq;
5348 MUTEX_EXIT(&peer->peer_lock);
5349 /* Clear retry times on packets. Otherwise, it's possible for
5350 * some packets in the queue to force resends at rates faster
5351 * than recovery rates.
5353 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5354 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5355 clock_Zero(&p->retryTime);
5360 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5361 if (rx_stats_active)
5362 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5367 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5368 /* Get clock to compute the re-transmit time for any packets
5369 * in this burst. Note, if we back off, it's reasonable to
5370 * back off all of the packets in the same manner, even if
5371 * some of them have been retransmitted more times than more
5373 * Do a dance to avoid blocking after setting now. */
5374 clock_Zero(&retryTime);
5375 MUTEX_ENTER(&peer->peer_lock);
5376 clock_Add(&retryTime, &peer->timeout);
5377 MUTEX_EXIT(&peer->peer_lock);
5378 clock_GetTime(&now);
5379 clock_Add(&retryTime, &now);
5381 /* Send (or resend) any packets that need it, subject to
5382 * window restrictions and congestion burst control
5383 * restrictions. Ask for an ack on the last packet sent in
5384 * this burst. For now, we're relying upon the window being
5385 * considerably bigger than the largest number of packets that
5386 * are typically sent at once by one initial call to
5387 * rxi_Start. This is probably bogus (perhaps we should ask
5388 * for an ack when we're half way through the current
5389 * window?). Also, for non file transfer applications, this
5390 * may end up asking for an ack for every packet. Bogus. XXXX
5393 * But check whether we're here recursively, and let the other guy
5396 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5397 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5398 call->flags |= RX_CALL_TQ_BUSY;
5400 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5402 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5403 call->flags &= ~RX_CALL_NEED_START;
5404 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5406 maxXmitPackets = MIN(call->twind, call->cwind);
5407 xmitList = (struct rx_packet **)
5408 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5409 /* XXXX else we must drop any mtx we hold */
5410 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5412 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5414 if (xmitList == NULL)
5415 osi_Panic("rxi_Start, failed to allocate xmit list");
5416 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5417 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5418 /* We shouldn't be sending packets if a thread is waiting
5419 * to initiate congestion recovery */
5423 && (call->flags & RX_CALL_FAST_RECOVER)) {
5424 /* Only send one packet during fast recovery */
5427 if ((p->flags & RX_PKTFLAG_FREE)
5428 || (!queue_IsEnd(&call->tq, nxp)
5429 && (nxp->flags & RX_PKTFLAG_FREE))
5430 || (p == (struct rx_packet *)&rx_freePacketQueue)
5431 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5432 osi_Panic("rxi_Start: xmit queue clobbered");
5434 if (p->flags & RX_PKTFLAG_ACKED) {
5435 /* Since we may block, don't trust this */
5436 usenow.sec = usenow.usec = 0;
5437 if (rx_stats_active)
5438 rx_AtomicIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5439 continue; /* Ignore this packet if it has been acknowledged */
5442 /* Turn off all flags except these ones, which are the same
5443 * on each transmission */
5444 p->header.flags &= RX_PRESET_FLAGS;
5446 if (p->header.seq >=
5447 call->tfirst + MIN((int)call->twind,
5448 (int)(call->nSoftAcked +
5450 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5451 /* Note: if we're waiting for more window space, we can
5452 * still send retransmits; hence we don't return here, but
5453 * break out to schedule a retransmit event */
5454 dpf(("call %d waiting for window",
5455 *(call->callNumber)));
5459 /* Transmit the packet if it needs to be sent. */
5460 if (!clock_Lt(&now, &p->retryTime)) {
5461 if (nXmitPackets == maxXmitPackets) {
5462 rxi_SendXmitList(call, xmitList, nXmitPackets,
5463 istack, &now, &retryTime,
5465 osi_Free(xmitList, maxXmitPackets *
5466 sizeof(struct rx_packet *));
5469 xmitList[nXmitPackets++] = p;
5473 /* xmitList now hold pointers to all of the packets that are
5474 * ready to send. Now we loop to send the packets */
5475 if (nXmitPackets > 0) {
5476 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5477 &now, &retryTime, resending);
5480 maxXmitPackets * sizeof(struct rx_packet *));
5482 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5484 * TQ references no longer protected by this flag; they must remain
5485 * protected by the global lock.
5487 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5488 call->flags &= ~RX_CALL_TQ_BUSY;
5489 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5490 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5491 #ifdef RX_ENABLE_LOCKS
5492 osirx_AssertMine(&call->lock, "rxi_Start start");
5493 CV_BROADCAST(&call->cv_tq);
5494 #else /* RX_ENABLE_LOCKS */
5495 osi_rxWakeup(&call->tq);
5496 #endif /* RX_ENABLE_LOCKS */
5501 /* We went into the error state while sending packets. Now is
5502 * the time to reset the call. This will also inform the using
5503 * process that the call is in an error state.
5505 if (rx_stats_active)
5506 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5507 call->flags &= ~RX_CALL_TQ_BUSY;
5508 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5509 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5510 #ifdef RX_ENABLE_LOCKS
5511 osirx_AssertMine(&call->lock, "rxi_Start middle");
5512 CV_BROADCAST(&call->cv_tq);
5513 #else /* RX_ENABLE_LOCKS */
5514 osi_rxWakeup(&call->tq);
5515 #endif /* RX_ENABLE_LOCKS */
5517 rxi_CallError(call, call->error);
5520 #ifdef RX_ENABLE_LOCKS
5521 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5523 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5524 /* Some packets have received acks. If they all have, we can clear
5525 * the transmit queue.
5528 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5529 if (p->header.seq < call->tfirst
5530 && (p->flags & RX_PKTFLAG_ACKED)) {
5532 p->flags &= ~RX_PKTFLAG_TQ;
5533 #ifdef RXDEBUG_PACKET
5541 call->flags |= RX_CALL_TQ_CLEARME;
5543 #endif /* RX_ENABLE_LOCKS */
5544 /* Don't bother doing retransmits if the TQ is cleared. */
5545 if (call->flags & RX_CALL_TQ_CLEARME) {
5546 rxi_ClearTransmitQueue(call, 1);
5548 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5551 /* Always post a resend event, if there is anything in the
5552 * queue, and resend is possible. There should be at least
5553 * one unacknowledged packet in the queue ... otherwise none
5554 * of these packets should be on the queue in the first place.
5556 if (call->resendEvent) {
5557 /* Cancel the existing event and post a new one */
5558 rxevent_Cancel(call->resendEvent, call,
5559 RX_CALL_REFCOUNT_RESEND);
5562 /* The retry time is the retry time on the first unacknowledged
5563 * packet inside the current window */
5565 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5566 /* Don't set timers for packets outside the window */
5567 if (p->header.seq >= call->tfirst + call->twind) {
5571 if (!(p->flags & RX_PKTFLAG_ACKED)
5572 && !clock_IsZero(&p->retryTime)) {
5574 retryTime = p->retryTime;
5579 /* Post a new event to re-run rxi_Start when retries may be needed */
5580 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5581 #ifdef RX_ENABLE_LOCKS
5582 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5584 rxevent_PostNow2(&retryTime, &usenow,
5586 (void *)call, 0, istack);
5587 #else /* RX_ENABLE_LOCKS */
5589 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5590 (void *)call, 0, istack);
5591 #endif /* RX_ENABLE_LOCKS */
5594 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5595 } while (call->flags & RX_CALL_NEED_START);
5597 * TQ references no longer protected by this flag; they must remain
5598 * protected by the global lock.
5600 call->flags &= ~RX_CALL_TQ_BUSY;
5601 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5602 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5603 #ifdef RX_ENABLE_LOCKS
5604 osirx_AssertMine(&call->lock, "rxi_Start end");
5605 CV_BROADCAST(&call->cv_tq);
5606 #else /* RX_ENABLE_LOCKS */
5607 osi_rxWakeup(&call->tq);
5608 #endif /* RX_ENABLE_LOCKS */
5611 call->flags |= RX_CALL_NEED_START;
5613 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5615 if (call->resendEvent) {
5616 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5621 /* Also adjusts the keep alive parameters for the call, to reflect
5622 * that we have just sent a packet (so keep alives aren't sent
5625 rxi_Send(struct rx_call *call, struct rx_packet *p,
5628 struct rx_connection *conn = call->conn;
5630 /* Stamp each packet with the user supplied status */
5631 p->header.userStatus = call->localStatus;
5633 /* Allow the security object controlling this call's security to
5634 * make any last-minute changes to the packet */
5635 RXS_SendPacket(conn->securityObject, call, p);
5637 /* Since we're about to send SOME sort of packet to the peer, it's
5638 * safe to nuke any scheduled end-of-packets ack */
5639 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5641 /* Actually send the packet, filling in more connection-specific fields */
5642 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5643 MUTEX_EXIT(&call->lock);
5644 rxi_SendPacket(call, conn, p, istack);
5645 MUTEX_ENTER(&call->lock);
5646 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5648 /* Update last send time for this call (for keep-alive
5649 * processing), and for the connection (so that we can discover
5650 * idle connections) */
5651 conn->lastSendTime = call->lastSendTime = clock_Sec();
5652 /* Don't count keepalives here, so idleness can be tracked. */
5653 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5654 call->lastSendData = call->lastSendTime;
5658 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5659 * that things are fine. Also called periodically to guarantee that nothing
5660 * falls through the cracks (e.g. (error + dally) connections have keepalive
5661 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5663 * haveCTLock Set if calling from rxi_ReapConnections
5665 #ifdef RX_ENABLE_LOCKS
5667 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5668 #else /* RX_ENABLE_LOCKS */
5670 rxi_CheckCall(struct rx_call *call)
5671 #endif /* RX_ENABLE_LOCKS */
5673 struct rx_connection *conn = call->conn;
5675 afs_uint32 deadTime;
5677 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5678 if (call->flags & RX_CALL_TQ_BUSY) {
5679 /* Call is active and will be reset by rxi_Start if it's
5680 * in an error state.
5685 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5687 (((afs_uint32) rx_ConnSecondsUntilDead(conn) << 10) +
5688 ((afs_uint32) conn->peer->rtt >> 3) +
5689 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5691 /* These are computed to the second (+- 1 second). But that's
5692 * good enough for these values, which should be a significant
5693 * number of seconds. */
5694 if (now > (call->lastReceiveTime + deadTime)) {
5695 if (call->state == RX_STATE_ACTIVE) {
5697 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5699 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5700 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5701 ip_stack_t *ipst = ns->netstack_ip;
5703 ire = ire_cache_lookup(call->conn->peer->host
5704 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5706 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5708 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5715 if (ire && ire->ire_max_frag > 0)
5716 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5717 #if defined(GLOBAL_NETSTACKID)
5721 #endif /* ADAPT_PMTU */
5722 rxi_CallError(call, RX_CALL_DEAD);
5725 #ifdef RX_ENABLE_LOCKS
5726 /* Cancel pending events */
5727 rxevent_Cancel(call->delayedAckEvent, call,
5728 RX_CALL_REFCOUNT_DELAY);
5729 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5730 rxevent_Cancel(call->keepAliveEvent, call,
5731 RX_CALL_REFCOUNT_ALIVE);
5732 if (call->refCount == 0) {
5733 rxi_FreeCall(call, haveCTLock);
5737 #else /* RX_ENABLE_LOCKS */
5740 #endif /* RX_ENABLE_LOCKS */
5742 /* Non-active calls are destroyed if they are not responding
5743 * to pings; active calls are simply flagged in error, so the
5744 * attached process can die reasonably gracefully. */
5746 /* see if we have a non-activity timeout */
5747 if (call->startWait && rx_ConnIdleDeadTime(conn)
5748 && ((call->startWait + rx_ConnIdleDeadTime(conn)) < now)) {
5749 if (call->state == RX_STATE_ACTIVE) {
5750 rxi_CallError(call, RX_CALL_TIMEOUT);
5754 if (call->lastSendData && rx_ConnIdleDeadTime(conn)
5755 && (rx_ConnIdleDeadErr(conn) != 0)
5756 && ((call->lastSendData + rx_ConnIdleDeadTime(conn)) < now)) {
5757 if (call->state == RX_STATE_ACTIVE) {
5758 rxi_CallError(call, conn->idleDeadErr);
5762 /* see if we have a hard timeout */
5763 if (rx_ConnHardDeadTime(conn)
5764 && (now > (rx_ConnHardDeadTime(conn) + call->startTime.sec))) {
5765 if (call->state == RX_STATE_ACTIVE)
5766 rxi_CallError(call, RX_CALL_TIMEOUT);
5773 /* When a call is in progress, this routine is called occasionally to
5774 * make sure that some traffic has arrived (or been sent to) the peer.
5775 * If nothing has arrived in a reasonable amount of time, the call is
5776 * declared dead; if nothing has been sent for a while, we send a
5777 * keep-alive packet (if we're actually trying to keep the call alive)
5780 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5782 struct rx_call *call = arg1;
5783 struct rx_connection *conn;
5786 MUTEX_ENTER(&call->lock);
5787 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5788 if (event == call->keepAliveEvent)
5789 call->keepAliveEvent = NULL;
5792 #ifdef RX_ENABLE_LOCKS
5793 if (rxi_CheckCall(call, 0)) {
5794 MUTEX_EXIT(&call->lock);
5797 #else /* RX_ENABLE_LOCKS */
5798 if (rxi_CheckCall(call))
5800 #endif /* RX_ENABLE_LOCKS */
5802 /* Don't try to keep alive dallying calls */
5803 if (call->state == RX_STATE_DALLY) {
5804 MUTEX_EXIT(&call->lock);
5809 if ((now - call->lastSendTime) > rx_ConnSecondsUntilPing(conn)) {
5810 /* Don't try to send keepalives if there is unacknowledged data */
5811 /* the rexmit code should be good enough, this little hack
5812 * doesn't quite work XXX */
5813 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5815 rxi_ScheduleKeepAliveEvent(call);
5816 MUTEX_EXIT(&call->lock);
5821 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
5823 if (!call->keepAliveEvent) {
5824 struct clock when, now;
5825 clock_GetTime(&now);
5827 when.sec += rx_ConnSecondsUntilPing(call->conn);
5828 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5829 call->keepAliveEvent =
5830 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5834 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5836 rxi_KeepAliveOn(struct rx_call *call)
5838 /* Pretend last packet received was received now--i.e. if another
5839 * packet isn't received within the keep alive time, then the call
5840 * will die; Initialize last send time to the current time--even
5841 * if a packet hasn't been sent yet. This will guarantee that a
5842 * keep-alive is sent within the ping time */
5843 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5844 rxi_ScheduleKeepAliveEvent(call);
5847 /* This routine is called to send connection abort messages
5848 * that have been delayed to throttle looping clients. */
5850 rxi_SendDelayedConnAbort(struct rxevent *event,
5851 void *arg1, void *unused)
5853 struct rx_connection *conn = arg1;
5856 struct rx_packet *packet;
5858 MUTEX_ENTER(&conn->conn_data_lock);
5859 conn->delayedAbortEvent = NULL;
5860 error = htonl(rx_ConnError(conn));
5862 MUTEX_EXIT(&conn->conn_data_lock);
5863 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5866 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5867 RX_PACKET_TYPE_ABORT, (char *)&error,
5869 rxi_FreePacket(packet);
5873 /* This routine is called to send call abort messages
5874 * that have been delayed to throttle looping clients. */
5876 rxi_SendDelayedCallAbort(struct rxevent *event,
5877 void *arg1, void *dummy)
5879 struct rx_call *call = arg1;
5882 struct rx_packet *packet;
5884 MUTEX_ENTER(&call->lock);
5885 call->delayedAbortEvent = NULL;
5886 error = htonl(call->error);
5888 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5891 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5892 (char *)&error, sizeof(error), 0);
5893 rxi_FreePacket(packet);
5895 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5896 MUTEX_EXIT(&call->lock);
5899 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5900 * seconds) to ask the client to authenticate itself. The routine
5901 * issues a challenge to the client, which is obtained from the
5902 * security object associated with the connection */
5904 rxi_ChallengeEvent(struct rxevent *event,
5905 void *arg0, void *arg1, int tries)
5907 struct rx_connection *conn = arg0;
5909 conn->challengeEvent = NULL;
5910 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5911 struct rx_packet *packet;
5912 struct clock when, now;
5915 /* We've failed to authenticate for too long.
5916 * Reset any calls waiting for authentication;
5917 * they are all in RX_STATE_PRECALL.
5921 MUTEX_ENTER(&conn->conn_call_lock);
5922 for (i = 0; i < RX_MAXCALLS; i++) {
5923 struct rx_call *call = conn->call[i];
5925 MUTEX_ENTER(&call->lock);
5926 if (call->state == RX_STATE_PRECALL) {
5927 rxi_CallError(call, RX_CALL_DEAD);
5928 rxi_SendCallAbort(call, NULL, 0, 0);
5930 MUTEX_EXIT(&call->lock);
5933 MUTEX_EXIT(&conn->conn_call_lock);
5937 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5939 /* If there's no packet available, do this later. */
5940 RXS_GetChallenge(conn->securityObject, conn, packet);
5941 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5942 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5943 rxi_FreePacket(packet);
5945 clock_GetTime(&now);
5947 when.sec += RX_CHALLENGE_TIMEOUT;
5948 conn->challengeEvent =
5949 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5954 /* Call this routine to start requesting the client to authenticate
5955 * itself. This will continue until authentication is established,
5956 * the call times out, or an invalid response is returned. The
5957 * security object associated with the connection is asked to create
5958 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5959 * defined earlier. */
5961 rxi_ChallengeOn(struct rx_connection *conn)
5963 if (!conn->challengeEvent) {
5964 RXS_CreateChallenge(conn->securityObject, conn);
5965 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5970 /* Compute round trip time of the packet provided, in *rttp.
5973 /* rxi_ComputeRoundTripTime is called with peer locked. */
5974 /* sentp and/or peer may be null */
5976 rxi_ComputeRoundTripTime(struct rx_packet *p,
5977 struct clock *sentp,
5978 struct rx_peer *peer)
5980 struct clock thisRtt, *rttp = &thisRtt;
5984 clock_GetTime(rttp);
5986 if (clock_Lt(rttp, sentp)) {
5988 return; /* somebody set the clock back, don't count this time. */
5990 clock_Sub(rttp, sentp);
5991 if (rx_stats_active) {
5992 MUTEX_ENTER(&rx_stats_mutex);
5993 if (clock_Lt(rttp, &rx_stats.minRtt))
5994 rx_stats.minRtt = *rttp;
5995 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5996 if (rttp->sec > 60) {
5997 MUTEX_EXIT(&rx_stats_mutex);
5998 return; /* somebody set the clock ahead */
6000 rx_stats.maxRtt = *rttp;
6002 clock_Add(&rx_stats.totalRtt, rttp);
6003 rx_AtomicIncrement_NL(rx_stats.nRttSamples);
6004 MUTEX_EXIT(&rx_stats_mutex);
6007 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6009 /* Apply VanJacobson round-trip estimations */
6014 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6015 * srtt is stored as fixed point with 3 bits after the binary
6016 * point (i.e., scaled by 8). The following magic is
6017 * equivalent to the smoothing algorithm in rfc793 with an
6018 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6019 * srtt*8 = srtt*8 + rtt - srtt
6020 * srtt = srtt + rtt/8 - srtt/8
6023 delta = MSEC(rttp) - (peer->rtt >> 3);
6027 * We accumulate a smoothed rtt variance (actually, a smoothed
6028 * mean difference), then set the retransmit timer to smoothed
6029 * rtt + 4 times the smoothed variance (was 2x in van's original
6030 * paper, but 4x works better for me, and apparently for him as
6032 * rttvar is stored as
6033 * fixed point with 2 bits after the binary point (scaled by
6034 * 4). The following is equivalent to rfc793 smoothing with
6035 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
6036 * replaces rfc793's wired-in beta.
6037 * dev*4 = dev*4 + (|actual - expected| - dev)
6043 delta -= (peer->rtt_dev >> 2);
6044 peer->rtt_dev += delta;
6046 /* I don't have a stored RTT so I start with this value. Since I'm
6047 * probably just starting a call, and will be pushing more data down
6048 * this, I expect congestion to increase rapidly. So I fudge a
6049 * little, and I set deviance to half the rtt. In practice,
6050 * deviance tends to approach something a little less than
6051 * half the smoothed rtt. */
6052 peer->rtt = (MSEC(rttp) << 3) + 8;
6053 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6055 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
6056 * the other of these connections is usually in a user process, and can
6057 * be switched and/or swapped out. So on fast, reliable networks, the
6058 * timeout would otherwise be too short.
6060 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
6061 clock_Zero(&(peer->timeout));
6062 clock_Addmsec(&(peer->timeout), rtt_timeout);
6064 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)));
6068 /* Find all server connections that have not been active for a long time, and
6071 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6073 struct clock now, when;
6074 clock_GetTime(&now);
6076 /* Find server connection structures that haven't been used for
6077 * greater than rx_idleConnectionTime */
6079 struct rx_connection **conn_ptr, **conn_end;
6080 int i, havecalls = 0;
6081 MUTEX_ENTER(&rx_connHashTable_lock);
6082 for (conn_ptr = &rx_connHashTable[0], conn_end =
6083 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6085 struct rx_connection *conn, *next;
6086 struct rx_call *call;
6090 for (conn = *conn_ptr; conn; conn = next) {
6091 /* XXX -- Shouldn't the connection be locked? */
6094 for (i = 0; i < RX_MAXCALLS; i++) {
6095 call = conn->call[i];
6099 code = MUTEX_TRYENTER(&call->lock);
6102 #ifdef RX_ENABLE_LOCKS
6103 result = rxi_CheckCall(call, 1);
6104 #else /* RX_ENABLE_LOCKS */
6105 result = rxi_CheckCall(call);
6106 #endif /* RX_ENABLE_LOCKS */
6107 MUTEX_EXIT(&call->lock);
6109 /* If CheckCall freed the call, it might
6110 * have destroyed the connection as well,
6111 * which screws up the linked lists.
6117 if (conn->type == RX_SERVER_CONNECTION) {
6118 /* This only actually destroys the connection if
6119 * there are no outstanding calls */
6120 MUTEX_ENTER(&conn->conn_data_lock);
6121 if (!havecalls && (rx_AtomicPeek_NL(conn->refCount) == 0)
6122 && ((conn->lastSendTime + rx_idleConnectionTime) <
6124 rx_AtomicIncrement_NL(conn->refCount); /* it will be decr in rx_DestroyConn */
6125 MUTEX_EXIT(&conn->conn_data_lock);
6126 #ifdef RX_ENABLE_LOCKS
6127 rxi_DestroyConnectionNoLock(conn);
6128 #else /* RX_ENABLE_LOCKS */
6129 rxi_DestroyConnection(conn);
6130 #endif /* RX_ENABLE_LOCKS */
6132 #ifdef RX_ENABLE_LOCKS
6134 MUTEX_EXIT(&conn->conn_data_lock);
6136 #endif /* RX_ENABLE_LOCKS */
6140 #ifdef RX_ENABLE_LOCKS
6141 while (rx_connCleanup_list) {
6142 struct rx_connection *conn;
6143 conn = rx_connCleanup_list;
6144 rx_connCleanup_list = rx_connCleanup_list->next;
6145 MUTEX_EXIT(&rx_connHashTable_lock);
6146 rxi_CleanupConnection(conn);
6147 MUTEX_ENTER(&rx_connHashTable_lock);
6149 MUTEX_EXIT(&rx_connHashTable_lock);
6150 #endif /* RX_ENABLE_LOCKS */
6153 /* Find any peer structures that haven't been used (haven't had an
6154 * associated connection) for greater than rx_idlePeerTime */
6156 struct rx_peer **peer_ptr, **peer_end;
6158 MUTEX_ENTER(&rx_rpc_stats);
6159 MUTEX_ENTER(&rx_peerHashTable_lock);
6160 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6161 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6163 struct rx_peer *peer, *next, *prev;
6164 for (prev = peer = *peer_ptr; peer; peer = next) {
6166 code = MUTEX_TRYENTER(&peer->peer_lock);
6167 if ((code) && (rx_AtomicPeek_NL(peer->refCount) == 0)
6168 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6169 rx_interface_stat_p rpc_stat, nrpc_stat;
6171 MUTEX_EXIT(&peer->peer_lock);
6172 MUTEX_DESTROY(&peer->peer_lock);
6174 (&peer->rpcStats, rpc_stat, nrpc_stat,
6175 rx_interface_stat)) {
6176 unsigned int num_funcs;
6179 queue_Remove(&rpc_stat->queue_header);
6180 queue_Remove(&rpc_stat->all_peers);
6181 num_funcs = rpc_stat->stats[0].func_total;
6183 sizeof(rx_interface_stat_t) +
6184 rpc_stat->stats[0].func_total *
6185 sizeof(rx_function_entry_v1_t);
6187 rxi_Free(rpc_stat, space);
6188 rxi_rpc_peer_stat_cnt -= num_funcs;
6191 if (rx_stats_active)
6192 rx_AtomicDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6193 if (peer == *peer_ptr) {
6200 MUTEX_EXIT(&peer->peer_lock);
6206 MUTEX_EXIT(&rx_peerHashTable_lock);
6207 MUTEX_EXIT(&rx_rpc_stats);
6210 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6211 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6212 * GC, just below. Really, we shouldn't have to keep moving packets from
6213 * one place to another, but instead ought to always know if we can
6214 * afford to hold onto a packet in its particular use. */
6215 MUTEX_ENTER(&rx_freePktQ_lock);
6216 if (rx_waitingForPackets) {
6217 rx_waitingForPackets = 0;
6218 #ifdef RX_ENABLE_LOCKS
6219 CV_BROADCAST(&rx_waitingForPackets_cv);
6221 osi_rxWakeup(&rx_waitingForPackets);
6224 MUTEX_EXIT(&rx_freePktQ_lock);
6227 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6228 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6232 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6233 * rx.h is sort of strange this is better. This is called with a security
6234 * object before it is discarded. Each connection using a security object has
6235 * its own refcount to the object so it won't actually be freed until the last
6236 * connection is destroyed.
6238 * This is the only rxs module call. A hold could also be written but no one
6242 rxs_Release(struct rx_securityClass *aobj)
6244 return RXS_Close(aobj);
6248 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6249 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6250 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6251 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6253 /* Adjust our estimate of the transmission rate to this peer, given
6254 * that the packet p was just acked. We can adjust peer->timeout and
6255 * call->twind. Pragmatically, this is called
6256 * only with packets of maximal length.
6257 * Called with peer and call locked.
6261 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6262 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6264 afs_int32 xferSize, xferMs;
6268 /* Count down packets */
6269 if (peer->rateFlag > 0)
6271 /* Do nothing until we're enabled */
6272 if (peer->rateFlag != 0)
6277 /* Count only when the ack seems legitimate */
6278 switch (ackReason) {
6279 case RX_ACK_REQUESTED:
6281 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6285 case RX_ACK_PING_RESPONSE:
6286 if (p) /* want the response to ping-request, not data send */
6288 clock_GetTime(&newTO);
6289 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6290 clock_Sub(&newTO, &call->pingRequestTime);
6291 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6295 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6302 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));
6304 /* Track only packets that are big enough. */
6305 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6309 /* absorb RTT data (in milliseconds) for these big packets */
6310 if (peer->smRtt == 0) {
6311 peer->smRtt = xferMs;
6313 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6318 if (peer->countDown) {
6322 peer->countDown = 10; /* recalculate only every so often */
6324 /* In practice, we can measure only the RTT for full packets,
6325 * because of the way Rx acks the data that it receives. (If it's
6326 * smaller than a full packet, it often gets implicitly acked
6327 * either by the call response (from a server) or by the next call
6328 * (from a client), and either case confuses transmission times
6329 * with processing times.) Therefore, replace the above
6330 * more-sophisticated processing with a simpler version, where the
6331 * smoothed RTT is kept for full-size packets, and the time to
6332 * transmit a windowful of full-size packets is simply RTT *
6333 * windowSize. Again, we take two steps:
6334 - ensure the timeout is large enough for a single packet's RTT;
6335 - ensure that the window is small enough to fit in the desired timeout.*/
6337 /* First, the timeout check. */
6338 minTime = peer->smRtt;
6339 /* Get a reasonable estimate for a timeout period */
6341 newTO.sec = minTime / 1000;
6342 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6344 /* Increase the timeout period so that we can always do at least
6345 * one packet exchange */
6346 if (clock_Gt(&newTO, &peer->timeout)) {
6348 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));
6350 peer->timeout = newTO;
6353 /* Now, get an estimate for the transmit window size. */
6354 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6355 /* Now, convert to the number of full packets that could fit in a
6356 * reasonable fraction of that interval */
6357 minTime /= (peer->smRtt << 1);
6358 xferSize = minTime; /* (make a copy) */
6360 /* Now clamp the size to reasonable bounds. */
6363 else if (minTime > rx_Window)
6364 minTime = rx_Window;
6365 /* if (minTime != peer->maxWindow) {
6366 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6367 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6368 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6370 peer->maxWindow = minTime;
6371 elide... call->twind = minTime;
6375 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6376 * Discern this by calculating the timeout necessary for rx_Window
6378 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6379 /* calculate estimate for transmission interval in milliseconds */
6380 minTime = rx_Window * peer->smRtt;
6381 if (minTime < 1000) {
6382 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
6383 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6384 peer->timeout.usec, peer->smRtt, peer->packetSize));
6386 newTO.sec = 0; /* cut back on timeout by half a second */
6387 newTO.usec = 500000;
6388 clock_Sub(&peer->timeout, &newTO);
6393 } /* end of rxi_ComputeRate */
6394 #endif /* ADAPT_WINDOW */
6402 #define TRACE_OPTION_RX_DEBUG 16
6410 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6411 0, KEY_QUERY_VALUE, &parmKey);
6412 if (code != ERROR_SUCCESS)
6415 dummyLen = sizeof(TraceOption);
6416 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6417 (BYTE *) &TraceOption, &dummyLen);
6418 if (code == ERROR_SUCCESS) {
6419 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6421 RegCloseKey (parmKey);
6422 #endif /* AFS_NT40_ENV */
6427 rx_DebugOnOff(int on)
6431 rxdebug_active = on;
6437 rx_StatsOnOff(int on)
6440 rx_stats_active = on;
6445 /* Don't call this debugging routine directly; use dpf */
6447 rxi_DebugPrint(char *format, ...)
6456 va_start(ap, format);
6458 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6461 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6463 if (msg[len-1] != '\n') {
6467 OutputDebugString(msg);
6474 va_start(ap, format);
6476 clock_GetTime(&now);
6477 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
6478 (unsigned int)now.usec / 1000);
6479 vfprintf(rx_Log, format, ap);
6488 * This function is used to process the rx_stats structure that is local
6489 * to a process as well as an rx_stats structure received from a remote
6490 * process (via rxdebug). Therefore, it needs to do minimal version
6494 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6495 afs_int32 freePackets, char version)
6500 if (size != sizeof(struct rx_statistics)) {
6502 "Unexpected size of stats structure: was %d, expected %lud\n",
6503 size, sizeof(struct rx_statistics));
6506 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6507 rx_AtomicPeek_NL(s->packetRequests));
6509 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6510 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
6511 rx_AtomicPeek_NL(s->receivePktAllocFailures),
6512 rx_AtomicPeek_NL(s->receiveCbufPktAllocFailures),
6513 rx_AtomicPeek_NL(s->sendPktAllocFailures),
6514 rx_AtomicPeek_NL(s->sendCbufPktAllocFailures),
6515 rx_AtomicPeek_NL(s->specialPktAllocFailures));
6517 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
6518 rx_AtomicPeek_NL(s->receivePktAllocFailures),
6519 rx_AtomicPeek_NL(s->sendPktAllocFailures),
6520 rx_AtomicPeek_NL(s->specialPktAllocFailures));
6524 " greedy %u, " "bogusReads %u (last from host %x), "
6525 "noPackets %u, " "noBuffers %u, " "selects %u, "
6527 rx_AtomicPeek_NL(s->socketGreedy),
6528 rx_AtomicPeek_NL(s->bogusPacketOnRead),
6529 rx_AtomicPeek_NL(s->bogusHost),
6530 rx_AtomicPeek_NL(s->noPacketOnRead),
6531 rx_AtomicPeek_NL(s->noPacketBuffersOnRead),
6532 rx_AtomicPeek_NL(s->selects),
6533 rx_AtomicPeek_NL(s->sendSelects));
6535 fprintf(file, " packets read: ");
6536 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6537 fprintf(file, "%s %u ", rx_packetTypes[i], rx_AtomicPeek_NL(s->packetsRead[i]));
6539 fprintf(file, "\n");
6542 " other read counters: data %u, " "ack %u, " "dup %u "
6543 "spurious %u " "dally %u\n", rx_AtomicPeek_NL(s->dataPacketsRead),
6544 rx_AtomicPeek_NL(s->ackPacketsRead),
6545 rx_AtomicPeek_NL(s->dupPacketsRead),
6546 rx_AtomicPeek_NL(s->spuriousPacketsRead),
6547 rx_AtomicPeek_NL(s->ignorePacketDally));
6549 fprintf(file, " packets sent: ");
6550 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6551 fprintf(file, "%s %u ", rx_packetTypes[i], rx_AtomicPeek_NL(s->packetsSent[i]));
6553 fprintf(file, "\n");
6556 " other send counters: ack %u, " "data %u (not resends), "
6557 "resends %u, " "pushed %u, " "acked&ignored %u\n",
6558 rx_AtomicPeek_NL(s->ackPacketsSent),
6559 rx_AtomicPeek_NL(s->dataPacketsSent),
6560 rx_AtomicPeek_NL(s->dataPacketsReSent),
6561 rx_AtomicPeek_NL(s->dataPacketsPushed),
6562 rx_AtomicPeek_NL(s->ignoreAckedPacket));
6565 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
6566 rx_AtomicPeek_NL(s->netSendFailures), rx_AtomicPeek_NL(s->fatalErrors));
6568 if (rx_AtomicPeek_NL(s->nRttSamples)) {
6569 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6570 clock_Float(&s->totalRtt) / rx_AtomicPeek_NL(s->nRttSamples), rx_AtomicPeek_NL(s->nRttSamples));
6572 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6573 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6577 " %d server connections, " "%d client connections, "
6578 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6579 rx_AtomicPeek_NL(s->nServerConns),
6580 rx_AtomicPeek_NL(s->nClientConns),
6581 rx_AtomicPeek_NL(s->nPeerStructs),
6582 rx_AtomicPeek_NL(s->nCallStructs),
6583 rx_AtomicPeek_NL(s->nFreeCallStructs));
6585 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6586 fprintf(file, " %d clock updates\n", clock_nUpdates);
6589 fprintf(file, "ERROR: compiled without RXDEBUG\n");
6593 /* for backward compatibility */
6595 rx_PrintStats(FILE * file)
6597 MUTEX_ENTER(&rx_stats_mutex);
6598 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6600 MUTEX_EXIT(&rx_stats_mutex);
6604 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6606 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6607 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6608 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6611 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6612 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6613 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6616 " Packet size %d, " "max in packet skew %d, "
6617 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6618 (int)peer->outPacketSkew);
6622 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
6624 * This mutex protects the following static variables:
6628 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
6629 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
6631 #define LOCK_RX_DEBUG
6632 #define UNLOCK_RX_DEBUG
6633 #endif /* AFS_PTHREAD_ENV */
6637 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6638 u_char type, void *inputData, size_t inputLength,
6639 void *outputData, size_t outputLength)
6641 static afs_int32 counter = 100;
6642 time_t waitTime, waitCount, startTime;
6643 struct rx_header theader;
6646 struct timeval tv_now, tv_wake, tv_delta;
6647 struct sockaddr_in taddr, faddr;
6656 startTime = time(0);
6662 tp = &tbuffer[sizeof(struct rx_header)];
6663 taddr.sin_family = AF_INET;
6664 taddr.sin_port = remotePort;
6665 taddr.sin_addr.s_addr = remoteAddr;
6666 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6667 taddr.sin_len = sizeof(struct sockaddr_in);
6670 memset(&theader, 0, sizeof(theader));
6671 theader.epoch = htonl(999);
6673 theader.callNumber = htonl(counter);
6676 theader.type = type;
6677 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6678 theader.serviceId = 0;
6680 memcpy(tbuffer, &theader, sizeof(theader));
6681 memcpy(tp, inputData, inputLength);
6683 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6684 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6686 /* see if there's a packet available */
6687 gettimeofday(&tv_wake,0);
6688 tv_wake.tv_sec += waitTime;
6691 FD_SET(socket, &imask);
6692 tv_delta.tv_sec = tv_wake.tv_sec;
6693 tv_delta.tv_usec = tv_wake.tv_usec;
6694 gettimeofday(&tv_now, 0);
6696 if (tv_delta.tv_usec < tv_now.tv_usec) {
6698 tv_delta.tv_usec += 1000000;
6701 tv_delta.tv_usec -= tv_now.tv_usec;
6703 if (tv_delta.tv_sec < tv_now.tv_sec) {
6707 tv_delta.tv_sec -= tv_now.tv_sec;
6709 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6710 if (code == 1 && FD_ISSET(socket, &imask)) {
6711 /* now receive a packet */
6712 faddrLen = sizeof(struct sockaddr_in);
6714 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6715 (struct sockaddr *)&faddr, &faddrLen);
6718 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6719 if (counter == ntohl(theader.callNumber))
6727 /* see if we've timed out */
6735 code -= sizeof(struct rx_header);
6736 if (code > outputLength)
6737 code = outputLength;
6738 memcpy(outputData, tp, code);
6741 #endif /* RXDEBUG */
6744 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6745 afs_uint16 remotePort, struct rx_debugStats * stat,
6746 afs_uint32 * supportedValues)
6752 struct rx_debugIn in;
6754 *supportedValues = 0;
6755 in.type = htonl(RX_DEBUGI_GETSTATS);
6758 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6759 &in, sizeof(in), stat, sizeof(*stat));
6762 * If the call was successful, fixup the version and indicate
6763 * what contents of the stat structure are valid.
6764 * Also do net to host conversion of fields here.
6768 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6769 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6771 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6772 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6774 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6775 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6777 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6778 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6780 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6781 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6783 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6784 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6786 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6787 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6789 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6790 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6792 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6793 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6795 stat->nFreePackets = ntohl(stat->nFreePackets);
6796 stat->packetReclaims = ntohl(stat->packetReclaims);
6797 stat->callsExecuted = ntohl(stat->callsExecuted);
6798 stat->nWaiting = ntohl(stat->nWaiting);
6799 stat->idleThreads = ntohl(stat->idleThreads);
6800 stat->nWaited = ntohl(stat->nWaited);
6801 stat->nPackets = ntohl(stat->nPackets);
6808 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6809 afs_uint16 remotePort, struct rx_statistics * stat,
6810 afs_uint32 * supportedValues)
6816 struct rx_debugIn in;
6818 afs_int32 *lp = (afs_int32 *) stat;
6821 * supportedValues is currently unused, but added to allow future
6822 * versioning of this function.
6825 *supportedValues = 0;
6826 in.type = htonl(RX_DEBUGI_RXSTATS);
6828 memset(stat, 0, sizeof(*stat));
6830 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6831 &in, sizeof(in), stat, sizeof(*stat));
6836 * Do net to host conversion here
6839 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6848 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6849 afs_uint16 remotePort, size_t version_length,
6854 return MakeDebugCall(socket, remoteAddr, remotePort,
6855 RX_PACKET_TYPE_VERSION, a, 1, version,
6863 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6864 afs_uint16 remotePort, afs_int32 * nextConnection,
6865 int allConnections, afs_uint32 debugSupportedValues,
6866 struct rx_debugConn * conn,
6867 afs_uint32 * supportedValues)
6873 struct rx_debugIn in;
6877 * supportedValues is currently unused, but added to allow future
6878 * versioning of this function.
6881 *supportedValues = 0;
6882 if (allConnections) {
6883 in.type = htonl(RX_DEBUGI_GETALLCONN);
6885 in.type = htonl(RX_DEBUGI_GETCONN);
6887 in.index = htonl(*nextConnection);
6888 memset(conn, 0, sizeof(*conn));
6890 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6891 &in, sizeof(in), conn, sizeof(*conn));
6894 *nextConnection += 1;
6897 * Convert old connection format to new structure.
6900 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6901 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6902 #define MOVEvL(a) (conn->a = vL->a)
6904 /* any old or unrecognized version... */
6905 for (i = 0; i < RX_MAXCALLS; i++) {
6906 MOVEvL(callState[i]);
6907 MOVEvL(callMode[i]);
6908 MOVEvL(callFlags[i]);
6909 MOVEvL(callOther[i]);
6911 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6912 MOVEvL(secStats.type);
6913 MOVEvL(secStats.level);
6914 MOVEvL(secStats.flags);
6915 MOVEvL(secStats.expires);
6916 MOVEvL(secStats.packetsReceived);
6917 MOVEvL(secStats.packetsSent);
6918 MOVEvL(secStats.bytesReceived);
6919 MOVEvL(secStats.bytesSent);
6924 * Do net to host conversion here
6926 * I don't convert host or port since we are most likely
6927 * going to want these in NBO.
6929 conn->cid = ntohl(conn->cid);
6930 conn->serial = ntohl(conn->serial);
6931 for (i = 0; i < RX_MAXCALLS; i++) {
6932 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6934 rx_SetConnError(conn, ntohl(rx_ConnError(conn)));
6935 conn->secStats.flags = ntohl(conn->secStats.flags);
6936 conn->secStats.expires = ntohl(conn->secStats.expires);
6937 conn->secStats.packetsReceived =
6938 ntohl(conn->secStats.packetsReceived);
6939 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6940 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6941 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6942 conn->epoch = ntohl(conn->epoch);
6943 conn->natMTU = ntohl(conn->natMTU);
6950 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6951 afs_uint16 remotePort, afs_int32 * nextPeer,
6952 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6953 afs_uint32 * supportedValues)
6959 struct rx_debugIn in;
6962 * supportedValues is currently unused, but added to allow future
6963 * versioning of this function.
6966 *supportedValues = 0;
6967 in.type = htonl(RX_DEBUGI_GETPEER);
6968 in.index = htonl(*nextPeer);
6969 memset(peer, 0, sizeof(*peer));
6971 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6972 &in, sizeof(in), peer, sizeof(*peer));
6978 * Do net to host conversion here
6980 * I don't convert host or port since we are most likely
6981 * going to want these in NBO.
6983 peer->ifMTU = ntohs(peer->ifMTU);
6984 peer->idleWhen = ntohl(peer->idleWhen);
6985 peer->refCount = ntohs(peer->refCount);
6986 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6987 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6988 peer->rtt = ntohl(peer->rtt);
6989 peer->rtt_dev = ntohl(peer->rtt_dev);
6990 peer->timeout.sec = ntohl(peer->timeout.sec);
6991 peer->timeout.usec = ntohl(peer->timeout.usec);
6992 peer->nSent = ntohl(peer->nSent);
6993 peer->reSends = ntohl(peer->reSends);
6994 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6995 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6996 peer->rateFlag = ntohl(peer->rateFlag);
6997 peer->natMTU = ntohs(peer->natMTU);
6998 peer->maxMTU = ntohs(peer->maxMTU);
6999 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7000 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7001 peer->MTU = ntohs(peer->MTU);
7002 peer->cwind = ntohs(peer->cwind);
7003 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7004 peer->congestSeq = ntohs(peer->congestSeq);
7005 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7006 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7007 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7008 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7017 struct rx_serverQueueEntry *np;
7020 struct rx_call *call;
7021 struct rx_serverQueueEntry *sq;
7025 if (rxinit_status == 1) {
7027 return; /* Already shutdown. */
7031 #ifndef AFS_PTHREAD_ENV
7032 FD_ZERO(&rx_selectMask);
7033 #endif /* AFS_PTHREAD_ENV */
7034 rxi_dataQuota = RX_MAX_QUOTA;
7035 #ifndef AFS_PTHREAD_ENV
7037 #endif /* AFS_PTHREAD_ENV */
7040 #ifndef AFS_PTHREAD_ENV
7041 #ifndef AFS_USE_GETTIMEOFDAY
7043 #endif /* AFS_USE_GETTIMEOFDAY */
7044 #endif /* AFS_PTHREAD_ENV */
7046 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7047 call = queue_First(&rx_freeCallQueue, rx_call);
7049 rxi_Free(call, sizeof(struct rx_call));
7052 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7053 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7059 struct rx_peer **peer_ptr, **peer_end;
7060 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7061 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7063 struct rx_peer *peer, *next;
7064 for (peer = *peer_ptr; peer; peer = next) {
7065 rx_interface_stat_p rpc_stat, nrpc_stat;
7068 (&peer->rpcStats, rpc_stat, nrpc_stat,
7069 rx_interface_stat)) {
7070 unsigned int num_funcs;
7073 queue_Remove(&rpc_stat->queue_header);
7074 queue_Remove(&rpc_stat->all_peers);
7075 num_funcs = rpc_stat->stats[0].func_total;
7077 sizeof(rx_interface_stat_t) +
7078 rpc_stat->stats[0].func_total *
7079 sizeof(rx_function_entry_v1_t);
7081 rxi_Free(rpc_stat, space);
7082 rx_MutexAdd(rxi_rpc_peer_stat_cnt, -num_funcs, rx_rpc_stats);
7086 if (rx_stats_active)
7087 rx_AtomicDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7091 for (i = 0; i < RX_MAX_SERVICES; i++) {
7093 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7095 for (i = 0; i < rx_hashTableSize; i++) {
7096 struct rx_connection *tc, *ntc;
7097 MUTEX_ENTER(&rx_connHashTable_lock);
7098 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7100 for (j = 0; j < RX_MAXCALLS; j++) {
7102 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7105 rxi_Free(tc, sizeof(*tc));
7107 MUTEX_EXIT(&rx_connHashTable_lock);
7110 MUTEX_ENTER(&freeSQEList_lock);
7112 while ((np = rx_FreeSQEList)) {
7113 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7114 MUTEX_DESTROY(&np->lock);
7115 rxi_Free(np, sizeof(*np));
7118 MUTEX_EXIT(&freeSQEList_lock);
7119 MUTEX_DESTROY(&freeSQEList_lock);
7120 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7121 MUTEX_DESTROY(&rx_connHashTable_lock);
7122 MUTEX_DESTROY(&rx_peerHashTable_lock);
7123 MUTEX_DESTROY(&rx_serverPool_lock);
7125 osi_Free(rx_connHashTable,
7126 rx_hashTableSize * sizeof(struct rx_connection *));
7127 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7129 UNPIN(rx_connHashTable,
7130 rx_hashTableSize * sizeof(struct rx_connection *));
7131 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7133 rxi_FreeAllPackets();
7135 MUTEX_ENTER(&rx_quota_mutex);
7136 rxi_dataQuota = RX_MAX_QUOTA;
7137 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7138 MUTEX_EXIT(&rx_quota_mutex);
7143 #ifdef RX_ENABLE_LOCKS
7145 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7147 if (!MUTEX_ISMINE(lockaddr))
7148 osi_Panic("Lock not held: %s", msg);
7150 #endif /* RX_ENABLE_LOCKS */
7155 * Routines to implement connection specific data.
7159 rx_KeyCreate(rx_destructor_t rtn)
7162 MUTEX_ENTER(&rxi_keyCreate_lock);
7163 key = rxi_keyCreate_counter++;
7164 rxi_keyCreate_destructor = (rx_destructor_t *)
7165 realloc((void *)rxi_keyCreate_destructor,
7166 (key + 1) * sizeof(rx_destructor_t));
7167 rxi_keyCreate_destructor[key] = rtn;
7168 MUTEX_EXIT(&rxi_keyCreate_lock);
7173 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7176 struct rx_connection *tconn =
7177 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7179 MUTEX_ENTER(&tconn->conn_data_lock);
7180 if (!tconn->specific) {
7181 tconn->specific = (void **)malloc((key + 1) * sizeof(void *));
7182 for (i = 0; i < key; i++)
7183 tconn->specific[i] = NULL;
7184 tconn->nSpecific = key + 1;
7185 tconn->specific[key] = ptr;
7186 } else if (key >= tconn->nSpecific) {
7187 tconn->specific = (void **)
7188 realloc(tconn->specific, (key + 1) * sizeof(void *));
7189 for (i = tconn->nSpecific; i < key; i++)
7190 tconn->specific[i] = NULL;
7191 tconn->nSpecific = key + 1;
7192 tconn->specific[key] = ptr;
7194 if (tconn->specific[key] && rxi_keyCreate_destructor[key])
7195 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7196 tconn->specific[key] = ptr;
7198 MUTEX_EXIT(&tconn->conn_data_lock);
7202 rx_GetSpecific(struct rx_connection *conn, int key)
7205 struct rx_connection *tconn =
7206 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7208 MUTEX_ENTER(&tconn->conn_data_lock);
7209 if (key >= tconn->nSpecific)
7212 ptr = tconn->specific[key];
7213 MUTEX_EXIT(&tconn->conn_data_lock);
7217 #endif /* !KERNEL */
7220 * processStats is a queue used to store the statistics for the local
7221 * process. Its contents are similar to the contents of the rpcStats
7222 * queue on a rx_peer structure, but the actual data stored within
7223 * this queue contains totals across the lifetime of the process (assuming
7224 * the stats have not been reset) - unlike the per peer structures
7225 * which can come and go based upon the peer lifetime.
7228 static struct rx_queue processStats = { &processStats, &processStats };
7231 * peerStats is a queue used to store the statistics for all peer structs.
7232 * Its contents are the union of all the peer rpcStats queues.
7235 static struct rx_queue peerStats = { &peerStats, &peerStats };
7238 * rxi_monitor_processStats is used to turn process wide stat collection
7242 static int rxi_monitor_processStats = 0;
7245 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7248 static int rxi_monitor_peerStats = 0;
7251 * rxi_AddRpcStat - given all of the information for a particular rpc
7252 * call, create (if needed) and update the stat totals for the rpc.
7256 * IN stats - the queue of stats that will be updated with the new value
7258 * IN rxInterface - a unique number that identifies the rpc interface
7260 * IN currentFunc - the index of the function being invoked
7262 * IN totalFunc - the total number of functions in this interface
7264 * IN queueTime - the amount of time this function waited for a thread
7266 * IN execTime - the amount of time this function invocation took to execute
7268 * IN bytesSent - the number bytes sent by this invocation
7270 * IN bytesRcvd - the number bytes received by this invocation
7272 * IN isServer - if true, this invocation was made to a server
7274 * IN remoteHost - the ip address of the remote host
7276 * IN remotePort - the port of the remote host
7278 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7280 * INOUT counter - if a new stats structure is allocated, the counter will
7281 * be updated with the new number of allocated stat structures
7289 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7290 afs_uint32 currentFunc, afs_uint32 totalFunc,
7291 struct clock *queueTime, struct clock *execTime,
7292 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7293 afs_uint32 remoteHost, afs_uint32 remotePort,
7294 int addToPeerList, unsigned int *counter)
7297 rx_interface_stat_p rpc_stat, nrpc_stat;
7300 * See if there's already a structure for this interface
7303 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7304 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7305 && (rpc_stat->stats[0].remote_is_server == isServer))
7310 * Didn't find a match so allocate a new structure and add it to the
7314 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7315 || (rpc_stat->stats[0].interfaceId != rxInterface)
7316 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7321 sizeof(rx_interface_stat_t) +
7322 totalFunc * sizeof(rx_function_entry_v1_t);
7324 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7325 if (rpc_stat == NULL) {
7329 *counter += totalFunc;
7330 for (i = 0; i < totalFunc; i++) {
7331 rpc_stat->stats[i].remote_peer = remoteHost;
7332 rpc_stat->stats[i].remote_port = remotePort;
7333 rpc_stat->stats[i].remote_is_server = isServer;
7334 rpc_stat->stats[i].interfaceId = rxInterface;
7335 rpc_stat->stats[i].func_total = totalFunc;
7336 rpc_stat->stats[i].func_index = i;
7337 hzero(rpc_stat->stats[i].invocations);
7338 hzero(rpc_stat->stats[i].bytes_sent);
7339 hzero(rpc_stat->stats[i].bytes_rcvd);
7340 rpc_stat->stats[i].queue_time_sum.sec = 0;
7341 rpc_stat->stats[i].queue_time_sum.usec = 0;
7342 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7343 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7344 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7345 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7346 rpc_stat->stats[i].queue_time_max.sec = 0;
7347 rpc_stat->stats[i].queue_time_max.usec = 0;
7348 rpc_stat->stats[i].execution_time_sum.sec = 0;
7349 rpc_stat->stats[i].execution_time_sum.usec = 0;
7350 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7351 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7352 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7353 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7354 rpc_stat->stats[i].execution_time_max.sec = 0;
7355 rpc_stat->stats[i].execution_time_max.usec = 0;
7357 queue_Prepend(stats, rpc_stat);
7358 if (addToPeerList) {
7359 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7364 * Increment the stats for this function
7367 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7368 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7369 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7370 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7371 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7372 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7373 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7375 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7376 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7378 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7379 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7381 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7382 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7384 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7385 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7393 * rx_IncrementTimeAndCount - increment the times and count for a particular
7398 * IN peer - the peer who invoked the rpc
7400 * IN rxInterface - a unique number that identifies the rpc interface
7402 * IN currentFunc - the index of the function being invoked
7404 * IN totalFunc - the total number of functions in this interface
7406 * IN queueTime - the amount of time this function waited for a thread
7408 * IN execTime - the amount of time this function invocation took to execute
7410 * IN bytesSent - the number bytes sent by this invocation
7412 * IN bytesRcvd - the number bytes received by this invocation
7414 * IN isServer - if true, this invocation was made to a server
7422 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7423 afs_uint32 currentFunc, afs_uint32 totalFunc,
7424 struct clock *queueTime, struct clock *execTime,
7425 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7429 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7432 MUTEX_ENTER(&rx_rpc_stats);
7433 MUTEX_ENTER(&peer->peer_lock);
7435 if (rxi_monitor_peerStats) {
7436 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7437 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7438 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7441 if (rxi_monitor_processStats) {
7442 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7443 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7444 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7447 MUTEX_EXIT(&peer->peer_lock);
7448 MUTEX_EXIT(&rx_rpc_stats);
7453 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7457 * IN callerVersion - the rpc stat version of the caller.
7459 * IN count - the number of entries to marshall.
7461 * IN stats - pointer to stats to be marshalled.
7463 * OUT ptr - Where to store the marshalled data.
7470 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7471 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7477 * We only support the first version
7479 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7480 *(ptr++) = stats->remote_peer;
7481 *(ptr++) = stats->remote_port;
7482 *(ptr++) = stats->remote_is_server;
7483 *(ptr++) = stats->interfaceId;
7484 *(ptr++) = stats->func_total;
7485 *(ptr++) = stats->func_index;
7486 *(ptr++) = hgethi(stats->invocations);
7487 *(ptr++) = hgetlo(stats->invocations);
7488 *(ptr++) = hgethi(stats->bytes_sent);
7489 *(ptr++) = hgetlo(stats->bytes_sent);
7490 *(ptr++) = hgethi(stats->bytes_rcvd);
7491 *(ptr++) = hgetlo(stats->bytes_rcvd);
7492 *(ptr++) = stats->queue_time_sum.sec;
7493 *(ptr++) = stats->queue_time_sum.usec;
7494 *(ptr++) = stats->queue_time_sum_sqr.sec;
7495 *(ptr++) = stats->queue_time_sum_sqr.usec;
7496 *(ptr++) = stats->queue_time_min.sec;
7497 *(ptr++) = stats->queue_time_min.usec;
7498 *(ptr++) = stats->queue_time_max.sec;
7499 *(ptr++) = stats->queue_time_max.usec;
7500 *(ptr++) = stats->execution_time_sum.sec;
7501 *(ptr++) = stats->execution_time_sum.usec;
7502 *(ptr++) = stats->execution_time_sum_sqr.sec;
7503 *(ptr++) = stats->execution_time_sum_sqr.usec;
7504 *(ptr++) = stats->execution_time_min.sec;
7505 *(ptr++) = stats->execution_time_min.usec;
7506 *(ptr++) = stats->execution_time_max.sec;
7507 *(ptr++) = stats->execution_time_max.usec;
7513 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7518 * IN callerVersion - the rpc stat version of the caller
7520 * OUT myVersion - the rpc stat version of this function
7522 * OUT clock_sec - local time seconds
7524 * OUT clock_usec - local time microseconds
7526 * OUT allocSize - the number of bytes allocated to contain stats
7528 * OUT statCount - the number stats retrieved from this process.
7530 * OUT stats - the actual stats retrieved from this process.
7534 * Returns void. If successful, stats will != NULL.
7538 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7539 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7540 size_t * allocSize, afs_uint32 * statCount,
7541 afs_uint32 ** stats)
7551 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7554 * Check to see if stats are enabled
7557 MUTEX_ENTER(&rx_rpc_stats);
7558 if (!rxi_monitor_processStats) {
7559 MUTEX_EXIT(&rx_rpc_stats);
7563 clock_GetTime(&now);
7564 *clock_sec = now.sec;
7565 *clock_usec = now.usec;
7568 * Allocate the space based upon the caller version
7570 * If the client is at an older version than we are,
7571 * we return the statistic data in the older data format, but
7572 * we still return our version number so the client knows we
7573 * are maintaining more data than it can retrieve.
7576 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7577 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7578 *statCount = rxi_rpc_process_stat_cnt;
7581 * This can't happen yet, but in the future version changes
7582 * can be handled by adding additional code here
7586 if (space > (size_t) 0) {
7588 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7591 rx_interface_stat_p rpc_stat, nrpc_stat;
7595 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7597 * Copy the data based upon the caller version
7599 rx_MarshallProcessRPCStats(callerVersion,
7600 rpc_stat->stats[0].func_total,
7601 rpc_stat->stats, &ptr);
7607 MUTEX_EXIT(&rx_rpc_stats);
7612 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7616 * IN callerVersion - the rpc stat version of the caller
7618 * OUT myVersion - the rpc stat version of this function
7620 * OUT clock_sec - local time seconds
7622 * OUT clock_usec - local time microseconds
7624 * OUT allocSize - the number of bytes allocated to contain stats
7626 * OUT statCount - the number of stats retrieved from the individual
7629 * OUT stats - the actual stats retrieved from the individual peer structures.
7633 * Returns void. If successful, stats will != NULL.
7637 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7638 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7639 size_t * allocSize, afs_uint32 * statCount,
7640 afs_uint32 ** stats)
7650 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7653 * Check to see if stats are enabled
7656 MUTEX_ENTER(&rx_rpc_stats);
7657 if (!rxi_monitor_peerStats) {
7658 MUTEX_EXIT(&rx_rpc_stats);
7662 clock_GetTime(&now);
7663 *clock_sec = now.sec;
7664 *clock_usec = now.usec;
7667 * Allocate the space based upon the caller version
7669 * If the client is at an older version than we are,
7670 * we return the statistic data in the older data format, but
7671 * we still return our version number so the client knows we
7672 * are maintaining more data than it can retrieve.
7675 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7676 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7677 *statCount = rxi_rpc_peer_stat_cnt;
7680 * This can't happen yet, but in the future version changes
7681 * can be handled by adding additional code here
7685 if (space > (size_t) 0) {
7687 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7690 rx_interface_stat_p rpc_stat, nrpc_stat;
7694 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7696 * We have to fix the offset of rpc_stat since we are
7697 * keeping this structure on two rx_queues. The rx_queue
7698 * package assumes that the rx_queue member is the first
7699 * member of the structure. That is, rx_queue assumes that
7700 * any one item is only on one queue at a time. We are
7701 * breaking that assumption and so we have to do a little
7702 * math to fix our pointers.
7705 fix_offset = (char *)rpc_stat;
7706 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7707 rpc_stat = (rx_interface_stat_p) fix_offset;
7710 * Copy the data based upon the caller version
7712 rx_MarshallProcessRPCStats(callerVersion,
7713 rpc_stat->stats[0].func_total,
7714 rpc_stat->stats, &ptr);
7720 MUTEX_EXIT(&rx_rpc_stats);
7725 * rx_FreeRPCStats - free memory allocated by
7726 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7730 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7731 * rx_RetrievePeerRPCStats
7733 * IN allocSize - the number of bytes in stats.
7741 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7743 rxi_Free(stats, allocSize);
7747 * rx_queryProcessRPCStats - see if process rpc stat collection is
7748 * currently enabled.
7754 * Returns 0 if stats are not enabled != 0 otherwise
7758 rx_queryProcessRPCStats(void)
7761 MUTEX_ENTER(&rx_rpc_stats);
7762 rc = rxi_monitor_processStats;
7763 MUTEX_EXIT(&rx_rpc_stats);
7768 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7774 * Returns 0 if stats are not enabled != 0 otherwise
7778 rx_queryPeerRPCStats(void)
7781 MUTEX_ENTER(&rx_rpc_stats);
7782 rc = rxi_monitor_peerStats;
7783 MUTEX_EXIT(&rx_rpc_stats);
7788 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7798 rx_enableProcessRPCStats(void)
7800 MUTEX_ENTER(&rx_rpc_stats);
7801 rx_enable_stats = 1;
7802 rxi_monitor_processStats = 1;
7803 MUTEX_EXIT(&rx_rpc_stats);
7807 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7817 rx_enablePeerRPCStats(void)
7819 MUTEX_ENTER(&rx_rpc_stats);
7820 rx_enable_stats = 1;
7821 rxi_monitor_peerStats = 1;
7822 MUTEX_EXIT(&rx_rpc_stats);
7826 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7836 rx_disableProcessRPCStats(void)
7838 rx_interface_stat_p rpc_stat, nrpc_stat;
7841 MUTEX_ENTER(&rx_rpc_stats);
7844 * Turn off process statistics and if peer stats is also off, turn
7848 rxi_monitor_processStats = 0;
7849 if (rxi_monitor_peerStats == 0) {
7850 rx_enable_stats = 0;
7853 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7854 unsigned int num_funcs = 0;
7857 queue_Remove(rpc_stat);
7858 num_funcs = rpc_stat->stats[0].func_total;
7860 sizeof(rx_interface_stat_t) +
7861 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7863 rxi_Free(rpc_stat, space);
7864 rxi_rpc_process_stat_cnt -= num_funcs;
7866 MUTEX_EXIT(&rx_rpc_stats);
7870 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7880 rx_disablePeerRPCStats(void)
7882 struct rx_peer **peer_ptr, **peer_end;
7885 MUTEX_ENTER(&rx_rpc_stats);
7888 * Turn off peer statistics and if process stats is also off, turn
7892 rxi_monitor_peerStats = 0;
7893 if (rxi_monitor_processStats == 0) {
7894 rx_enable_stats = 0;
7897 MUTEX_ENTER(&rx_peerHashTable_lock);
7898 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7899 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7901 struct rx_peer *peer, *next, *prev;
7902 for (prev = peer = *peer_ptr; peer; peer = next) {
7904 code = MUTEX_TRYENTER(&peer->peer_lock);
7906 rx_interface_stat_p rpc_stat, nrpc_stat;
7909 (&peer->rpcStats, rpc_stat, nrpc_stat,
7910 rx_interface_stat)) {
7911 unsigned int num_funcs = 0;
7914 queue_Remove(&rpc_stat->queue_header);
7915 queue_Remove(&rpc_stat->all_peers);
7916 num_funcs = rpc_stat->stats[0].func_total;
7918 sizeof(rx_interface_stat_t) +
7919 rpc_stat->stats[0].func_total *
7920 sizeof(rx_function_entry_v1_t);
7922 rxi_Free(rpc_stat, space);
7923 rxi_rpc_peer_stat_cnt -= num_funcs;
7925 MUTEX_EXIT(&peer->peer_lock);
7926 if (prev == *peer_ptr) {
7936 MUTEX_EXIT(&rx_peerHashTable_lock);
7937 MUTEX_EXIT(&rx_rpc_stats);
7941 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7946 * IN clearFlag - flag indicating which stats to clear
7954 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7956 rx_interface_stat_p rpc_stat, nrpc_stat;
7958 MUTEX_ENTER(&rx_rpc_stats);
7960 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7961 unsigned int num_funcs = 0, i;
7962 num_funcs = rpc_stat->stats[0].func_total;
7963 for (i = 0; i < num_funcs; i++) {
7964 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7965 hzero(rpc_stat->stats[i].invocations);
7967 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7968 hzero(rpc_stat->stats[i].bytes_sent);
7970 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7971 hzero(rpc_stat->stats[i].bytes_rcvd);
7973 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7974 rpc_stat->stats[i].queue_time_sum.sec = 0;
7975 rpc_stat->stats[i].queue_time_sum.usec = 0;
7977 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7978 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7979 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7981 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7982 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7983 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7985 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7986 rpc_stat->stats[i].queue_time_max.sec = 0;
7987 rpc_stat->stats[i].queue_time_max.usec = 0;
7989 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7990 rpc_stat->stats[i].execution_time_sum.sec = 0;
7991 rpc_stat->stats[i].execution_time_sum.usec = 0;
7993 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7994 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7995 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7997 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7998 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7999 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8001 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8002 rpc_stat->stats[i].execution_time_max.sec = 0;
8003 rpc_stat->stats[i].execution_time_max.usec = 0;
8008 MUTEX_EXIT(&rx_rpc_stats);
8012 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8017 * IN clearFlag - flag indicating which stats to clear
8025 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8027 rx_interface_stat_p rpc_stat, nrpc_stat;
8029 MUTEX_ENTER(&rx_rpc_stats);
8031 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8032 unsigned int num_funcs = 0, i;
8035 * We have to fix the offset of rpc_stat since we are
8036 * keeping this structure on two rx_queues. The rx_queue
8037 * package assumes that the rx_queue member is the first
8038 * member of the structure. That is, rx_queue assumes that
8039 * any one item is only on one queue at a time. We are
8040 * breaking that assumption and so we have to do a little
8041 * math to fix our pointers.
8044 fix_offset = (char *)rpc_stat;
8045 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8046 rpc_stat = (rx_interface_stat_p) fix_offset;
8048 num_funcs = rpc_stat->stats[0].func_total;
8049 for (i = 0; i < num_funcs; i++) {
8050 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8051 hzero(rpc_stat->stats[i].invocations);
8053 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8054 hzero(rpc_stat->stats[i].bytes_sent);
8056 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8057 hzero(rpc_stat->stats[i].bytes_rcvd);
8059 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8060 rpc_stat->stats[i].queue_time_sum.sec = 0;
8061 rpc_stat->stats[i].queue_time_sum.usec = 0;
8063 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8064 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8065 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8067 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8068 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8069 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8071 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8072 rpc_stat->stats[i].queue_time_max.sec = 0;
8073 rpc_stat->stats[i].queue_time_max.usec = 0;
8075 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8076 rpc_stat->stats[i].execution_time_sum.sec = 0;
8077 rpc_stat->stats[i].execution_time_sum.usec = 0;
8079 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8080 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8081 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8083 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8084 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8085 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8087 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8088 rpc_stat->stats[i].execution_time_max.sec = 0;
8089 rpc_stat->stats[i].execution_time_max.usec = 0;
8094 MUTEX_EXIT(&rx_rpc_stats);
8098 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8099 * is authorized to enable/disable/clear RX statistics.
8101 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8104 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8106 rxi_rxstat_userok = proc;
8110 rx_RxStatUserOk(struct rx_call *call)
8112 if (!rxi_rxstat_userok)
8114 return rxi_rxstat_userok(call);
8119 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8120 * function in the MSVC runtime DLL (msvcrt.dll).
8122 * Note: the system serializes calls to this function.
8125 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8126 DWORD reason, /* reason function is being called */
8127 LPVOID reserved) /* reserved for future use */
8130 case DLL_PROCESS_ATTACH:
8131 /* library is being attached to a process */
8135 case DLL_PROCESS_DETACH:
8144 int rx_DumpCalls(FILE *outputFile, char *cookie)
8146 #ifdef RXDEBUG_PACKET
8148 #ifdef KDUMP_RX_LOCK
8149 struct rx_call_rx_lock *c;
8155 sprintf(output, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8156 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8158 for (c = rx_allCallsp; c; c = c->allNextp) {
8159 u_short rqc, tqc, iovqc;
8160 struct rx_packet *p, *np;
8162 MUTEX_ENTER(&c->lock);
8163 queue_Count(&c->rq, p, np, rx_packet, rqc);
8164 queue_Count(&c->tq, p, np, rx_packet, tqc);
8165 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8167 sprintf(output, "%s - call=0x%p, id=%u, state=%u, mode=%u, conn=%p, epoch=%u, cid=%u, callNum=%u, connFlags=0x%x, flags=0x%x, "
8168 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8169 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8170 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8171 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8172 #ifdef RX_ENABLE_LOCKS
8175 #ifdef RX_REFCOUNT_CHECK
8176 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8177 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8180 cookie, c, c->call_id, (afs_uint32)c->state, (afs_uint32)c->mode, c->conn, c->conn?c->conn->epoch:0, c->conn?c->conn->cid:0,
8181 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8182 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8183 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8184 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8185 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8186 #ifdef RX_ENABLE_LOCKS
8187 , (afs_uint32)c->refCount
8189 #ifdef RX_REFCOUNT_CHECK
8190 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8193 MUTEX_EXIT(&c->lock);
8195 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8197 sprintf(output, "%s - End dumping all Rx Calls\r\n", cookie);
8198 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8199 #endif /* RXDEBUG_PACKET */
8202 #endif /* AFS_NT40_ENV */