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 */
3276 afs_uint32 seq, serial, flags;
3278 struct rx_packet *tnp;
3279 struct clock when, now;
3280 if (rx_stats_active)
3281 rx_AtomicIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3284 /* If there are no packet buffers, drop this new packet, unless we can find
3285 * packet buffers from inactive calls */
3287 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3288 MUTEX_ENTER(&rx_freePktQ_lock);
3289 rxi_NeedMorePackets = TRUE;
3290 MUTEX_EXIT(&rx_freePktQ_lock);
3291 if (rx_stats_active)
3292 rx_AtomicIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3293 call->rprev = np->header.serial;
3294 rxi_calltrace(RX_TRACE_DROP, call);
3295 dpf(("packet %x dropped on receipt - quota problems", np));
3297 rxi_ClearReceiveQueue(call);
3298 clock_GetTime(&now);
3300 clock_Add(&when, &rx_softAckDelay);
3301 if (!call->delayedAckEvent
3302 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3303 rxevent_Cancel(call->delayedAckEvent, call,
3304 RX_CALL_REFCOUNT_DELAY);
3305 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3306 call->delayedAckEvent =
3307 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3309 /* we've damaged this call already, might as well do it in. */
3315 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3316 * packet is one of several packets transmitted as a single
3317 * datagram. Do not send any soft or hard acks until all packets
3318 * in a jumbogram have been processed. Send negative acks right away.
3320 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3321 /* tnp is non-null when there are more packets in the
3322 * current jumbo gram */
3329 seq = np->header.seq;
3330 serial = np->header.serial;
3331 flags = np->header.flags;
3333 /* If the call is in an error state, send an abort message */
3335 return rxi_SendCallAbort(call, np, istack, 0);
3337 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3338 * AFS 3.5 jumbogram. */
3339 if (flags & RX_JUMBO_PACKET) {
3340 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3345 if (np->header.spare != 0) {
3346 MUTEX_ENTER(&call->conn->conn_data_lock);
3347 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3348 MUTEX_EXIT(&call->conn->conn_data_lock);
3351 /* The usual case is that this is the expected next packet */
3352 if (seq == call->rnext) {
3354 /* Check to make sure it is not a duplicate of one already queued */
3355 if (queue_IsNotEmpty(&call->rq)
3356 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3357 if (rx_stats_active)
3358 rx_AtomicIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3359 dpf(("packet %x dropped on receipt - duplicate", np));
3360 rxevent_Cancel(call->delayedAckEvent, call,
3361 RX_CALL_REFCOUNT_DELAY);
3362 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3368 /* It's the next packet. Stick it on the receive queue
3369 * for this call. Set newPackets to make sure we wake
3370 * the reader once all packets have been processed */
3371 np->flags |= RX_PKTFLAG_RQ;
3372 queue_Prepend(&call->rq, np);
3373 #ifdef RXDEBUG_PACKET
3375 #endif /* RXDEBUG_PACKET */
3377 np = NULL; /* We can't use this anymore */
3380 /* If an ack is requested then set a flag to make sure we
3381 * send an acknowledgement for this packet */
3382 if (flags & RX_REQUEST_ACK) {
3383 ackNeeded = RX_ACK_REQUESTED;
3386 /* Keep track of whether we have received the last packet */
3387 if (flags & RX_LAST_PACKET) {
3388 call->flags |= RX_CALL_HAVE_LAST;
3392 /* Check whether we have all of the packets for this call */
3393 if (call->flags & RX_CALL_HAVE_LAST) {
3394 afs_uint32 tseq; /* temporary sequence number */
3395 struct rx_packet *tp; /* Temporary packet pointer */
3396 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3398 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3399 if (tseq != tp->header.seq)
3401 if (tp->header.flags & RX_LAST_PACKET) {
3402 call->flags |= RX_CALL_RECEIVE_DONE;
3409 /* Provide asynchronous notification for those who want it
3410 * (e.g. multi rx) */
3411 if (call->arrivalProc) {
3412 (*call->arrivalProc) (call, call->arrivalProcHandle,
3413 call->arrivalProcArg);
3414 call->arrivalProc = (void (*)())0;
3417 /* Update last packet received */
3420 /* If there is no server process serving this call, grab
3421 * one, if available. We only need to do this once. If a
3422 * server thread is available, this thread becomes a server
3423 * thread and the server thread becomes a listener thread. */
3425 TryAttach(call, socket, tnop, newcallp, 0);
3428 /* This is not the expected next packet. */
3430 /* Determine whether this is a new or old packet, and if it's
3431 * a new one, whether it fits into the current receive window.
3432 * Also figure out whether the packet was delivered in sequence.
3433 * We use the prev variable to determine whether the new packet
3434 * is the successor of its immediate predecessor in the
3435 * receive queue, and the missing flag to determine whether
3436 * any of this packets predecessors are missing. */
3438 afs_uint32 prev; /* "Previous packet" sequence number */
3439 struct rx_packet *tp; /* Temporary packet pointer */
3440 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3441 int missing; /* Are any predecessors missing? */
3443 /* If the new packet's sequence number has been sent to the
3444 * application already, then this is a duplicate */
3445 if (seq < call->rnext) {
3446 if (rx_stats_active)
3447 rx_AtomicIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3448 rxevent_Cancel(call->delayedAckEvent, call,
3449 RX_CALL_REFCOUNT_DELAY);
3450 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3456 /* If the sequence number is greater than what can be
3457 * accomodated by the current window, then send a negative
3458 * acknowledge and drop the packet */
3459 if ((call->rnext + call->rwind) <= seq) {
3460 rxevent_Cancel(call->delayedAckEvent, call,
3461 RX_CALL_REFCOUNT_DELAY);
3462 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3469 /* Look for the packet in the queue of old received packets */
3470 for (prev = call->rnext - 1, missing =
3471 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3472 /*Check for duplicate packet */
3473 if (seq == tp->header.seq) {
3474 if (rx_stats_active)
3475 rx_AtomicIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3476 rxevent_Cancel(call->delayedAckEvent, call,
3477 RX_CALL_REFCOUNT_DELAY);
3478 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3484 /* If we find a higher sequence packet, break out and
3485 * insert the new packet here. */
3486 if (seq < tp->header.seq)
3488 /* Check for missing packet */
3489 if (tp->header.seq != prev + 1) {
3493 prev = tp->header.seq;
3496 /* Keep track of whether we have received the last packet. */
3497 if (flags & RX_LAST_PACKET) {
3498 call->flags |= RX_CALL_HAVE_LAST;
3501 /* It's within the window: add it to the the receive queue.
3502 * tp is left by the previous loop either pointing at the
3503 * packet before which to insert the new packet, or at the
3504 * queue head if the queue is empty or the packet should be
3506 np->flags |= RX_PKTFLAG_RQ;
3507 #ifdef RXDEBUG_PACKET
3509 #endif /* RXDEBUG_PACKET */
3510 queue_InsertBefore(tp, np);
3514 /* Check whether we have all of the packets for this call */
3515 if ((call->flags & RX_CALL_HAVE_LAST)
3516 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3517 afs_uint32 tseq; /* temporary sequence number */
3520 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3521 if (tseq != tp->header.seq)
3523 if (tp->header.flags & RX_LAST_PACKET) {
3524 call->flags |= RX_CALL_RECEIVE_DONE;
3531 /* We need to send an ack of the packet is out of sequence,
3532 * or if an ack was requested by the peer. */
3533 if (seq != prev + 1 || missing) {
3534 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3535 } else if (flags & RX_REQUEST_ACK) {
3536 ackNeeded = RX_ACK_REQUESTED;
3539 /* Acknowledge the last packet for each call */
3540 if (flags & RX_LAST_PACKET) {
3551 * If the receiver is waiting for an iovec, fill the iovec
3552 * using the data from the receive queue */
3553 if (call->flags & RX_CALL_IOVEC_WAIT) {
3554 didHardAck = rxi_FillReadVec(call, serial);
3555 /* the call may have been aborted */
3564 /* Wakeup the reader if any */
3565 if ((call->flags & RX_CALL_READER_WAIT)
3566 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3567 || (call->iovNext >= call->iovMax)
3568 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3569 call->flags &= ~RX_CALL_READER_WAIT;
3570 #ifdef RX_ENABLE_LOCKS
3571 CV_BROADCAST(&call->cv_rq);
3573 osi_rxWakeup(&call->rq);
3579 * Send an ack when requested by the peer, or once every
3580 * rxi_SoftAckRate packets until the last packet has been
3581 * received. Always send a soft ack for the last packet in
3582 * the server's reply. */
3584 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3585 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3586 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3587 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3588 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3589 } else if (call->nSoftAcks) {
3590 clock_GetTime(&now);
3592 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3593 clock_Add(&when, &rx_lastAckDelay);
3595 clock_Add(&when, &rx_softAckDelay);
3597 if (!call->delayedAckEvent
3598 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3599 rxevent_Cancel(call->delayedAckEvent, call,
3600 RX_CALL_REFCOUNT_DELAY);
3601 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3602 call->delayedAckEvent =
3603 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3605 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3606 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3613 static void rxi_ComputeRate();
3617 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3619 struct rx_peer *peer = conn->peer;
3621 MUTEX_ENTER(&peer->peer_lock);
3622 peer->lastReachTime = clock_Sec();
3623 MUTEX_EXIT(&peer->peer_lock);
3625 MUTEX_ENTER(&conn->conn_data_lock);
3626 if (conn->flags & RX_CONN_ATTACHWAIT) {
3629 conn->flags &= ~RX_CONN_ATTACHWAIT;
3630 MUTEX_EXIT(&conn->conn_data_lock);
3632 for (i = 0; i < RX_MAXCALLS; i++) {
3633 struct rx_call *call = conn->call[i];
3636 MUTEX_ENTER(&call->lock);
3637 /* tnop can be null if newcallp is null */
3638 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3640 MUTEX_EXIT(&call->lock);
3644 MUTEX_EXIT(&conn->conn_data_lock);
3648 rx_ack_reason(int reason)
3651 case RX_ACK_REQUESTED:
3653 case RX_ACK_DUPLICATE:
3655 case RX_ACK_OUT_OF_SEQUENCE:
3657 case RX_ACK_EXCEEDS_WINDOW:
3659 case RX_ACK_NOSPACE:
3663 case RX_ACK_PING_RESPONSE:
3675 /* rxi_ComputePeerNetStats
3677 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3678 * estimates (like RTT and throughput) based on ack packets. Caller
3679 * must ensure that the packet in question is the right one (i.e.
3680 * serial number matches).
3683 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3684 struct rx_ackPacket *ap, struct rx_packet *np)
3686 struct rx_peer *peer = call->conn->peer;
3688 /* Use RTT if not delayed by client. */
3689 if (ap->reason != RX_ACK_DELAY)
3690 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3692 rxi_ComputeRate(peer, call, p, np, ap->reason);
3696 /* The real smarts of the whole thing. */
3698 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3701 struct rx_ackPacket *ap;
3703 struct rx_packet *tp;
3704 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3705 struct rx_connection *conn = call->conn;
3706 struct rx_peer *peer = conn->peer;
3709 /* because there are CM's that are bogus, sending weird values for this. */
3710 afs_uint32 skew = 0;
3715 int newAckCount = 0;
3716 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3717 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3719 if (rx_stats_active)
3720 rx_AtomicIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3721 ap = (struct rx_ackPacket *)rx_DataOf(np);
3722 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3724 return np; /* truncated ack packet */
3726 /* depends on ack packet struct */
3727 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3728 first = ntohl(ap->firstPacket);
3729 serial = ntohl(ap->serial);
3730 /* temporarily disabled -- needs to degrade over time
3731 * skew = ntohs(ap->maxSkew); */
3733 /* Ignore ack packets received out of order */
3734 if (first < call->tfirst) {
3738 if (np->header.flags & RX_SLOW_START_OK) {
3739 call->flags |= RX_CALL_SLOW_START_OK;
3742 if (ap->reason == RX_ACK_PING_RESPONSE)
3743 rxi_UpdatePeerReach(conn, call);
3747 if (rxdebug_active) {
3751 len = _snprintf(msg, sizeof(msg),
3752 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3753 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3754 ntohl(ap->serial), ntohl(ap->previousPacket),
3755 (unsigned int)np->header.seq, (unsigned int)skew,
3756 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3760 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3761 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3765 OutputDebugString(msg);
3767 #else /* AFS_NT40_ENV */
3770 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3771 ap->reason, ntohl(ap->previousPacket),
3772 (unsigned int)np->header.seq, (unsigned int)serial,
3773 (unsigned int)skew, ntohl(ap->firstPacket));
3776 for (offset = 0; offset < nAcks; offset++)
3777 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3782 #endif /* AFS_NT40_ENV */
3785 /* Update the outgoing packet skew value to the latest value of
3786 * the peer's incoming packet skew value. The ack packet, of
3787 * course, could arrive out of order, but that won't affect things
3789 MUTEX_ENTER(&peer->peer_lock);
3790 peer->outPacketSkew = skew;
3792 /* Check for packets that no longer need to be transmitted, and
3793 * discard them. This only applies to packets positively
3794 * acknowledged as having been sent to the peer's upper level.
3795 * All other packets must be retained. So only packets with
3796 * sequence numbers < ap->firstPacket are candidates. */
3797 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3798 if (tp->header.seq >= first)
3800 call->tfirst = tp->header.seq + 1;
3802 && (tp->header.serial == serial || tp->firstSerial == serial))
3803 rxi_ComputePeerNetStats(call, tp, ap, np);
3804 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3807 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3808 /* XXX Hack. Because we have to release the global rx lock when sending
3809 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3810 * in rxi_Start sending packets out because packets may move to the
3811 * freePacketQueue as result of being here! So we drop these packets until
3812 * we're safely out of the traversing. Really ugly!
3813 * To make it even uglier, if we're using fine grain locking, we can
3814 * set the ack bits in the packets and have rxi_Start remove the packets
3815 * when it's done transmitting.
3817 if (call->flags & RX_CALL_TQ_BUSY) {
3818 #ifdef RX_ENABLE_LOCKS
3819 tp->flags |= RX_PKTFLAG_ACKED;
3820 call->flags |= RX_CALL_TQ_SOME_ACKED;
3821 #else /* RX_ENABLE_LOCKS */
3823 #endif /* RX_ENABLE_LOCKS */
3825 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3828 tp->flags &= ~RX_PKTFLAG_TQ;
3829 #ifdef RXDEBUG_PACKET
3831 #endif /* RXDEBUG_PACKET */
3832 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3837 /* Give rate detector a chance to respond to ping requests */
3838 if (ap->reason == RX_ACK_PING_RESPONSE) {
3839 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3843 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3845 /* Now go through explicit acks/nacks and record the results in
3846 * the waiting packets. These are packets that can't be released
3847 * yet, even with a positive acknowledge. This positive
3848 * acknowledge only means the packet has been received by the
3849 * peer, not that it will be retained long enough to be sent to
3850 * the peer's upper level. In addition, reset the transmit timers
3851 * of any missing packets (those packets that must be missing
3852 * because this packet was out of sequence) */
3854 call->nSoftAcked = 0;
3855 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3856 /* Update round trip time if the ack was stimulated on receipt
3858 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3859 #ifdef RX_ENABLE_LOCKS
3860 if (tp->header.seq >= first)
3861 #endif /* RX_ENABLE_LOCKS */
3862 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3864 && (tp->header.serial == serial || tp->firstSerial == serial))
3865 rxi_ComputePeerNetStats(call, tp, ap, np);
3867 /* Set the acknowledge flag per packet based on the
3868 * information in the ack packet. An acknowlegded packet can
3869 * be downgraded when the server has discarded a packet it
3870 * soacked previously, or when an ack packet is received
3871 * out of sequence. */
3872 if (tp->header.seq < first) {
3873 /* Implicit ack information */
3874 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3877 tp->flags |= RX_PKTFLAG_ACKED;
3878 } else if (tp->header.seq < first + nAcks) {
3879 /* Explicit ack information: set it in the packet appropriately */
3880 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3881 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3883 tp->flags |= RX_PKTFLAG_ACKED;
3890 } else /* RX_ACK_TYPE_NACK */ {
3891 tp->flags &= ~RX_PKTFLAG_ACKED;
3895 tp->flags &= ~RX_PKTFLAG_ACKED;
3899 /* If packet isn't yet acked, and it has been transmitted at least
3900 * once, reset retransmit time using latest timeout
3901 * ie, this should readjust the retransmit timer for all outstanding
3902 * packets... So we don't just retransmit when we should know better*/
3904 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3905 tp->retryTime = tp->timeSent;
3906 clock_Add(&tp->retryTime, &peer->timeout);
3907 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3908 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3912 /* If the window has been extended by this acknowledge packet,
3913 * then wakeup a sender waiting in alloc for window space, or try
3914 * sending packets now, if he's been sitting on packets due to
3915 * lack of window space */
3916 if (call->tnext < (call->tfirst + call->twind)) {
3917 #ifdef RX_ENABLE_LOCKS
3918 CV_SIGNAL(&call->cv_twind);
3920 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3921 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3922 osi_rxWakeup(&call->twind);
3925 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3926 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3930 /* if the ack packet has a receivelen field hanging off it,
3931 * update our state */
3932 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3935 /* If the ack packet has a "recommended" size that is less than
3936 * what I am using now, reduce my size to match */
3937 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3938 (int)sizeof(afs_int32), &tSize);
3939 tSize = (afs_uint32) ntohl(tSize);
3940 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3942 /* Get the maximum packet size to send to this peer */
3943 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3945 tSize = (afs_uint32) ntohl(tSize);
3946 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3947 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3949 /* sanity check - peer might have restarted with different params.
3950 * If peer says "send less", dammit, send less... Peer should never
3951 * be unable to accept packets of the size that prior AFS versions would
3952 * send without asking. */
3953 if (peer->maxMTU != tSize) {
3954 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3956 peer->maxMTU = tSize;
3957 peer->MTU = MIN(tSize, peer->MTU);
3958 call->MTU = MIN(call->MTU, tSize);
3961 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3964 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3965 (int)sizeof(afs_int32), &tSize);
3966 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3967 if (tSize < call->twind) { /* smaller than our send */
3968 call->twind = tSize; /* window, we must send less... */
3969 call->ssthresh = MIN(call->twind, call->ssthresh);
3970 call->conn->twind[call->channel] = call->twind;
3973 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3974 * network MTU confused with the loopback MTU. Calculate the
3975 * maximum MTU here for use in the slow start code below.
3977 maxMTU = peer->maxMTU;
3978 /* Did peer restart with older RX version? */
3979 if (peer->maxDgramPackets > 1) {
3980 peer->maxDgramPackets = 1;
3982 } else if (np->length >=
3983 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3986 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3987 sizeof(afs_int32), &tSize);
3988 tSize = (afs_uint32) ntohl(tSize);
3990 * As of AFS 3.5 we set the send window to match the receive window.
3992 if (tSize < call->twind) {
3993 call->twind = tSize;
3994 call->conn->twind[call->channel] = call->twind;
3995 call->ssthresh = MIN(call->twind, call->ssthresh);
3996 } else if (tSize > call->twind) {
3997 call->twind = tSize;
3998 call->conn->twind[call->channel] = call->twind;
4002 * As of AFS 3.5, a jumbogram is more than one fixed size
4003 * packet transmitted in a single UDP datagram. If the remote
4004 * MTU is smaller than our local MTU then never send a datagram
4005 * larger than the natural MTU.
4008 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
4009 sizeof(afs_int32), &tSize);
4010 maxDgramPackets = (afs_uint32) ntohl(tSize);
4011 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4012 maxDgramPackets = MIN(maxDgramPackets, peer->ifDgramPackets);
4013 if (peer->natMTU < peer->ifMTU)
4014 maxDgramPackets = MIN(maxDgramPackets, rxi_AdjustDgramPackets(1, peer->natMTU));
4015 if (maxDgramPackets > 1) {
4016 peer->maxDgramPackets = maxDgramPackets;
4017 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4019 peer->maxDgramPackets = 1;
4020 call->MTU = peer->natMTU;
4022 } else if (peer->maxDgramPackets > 1) {
4023 /* Restarted with lower version of RX */
4024 peer->maxDgramPackets = 1;
4026 } else if (peer->maxDgramPackets > 1
4027 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4028 /* Restarted with lower version of RX */
4029 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4030 peer->natMTU = OLD_MAX_PACKET_SIZE;
4031 peer->MTU = OLD_MAX_PACKET_SIZE;
4032 peer->maxDgramPackets = 1;
4033 peer->nDgramPackets = 1;
4035 call->MTU = OLD_MAX_PACKET_SIZE;
4040 * Calculate how many datagrams were successfully received after
4041 * the first missing packet and adjust the negative ack counter
4046 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4047 if (call->nNacks < nNacked) {
4048 call->nNacks = nNacked;
4051 call->nAcks += newAckCount;
4055 if (call->flags & RX_CALL_FAST_RECOVER) {
4057 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4059 call->flags &= ~RX_CALL_FAST_RECOVER;
4060 call->cwind = call->nextCwind;
4061 call->nextCwind = 0;
4064 call->nCwindAcks = 0;
4065 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4066 /* Three negative acks in a row trigger congestion recovery */
4067 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4068 MUTEX_EXIT(&peer->peer_lock);
4069 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4070 /* someone else is waiting to start recovery */
4073 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4074 rxi_WaitforTQBusy(call);
4075 MUTEX_ENTER(&peer->peer_lock);
4076 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4077 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4078 call->flags |= RX_CALL_FAST_RECOVER;
4079 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4081 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4082 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4083 call->nextCwind = call->ssthresh;
4086 peer->MTU = call->MTU;
4087 peer->cwind = call->nextCwind;
4088 peer->nDgramPackets = call->nDgramPackets;
4090 call->congestSeq = peer->congestSeq;
4091 /* Reset the resend times on the packets that were nacked
4092 * so we will retransmit as soon as the window permits*/
4093 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4095 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4096 clock_Zero(&tp->retryTime);
4098 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4103 /* If cwind is smaller than ssthresh, then increase
4104 * the window one packet for each ack we receive (exponential
4106 * If cwind is greater than or equal to ssthresh then increase
4107 * the congestion window by one packet for each cwind acks we
4108 * receive (linear growth). */
4109 if (call->cwind < call->ssthresh) {
4111 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4112 call->nCwindAcks = 0;
4114 call->nCwindAcks += newAckCount;
4115 if (call->nCwindAcks >= call->cwind) {
4116 call->nCwindAcks = 0;
4117 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4121 * If we have received several acknowledgements in a row then
4122 * it is time to increase the size of our datagrams
4124 if ((int)call->nAcks > rx_nDgramThreshold) {
4125 if (peer->maxDgramPackets > 1) {
4126 if (call->nDgramPackets < peer->maxDgramPackets) {
4127 call->nDgramPackets++;
4129 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4130 } else if (call->MTU < peer->maxMTU) {
4131 call->MTU += peer->natMTU;
4132 call->MTU = MIN(call->MTU, peer->maxMTU);
4138 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4140 /* Servers need to hold the call until all response packets have
4141 * been acknowledged. Soft acks are good enough since clients
4142 * are not allowed to clear their receive queues. */
4143 if (call->state == RX_STATE_HOLD
4144 && call->tfirst + call->nSoftAcked >= call->tnext) {
4145 call->state = RX_STATE_DALLY;
4146 rxi_ClearTransmitQueue(call, 0);
4147 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4148 } else if (!queue_IsEmpty(&call->tq)) {
4149 rxi_Start(0, call, 0, istack);
4154 /* Received a response to a challenge packet */
4156 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4157 struct rx_packet *np, int istack)
4161 /* Ignore the packet if we're the client */
4162 if (conn->type == RX_CLIENT_CONNECTION)
4165 /* If already authenticated, ignore the packet (it's probably a retry) */
4166 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4169 /* Otherwise, have the security object evaluate the response packet */
4170 error = RXS_CheckResponse(conn->securityObject, conn, np);
4172 /* If the response is invalid, reset the connection, sending
4173 * an abort to the peer */
4177 rxi_ConnectionError(conn, error);
4178 MUTEX_ENTER(&conn->conn_data_lock);
4179 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4180 MUTEX_EXIT(&conn->conn_data_lock);
4183 /* If the response is valid, any calls waiting to attach
4184 * servers can now do so */
4187 for (i = 0; i < RX_MAXCALLS; i++) {
4188 struct rx_call *call = conn->call[i];
4190 MUTEX_ENTER(&call->lock);
4191 if (call->state == RX_STATE_PRECALL)
4192 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4193 /* tnop can be null if newcallp is null */
4194 MUTEX_EXIT(&call->lock);
4198 /* Update the peer reachability information, just in case
4199 * some calls went into attach-wait while we were waiting
4200 * for authentication..
4202 rxi_UpdatePeerReach(conn, NULL);
4207 /* A client has received an authentication challenge: the security
4208 * object is asked to cough up a respectable response packet to send
4209 * back to the server. The server is responsible for retrying the
4210 * challenge if it fails to get a response. */
4213 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4214 struct rx_packet *np, int istack)
4218 /* Ignore the challenge if we're the server */
4219 if (conn->type == RX_SERVER_CONNECTION)
4222 /* Ignore the challenge if the connection is otherwise idle; someone's
4223 * trying to use us as an oracle. */
4224 if (!rxi_HasActiveCalls(conn))
4227 /* Send the security object the challenge packet. It is expected to fill
4228 * in the response. */
4229 error = RXS_GetResponse(conn->securityObject, conn, np);
4231 /* If the security object is unable to return a valid response, reset the
4232 * connection and send an abort to the peer. Otherwise send the response
4233 * packet to the peer connection. */
4235 rxi_ConnectionError(conn, error);
4236 MUTEX_ENTER(&conn->conn_data_lock);
4237 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4238 MUTEX_EXIT(&conn->conn_data_lock);
4240 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4241 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4247 /* Find an available server process to service the current request in
4248 * the given call structure. If one isn't available, queue up this
4249 * call so it eventually gets one */
4251 rxi_AttachServerProc(struct rx_call *call,
4252 osi_socket socket, int *tnop,
4253 struct rx_call **newcallp)
4255 struct rx_serverQueueEntry *sq;
4256 struct rx_service *service = call->conn->service;
4259 /* May already be attached */
4260 if (call->state == RX_STATE_ACTIVE)
4263 MUTEX_ENTER(&rx_serverPool_lock);
4265 haveQuota = QuotaOK(service);
4266 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4267 /* If there are no processes available to service this call,
4268 * put the call on the incoming call queue (unless it's
4269 * already on the queue).
4271 #ifdef RX_ENABLE_LOCKS
4273 ReturnToServerPool(service);
4274 #endif /* RX_ENABLE_LOCKS */
4276 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4277 call->flags |= RX_CALL_WAIT_PROC;
4278 MUTEX_ENTER(&rx_waiting_mutex);
4281 MUTEX_EXIT(&rx_waiting_mutex);
4282 rxi_calltrace(RX_CALL_ARRIVAL, call);
4283 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4284 queue_Append(&rx_incomingCallQueue, call);
4287 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4289 /* If hot threads are enabled, and both newcallp and sq->socketp
4290 * are non-null, then this thread will process the call, and the
4291 * idle server thread will start listening on this threads socket.
4294 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4297 *sq->socketp = socket;
4298 clock_GetTime(&call->startTime);
4299 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4303 if (call->flags & RX_CALL_WAIT_PROC) {
4304 /* Conservative: I don't think this should happen */
4305 call->flags &= ~RX_CALL_WAIT_PROC;
4306 if (queue_IsOnQueue(call)) {
4309 MUTEX_ENTER(&rx_waiting_mutex);
4311 MUTEX_EXIT(&rx_waiting_mutex);
4314 call->state = RX_STATE_ACTIVE;
4315 call->mode = RX_MODE_RECEIVING;
4316 #ifdef RX_KERNEL_TRACE
4318 int glockOwner = ISAFS_GLOCK();
4321 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4322 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4328 if (call->flags & RX_CALL_CLEARED) {
4329 /* send an ack now to start the packet flow up again */
4330 call->flags &= ~RX_CALL_CLEARED;
4331 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4333 #ifdef RX_ENABLE_LOCKS
4336 service->nRequestsRunning++;
4337 if (service->nRequestsRunning <= service->minProcs)
4343 MUTEX_EXIT(&rx_serverPool_lock);
4346 /* Delay the sending of an acknowledge event for a short while, while
4347 * a new call is being prepared (in the case of a client) or a reply
4348 * is being prepared (in the case of a server). Rather than sending
4349 * an ack packet, an ACKALL packet is sent. */
4351 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4353 #ifdef RX_ENABLE_LOCKS
4355 MUTEX_ENTER(&call->lock);
4356 call->delayedAckEvent = NULL;
4357 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4359 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4360 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4362 MUTEX_EXIT(&call->lock);
4363 #else /* RX_ENABLE_LOCKS */
4365 call->delayedAckEvent = NULL;
4366 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4367 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4368 #endif /* RX_ENABLE_LOCKS */
4372 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4374 struct rx_call *call = arg1;
4375 #ifdef RX_ENABLE_LOCKS
4377 MUTEX_ENTER(&call->lock);
4378 if (event == call->delayedAckEvent)
4379 call->delayedAckEvent = NULL;
4380 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4382 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4384 MUTEX_EXIT(&call->lock);
4385 #else /* RX_ENABLE_LOCKS */
4387 call->delayedAckEvent = NULL;
4388 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4389 #endif /* RX_ENABLE_LOCKS */
4393 #ifdef RX_ENABLE_LOCKS
4394 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4395 * clearing them out.
4398 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4400 struct rx_packet *p, *tp;
4403 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4404 p->flags |= RX_PKTFLAG_ACKED;
4408 call->flags |= RX_CALL_TQ_CLEARME;
4409 call->flags |= RX_CALL_TQ_SOME_ACKED;
4412 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4413 call->tfirst = call->tnext;
4414 call->nSoftAcked = 0;
4416 if (call->flags & RX_CALL_FAST_RECOVER) {
4417 call->flags &= ~RX_CALL_FAST_RECOVER;
4418 call->cwind = call->nextCwind;
4419 call->nextCwind = 0;
4422 CV_SIGNAL(&call->cv_twind);
4424 #endif /* RX_ENABLE_LOCKS */
4426 /* Clear out the transmit queue for the current call (all packets have
4427 * been received by peer) */
4429 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4431 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4432 struct rx_packet *p, *tp;
4434 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4436 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4437 p->flags |= RX_PKTFLAG_ACKED;
4441 call->flags |= RX_CALL_TQ_CLEARME;
4442 call->flags |= RX_CALL_TQ_SOME_ACKED;
4445 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4446 #ifdef RXDEBUG_PACKET
4448 #endif /* RXDEBUG_PACKET */
4449 rxi_FreePackets(0, &call->tq);
4450 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4451 call->flags &= ~RX_CALL_TQ_CLEARME;
4453 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4455 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4456 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4457 call->nSoftAcked = 0;
4459 if (call->flags & RX_CALL_FAST_RECOVER) {
4460 call->flags &= ~RX_CALL_FAST_RECOVER;
4461 call->cwind = call->nextCwind;
4463 #ifdef RX_ENABLE_LOCKS
4464 CV_SIGNAL(&call->cv_twind);
4466 osi_rxWakeup(&call->twind);
4471 rxi_ClearReceiveQueue(struct rx_call *call)
4473 if (queue_IsNotEmpty(&call->rq)) {
4476 count = rxi_FreePackets(0, &call->rq);
4477 rx_packetReclaims += count;
4478 #ifdef RXDEBUG_PACKET
4480 if ( call->rqc != 0 )
4481 dpf(("rxi_ClearReceiveQueue call %x rqc %u != 0", call, call->rqc));
4483 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4485 if (call->state == RX_STATE_PRECALL) {
4486 call->flags |= RX_CALL_CLEARED;
4490 /* Send an abort packet for the specified call */
4492 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4493 int istack, int force)
4496 struct clock when, now;
4501 /* Clients should never delay abort messages */
4502 if (rx_IsClientConn(call->conn))
4505 if (call->abortCode != call->error) {
4506 call->abortCode = call->error;
4507 call->abortCount = 0;
4510 if (force || rxi_callAbortThreshhold == 0
4511 || call->abortCount < rxi_callAbortThreshhold) {
4512 if (call->delayedAbortEvent) {
4513 rxevent_Cancel(call->delayedAbortEvent, call,
4514 RX_CALL_REFCOUNT_ABORT);
4516 error = htonl(call->error);
4519 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4520 (char *)&error, sizeof(error), istack);
4521 } else if (!call->delayedAbortEvent) {
4522 clock_GetTime(&now);
4524 clock_Addmsec(&when, rxi_callAbortDelay);
4525 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4526 call->delayedAbortEvent =
4527 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4532 /* Send an abort packet for the specified connection. Packet is an
4533 * optional pointer to a packet that can be used to send the abort.
4534 * Once the number of abort messages reaches the threshhold, an
4535 * event is scheduled to send the abort. Setting the force flag
4536 * overrides sending delayed abort messages.
4538 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4539 * to send the abort packet.
4542 rxi_SendConnectionAbort(struct rx_connection *conn,
4543 struct rx_packet *packet, int istack, int force)
4546 struct clock when, now;
4548 if (!rx_ConnError(conn))
4551 /* Clients should never delay abort messages */
4552 if (rx_IsClientConn(conn))
4555 if (force || rxi_connAbortThreshhold == 0
4556 || conn->abortCount < rxi_connAbortThreshhold) {
4557 if (conn->delayedAbortEvent) {
4558 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4560 error = htonl(rx_ConnError(conn));
4562 MUTEX_EXIT(&conn->conn_data_lock);
4564 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4565 RX_PACKET_TYPE_ABORT, (char *)&error,
4566 sizeof(error), istack);
4567 MUTEX_ENTER(&conn->conn_data_lock);
4568 } else if (!conn->delayedAbortEvent) {
4569 clock_GetTime(&now);
4571 clock_Addmsec(&when, rxi_connAbortDelay);
4572 conn->delayedAbortEvent =
4573 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4579 * Associate an error all of the calls owned by a connection. Called
4580 * with error non-zero. This is only for really fatal things, like
4581 * bad authentication responses. The connection itself is set in
4582 * error at this point, so that future packets received will be
4586 rxi_ConnectionError(struct rx_connection *conn,
4591 struct rx_connection *tconn;
4593 dpf(("rxi_ConnectionError conn %x error %d", conn, error));
4595 MUTEX_ENTER(&conn->conn_data_lock);
4596 if (conn->challengeEvent)
4597 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4598 if (conn->checkReachEvent) {
4599 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4600 conn->checkReachEvent = 0;
4601 conn->flags &= ~RX_CONN_ATTACHWAIT;
4602 rx_AtomicDecrement_NL(conn->refCount);
4604 MUTEX_EXIT(&conn->conn_data_lock);
4606 for ( tconn = rx_IsClonedConn(conn) ? conn->parent : conn;
4608 tconn = tconn->next_clone) {
4609 for (i = 0; i < RX_MAXCALLS; i++) {
4610 struct rx_call *call = tconn->call[i];
4612 MUTEX_ENTER(&call->lock);
4613 rxi_CallError(call, error);
4614 MUTEX_EXIT(&call->lock);
4618 rx_SetConnError(conn, error);
4619 if (rx_stats_active)
4620 rx_AtomicIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4625 rxi_CallError(struct rx_call *call, afs_int32 error)
4628 osirx_AssertMine(&call->lock, "rxi_CallError");
4630 dpf(("rxi_CallError call %x error %d call->error %d", call, error, call->error));
4632 error = call->error;
4634 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4635 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4636 rxi_ResetCall(call, 0);
4639 rxi_ResetCall(call, 0);
4641 call->error = error;
4642 call->mode = RX_MODE_ERROR;
4645 /* Reset various fields in a call structure, and wakeup waiting
4646 * processes. Some fields aren't changed: state & mode are not
4647 * touched (these must be set by the caller), and bufptr, nLeft, and
4648 * nFree are not reset, since these fields are manipulated by
4649 * unprotected macros, and may only be reset by non-interrupting code.
4652 /* this code requires that call->conn be set properly as a pre-condition. */
4653 #endif /* ADAPT_WINDOW */
4656 rxi_ResetCall(struct rx_call *call, int newcall)
4659 struct rx_peer *peer;
4660 struct rx_packet *packet;
4662 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4664 dpf(("rxi_ResetCall(call %x, newcall %d)\n", call, newcall));
4666 /* Notify anyone who is waiting for asynchronous packet arrival */
4667 if (call->arrivalProc) {
4668 (*call->arrivalProc) (call, call->arrivalProcHandle,
4669 call->arrivalProcArg);
4670 call->arrivalProc = (void (*)())0;
4673 if (call->delayedAbortEvent) {
4674 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4675 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4677 rxi_SendCallAbort(call, packet, 0, 1);
4678 rxi_FreePacket(packet);
4683 * Update the peer with the congestion information in this call
4684 * so other calls on this connection can pick up where this call
4685 * left off. If the congestion sequence numbers don't match then
4686 * another call experienced a retransmission.
4688 peer = call->conn->peer;
4689 MUTEX_ENTER(&peer->peer_lock);
4691 if (call->congestSeq == peer->congestSeq) {
4692 peer->cwind = MAX(peer->cwind, call->cwind);
4693 peer->MTU = MAX(peer->MTU, call->MTU);
4694 peer->nDgramPackets =
4695 MAX(peer->nDgramPackets, call->nDgramPackets);
4698 call->abortCode = 0;
4699 call->abortCount = 0;
4701 if (peer->maxDgramPackets > 1) {
4702 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4704 call->MTU = peer->MTU;
4706 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4707 call->ssthresh = rx_maxSendWindow;
4708 call->nDgramPackets = peer->nDgramPackets;
4709 call->congestSeq = peer->congestSeq;
4710 MUTEX_EXIT(&peer->peer_lock);
4712 flags = call->flags;
4713 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4714 if (flags & RX_CALL_TQ_BUSY) {
4715 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4716 call->flags |= (flags & RX_CALL_TQ_WAIT);
4718 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4720 rxi_ClearTransmitQueue(call, 1);
4721 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4722 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4723 dpf(("rcall %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4726 while (call->tqWaiters) {
4727 #ifdef RX_ENABLE_LOCKS
4728 CV_BROADCAST(&call->cv_tq);
4729 #else /* RX_ENABLE_LOCKS */
4730 osi_rxWakeup(&call->tq);
4731 #endif /* RX_ENABLE_LOCKS */
4736 rxi_ClearReceiveQueue(call);
4737 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4739 if (call->currentPacket) {
4740 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4741 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4742 queue_Prepend(&call->iovq, call->currentPacket);
4743 #ifdef RXDEBUG_PACKET
4745 #endif /* RXDEBUG_PACKET */
4746 call->currentPacket = (struct rx_packet *)0;
4748 call->curlen = call->nLeft = call->nFree = 0;
4750 #ifdef RXDEBUG_PACKET
4753 rxi_FreePackets(0, &call->iovq);
4756 call->twind = call->conn->twind[call->channel];
4757 call->rwind = call->conn->rwind[call->channel];
4758 call->nSoftAcked = 0;
4759 call->nextCwind = 0;
4762 call->nCwindAcks = 0;
4763 call->nSoftAcks = 0;
4764 call->nHardAcks = 0;
4766 call->tfirst = call->rnext = call->tnext = 1;
4768 call->lastAcked = 0;
4769 call->localStatus = call->remoteStatus = 0;
4771 if (flags & RX_CALL_READER_WAIT) {
4772 #ifdef RX_ENABLE_LOCKS
4773 CV_BROADCAST(&call->cv_rq);
4775 osi_rxWakeup(&call->rq);
4778 if (flags & RX_CALL_WAIT_PACKETS) {
4779 MUTEX_ENTER(&rx_freePktQ_lock);
4780 rxi_PacketsUnWait(); /* XXX */
4781 MUTEX_EXIT(&rx_freePktQ_lock);
4783 #ifdef RX_ENABLE_LOCKS
4784 CV_SIGNAL(&call->cv_twind);
4786 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4787 osi_rxWakeup(&call->twind);
4790 #ifdef RX_ENABLE_LOCKS
4791 /* The following ensures that we don't mess with any queue while some
4792 * other thread might also be doing so. The call_queue_lock field is
4793 * is only modified under the call lock. If the call is in the process
4794 * of being removed from a queue, the call is not locked until the
4795 * the queue lock is dropped and only then is the call_queue_lock field
4796 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4797 * Note that any other routine which removes a call from a queue has to
4798 * obtain the queue lock before examing the queue and removing the call.
4800 if (call->call_queue_lock) {
4801 MUTEX_ENTER(call->call_queue_lock);
4802 if (queue_IsOnQueue(call)) {
4804 if (flags & RX_CALL_WAIT_PROC) {
4806 MUTEX_ENTER(&rx_waiting_mutex);
4808 MUTEX_EXIT(&rx_waiting_mutex);
4811 MUTEX_EXIT(call->call_queue_lock);
4812 CLEAR_CALL_QUEUE_LOCK(call);
4814 #else /* RX_ENABLE_LOCKS */
4815 if (queue_IsOnQueue(call)) {
4817 if (flags & RX_CALL_WAIT_PROC)
4820 #endif /* RX_ENABLE_LOCKS */
4822 rxi_KeepAliveOff(call);
4823 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4826 /* Send an acknowledge for the indicated packet (seq,serial) of the
4827 * indicated call, for the indicated reason (reason). This
4828 * acknowledge will specifically acknowledge receiving the packet, and
4829 * will also specify which other packets for this call have been
4830 * received. This routine returns the packet that was used to the
4831 * caller. The caller is responsible for freeing it or re-using it.
4832 * This acknowledgement also returns the highest sequence number
4833 * actually read out by the higher level to the sender; the sender
4834 * promises to keep around packets that have not been read by the
4835 * higher level yet (unless, of course, the sender decides to abort
4836 * the call altogether). Any of p, seq, serial, pflags, or reason may
4837 * be set to zero without ill effect. That is, if they are zero, they
4838 * will not convey any information.
4839 * NOW there is a trailer field, after the ack where it will safely be
4840 * ignored by mundanes, which indicates the maximum size packet this
4841 * host can swallow. */
4843 struct rx_packet *optionalPacket; use to send ack (or null)
4844 int seq; Sequence number of the packet we are acking
4845 int serial; Serial number of the packet
4846 int pflags; Flags field from packet header
4847 int reason; Reason an acknowledge was prompted
4851 rxi_SendAck(struct rx_call *call,
4852 struct rx_packet *optionalPacket, int serial, int reason,
4855 struct rx_ackPacket *ap;
4856 struct rx_packet *rqp;
4857 struct rx_packet *nxp; /* For queue_Scan */
4858 struct rx_packet *p;
4861 #ifdef RX_ENABLE_TSFPQ
4862 struct rx_ts_info_t * rx_ts_info;
4866 * Open the receive window once a thread starts reading packets
4868 if (call->rnext > 1) {
4869 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4872 call->nHardAcks = 0;
4873 call->nSoftAcks = 0;
4874 if (call->rnext > call->lastAcked)
4875 call->lastAcked = call->rnext;
4879 rx_computelen(p, p->length); /* reset length, you never know */
4880 } /* where that's been... */
4881 #ifdef RX_ENABLE_TSFPQ
4883 RX_TS_INFO_GET(rx_ts_info);
4884 if ((p = rx_ts_info->local_special_packet)) {
4885 rx_computelen(p, p->length);
4886 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4887 rx_ts_info->local_special_packet = p;
4888 } else { /* We won't send the ack, but don't panic. */
4889 return optionalPacket;
4893 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4894 /* We won't send the ack, but don't panic. */
4895 return optionalPacket;
4900 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4903 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4904 #ifndef RX_ENABLE_TSFPQ
4905 if (!optionalPacket)
4908 return optionalPacket;
4910 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4911 if (rx_Contiguous(p) < templ) {
4912 #ifndef RX_ENABLE_TSFPQ
4913 if (!optionalPacket)
4916 return optionalPacket;
4921 /* MTUXXX failing to send an ack is very serious. We should */
4922 /* try as hard as possible to send even a partial ack; it's */
4923 /* better than nothing. */
4924 ap = (struct rx_ackPacket *)rx_DataOf(p);
4925 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4926 ap->reason = reason;
4928 /* The skew computation used to be bogus, I think it's better now. */
4929 /* We should start paying attention to skew. XXX */
4930 ap->serial = htonl(serial);
4931 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4933 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4934 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4936 /* No fear of running out of ack packet here because there can only be at most
4937 * one window full of unacknowledged packets. The window size must be constrained
4938 * to be less than the maximum ack size, of course. Also, an ack should always
4939 * fit into a single packet -- it should not ever be fragmented. */
4940 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4941 if (!rqp || !call->rq.next
4942 || (rqp->header.seq > (call->rnext + call->rwind))) {
4943 #ifndef RX_ENABLE_TSFPQ
4944 if (!optionalPacket)
4947 rxi_CallError(call, RX_CALL_DEAD);
4948 return optionalPacket;
4951 while (rqp->header.seq > call->rnext + offset)
4952 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4953 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4955 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4956 #ifndef RX_ENABLE_TSFPQ
4957 if (!optionalPacket)
4960 rxi_CallError(call, RX_CALL_DEAD);
4961 return optionalPacket;
4966 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4968 /* these are new for AFS 3.3 */
4969 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4970 templ = htonl(templ);
4971 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4972 templ = htonl(call->conn->peer->ifMTU);
4973 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4974 sizeof(afs_int32), &templ);
4976 /* new for AFS 3.4 */
4977 templ = htonl(call->rwind);
4978 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4979 sizeof(afs_int32), &templ);
4981 /* new for AFS 3.5 */
4982 templ = htonl(call->conn->peer->ifDgramPackets);
4983 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4984 sizeof(afs_int32), &templ);
4986 p->header.serviceId = call->conn->serviceId;
4987 p->header.cid = (call->conn->cid | call->channel);
4988 p->header.callNumber = *call->callNumber;
4990 p->header.securityIndex = call->conn->securityIndex;
4991 p->header.epoch = call->conn->epoch;
4992 p->header.type = RX_PACKET_TYPE_ACK;
4993 p->header.flags = RX_SLOW_START_OK;
4994 if (reason == RX_ACK_PING) {
4995 p->header.flags |= RX_REQUEST_ACK;
4997 clock_GetTime(&call->pingRequestTime);
5000 if (call->conn->type == RX_CLIENT_CONNECTION)
5001 p->header.flags |= RX_CLIENT_INITIATED;
5005 if (rxdebug_active) {
5009 len = _snprintf(msg, sizeof(msg),
5010 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5011 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5012 ntohl(ap->serial), ntohl(ap->previousPacket),
5013 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5014 ap->nAcks, ntohs(ap->bufferSpace) );
5018 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5019 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5023 OutputDebugString(msg);
5025 #else /* AFS_NT40_ENV */
5027 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5028 ap->reason, ntohl(ap->previousPacket),
5029 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5031 for (offset = 0; offset < ap->nAcks; offset++)
5032 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5037 #endif /* AFS_NT40_ENV */
5040 int i, nbytes = p->length;
5042 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5043 if (nbytes <= p->wirevec[i].iov_len) {
5046 savelen = p->wirevec[i].iov_len;
5048 p->wirevec[i].iov_len = nbytes;
5050 rxi_Send(call, p, istack);
5051 p->wirevec[i].iov_len = savelen;
5055 nbytes -= p->wirevec[i].iov_len;
5058 if (rx_stats_active)
5059 rx_AtomicIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5060 #ifndef RX_ENABLE_TSFPQ
5061 if (!optionalPacket)
5064 return optionalPacket; /* Return packet for re-use by caller */
5067 /* Send all of the packets in the list in single datagram */
5069 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5070 int istack, int moreFlag, struct clock *now,
5071 struct clock *retryTime, int resending)
5076 struct rx_connection *conn = call->conn;
5077 struct rx_peer *peer = conn->peer;
5079 MUTEX_ENTER(&peer->peer_lock);
5082 peer->reSends += len;
5083 if (rx_stats_active)
5084 rx_AtomicIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5085 MUTEX_EXIT(&peer->peer_lock);
5087 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5091 /* Set the packet flags and schedule the resend events */
5092 /* Only request an ack for the last packet in the list */
5093 for (i = 0; i < len; i++) {
5094 list[i]->retryTime = *retryTime;
5095 if (list[i]->header.serial) {
5096 /* Exponentially backoff retry times */
5097 if (list[i]->backoff < MAXBACKOFF) {
5098 /* so it can't stay == 0 */
5099 list[i]->backoff = (list[i]->backoff << 1) + 1;
5102 clock_Addmsec(&(list[i]->retryTime),
5103 ((afs_uint32) list[i]->backoff) << 8);
5106 /* Wait a little extra for the ack on the last packet */
5107 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5108 clock_Addmsec(&(list[i]->retryTime), 400);
5111 /* Record the time sent */
5112 list[i]->timeSent = *now;
5114 /* Ask for an ack on retransmitted packets, on every other packet
5115 * if the peer doesn't support slow start. Ask for an ack on every
5116 * packet until the congestion window reaches the ack rate. */
5117 if (list[i]->header.serial) {
5119 if (rx_stats_active)
5120 rx_AtomicIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5122 /* improved RTO calculation- not Karn */
5123 list[i]->firstSent = *now;
5124 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5125 || (!(call->flags & RX_CALL_SLOW_START_OK)
5126 && (list[i]->header.seq & 1)))) {
5131 MUTEX_ENTER(&peer->peer_lock);
5135 if (rx_stats_active)
5136 rx_AtomicIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5137 MUTEX_EXIT(&peer->peer_lock);
5139 /* Tag this packet as not being the last in this group,
5140 * for the receiver's benefit */
5141 if (i < len - 1 || moreFlag) {
5142 list[i]->header.flags |= RX_MORE_PACKETS;
5145 /* Install the new retransmit time for the packet, and
5146 * record the time sent */
5147 list[i]->timeSent = *now;
5151 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5154 /* Since we're about to send a data packet to the peer, it's
5155 * safe to nuke any scheduled end-of-packets ack */
5156 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5158 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5159 MUTEX_EXIT(&call->lock);
5161 rxi_SendPacketList(call, conn, list, len, istack);
5163 rxi_SendPacket(call, conn, list[0], istack);
5165 MUTEX_ENTER(&call->lock);
5166 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5168 /* Update last send time for this call (for keep-alive
5169 * processing), and for the connection (so that we can discover
5170 * idle connections) */
5171 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5174 /* When sending packets we need to follow these rules:
5175 * 1. Never send more than maxDgramPackets in a jumbogram.
5176 * 2. Never send a packet with more than two iovecs in a jumbogram.
5177 * 3. Never send a retransmitted packet in a jumbogram.
5178 * 4. Never send more than cwind/4 packets in a jumbogram
5179 * We always keep the last list we should have sent so we
5180 * can set the RX_MORE_PACKETS flags correctly.
5183 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5184 int istack, struct clock *now, struct clock *retryTime,
5187 int i, cnt, lastCnt = 0;
5188 struct rx_packet **listP, **lastP = 0;
5189 struct rx_peer *peer = call->conn->peer;
5190 int morePackets = 0;
5192 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5193 /* Does the current packet force us to flush the current list? */
5195 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5196 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5198 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5200 /* If the call enters an error state stop sending, or if
5201 * we entered congestion recovery mode, stop sending */
5202 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5210 /* Add the current packet to the list if it hasn't been acked.
5211 * Otherwise adjust the list pointer to skip the current packet. */
5212 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5214 /* Do we need to flush the list? */
5215 if (cnt >= (int)peer->maxDgramPackets
5216 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5217 || list[i]->header.serial
5218 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5220 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5221 retryTime, resending);
5222 /* If the call enters an error state stop sending, or if
5223 * we entered congestion recovery mode, stop sending */
5225 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5230 listP = &list[i + 1];
5235 osi_Panic("rxi_SendList error");
5237 listP = &list[i + 1];
5241 /* Send the whole list when the call is in receive mode, when
5242 * the call is in eof mode, when we are in fast recovery mode,
5243 * and when we have the last packet */
5244 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5245 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5246 || (call->flags & RX_CALL_FAST_RECOVER)) {
5247 /* Check for the case where the current list contains
5248 * an acked packet. Since we always send retransmissions
5249 * in a separate packet, we only need to check the first
5250 * packet in the list */
5251 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5255 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5256 retryTime, resending);
5257 /* If the call enters an error state stop sending, or if
5258 * we entered congestion recovery mode, stop sending */
5259 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5263 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5266 } else if (lastCnt > 0) {
5267 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5272 #ifdef RX_ENABLE_LOCKS
5273 /* Call rxi_Start, below, but with the call lock held. */
5275 rxi_StartUnlocked(struct rxevent *event,
5276 void *arg0, void *arg1, int istack)
5278 struct rx_call *call = arg0;
5280 MUTEX_ENTER(&call->lock);
5281 rxi_Start(event, call, arg1, istack);
5282 MUTEX_EXIT(&call->lock);
5284 #endif /* RX_ENABLE_LOCKS */
5286 /* This routine is called when new packets are readied for
5287 * transmission and when retransmission may be necessary, or when the
5288 * transmission window or burst count are favourable. This should be
5289 * better optimized for new packets, the usual case, now that we've
5290 * got rid of queues of send packets. XXXXXXXXXXX */
5292 rxi_Start(struct rxevent *event,
5293 void *arg0, void *arg1, int istack)
5295 struct rx_call *call = arg0;
5297 struct rx_packet *p;
5298 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5299 struct rx_peer *peer = call->conn->peer;
5300 struct clock now, usenow, retryTime;
5304 struct rx_packet **xmitList;
5307 /* If rxi_Start is being called as a result of a resend event,
5308 * then make sure that the event pointer is removed from the call
5309 * structure, since there is no longer a per-call retransmission
5311 if (event && event == call->resendEvent) {
5312 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5313 call->resendEvent = NULL;
5315 if (queue_IsEmpty(&call->tq)) {
5319 /* Timeouts trigger congestion recovery */
5320 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5321 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5322 /* someone else is waiting to start recovery */
5325 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5326 rxi_WaitforTQBusy(call);
5327 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5328 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5329 call->flags |= RX_CALL_FAST_RECOVER;
5330 if (peer->maxDgramPackets > 1) {
5331 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5333 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5335 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5336 call->nDgramPackets = 1;
5338 call->nextCwind = 1;
5341 MUTEX_ENTER(&peer->peer_lock);
5342 peer->MTU = call->MTU;
5343 peer->cwind = call->cwind;
5344 peer->nDgramPackets = 1;
5346 call->congestSeq = peer->congestSeq;
5347 MUTEX_EXIT(&peer->peer_lock);
5348 /* Clear retry times on packets. Otherwise, it's possible for
5349 * some packets in the queue to force resends at rates faster
5350 * than recovery rates.
5352 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5353 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5354 clock_Zero(&p->retryTime);
5359 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5360 if (rx_stats_active)
5361 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5366 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5367 /* Get clock to compute the re-transmit time for any packets
5368 * in this burst. Note, if we back off, it's reasonable to
5369 * back off all of the packets in the same manner, even if
5370 * some of them have been retransmitted more times than more
5372 * Do a dance to avoid blocking after setting now. */
5373 clock_Zero(&retryTime);
5374 MUTEX_ENTER(&peer->peer_lock);
5375 clock_Add(&retryTime, &peer->timeout);
5376 MUTEX_EXIT(&peer->peer_lock);
5377 clock_GetTime(&now);
5378 clock_Add(&retryTime, &now);
5380 /* Send (or resend) any packets that need it, subject to
5381 * window restrictions and congestion burst control
5382 * restrictions. Ask for an ack on the last packet sent in
5383 * this burst. For now, we're relying upon the window being
5384 * considerably bigger than the largest number of packets that
5385 * are typically sent at once by one initial call to
5386 * rxi_Start. This is probably bogus (perhaps we should ask
5387 * for an ack when we're half way through the current
5388 * window?). Also, for non file transfer applications, this
5389 * may end up asking for an ack for every packet. Bogus. XXXX
5392 * But check whether we're here recursively, and let the other guy
5395 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5396 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5397 call->flags |= RX_CALL_TQ_BUSY;
5399 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5401 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5402 call->flags &= ~RX_CALL_NEED_START;
5403 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5405 maxXmitPackets = MIN(call->twind, call->cwind);
5406 xmitList = (struct rx_packet **)
5407 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5408 /* XXXX else we must drop any mtx we hold */
5409 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5411 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5413 if (xmitList == NULL)
5414 osi_Panic("rxi_Start, failed to allocate xmit list");
5415 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5416 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5417 /* We shouldn't be sending packets if a thread is waiting
5418 * to initiate congestion recovery */
5422 && (call->flags & RX_CALL_FAST_RECOVER)) {
5423 /* Only send one packet during fast recovery */
5426 if ((p->flags & RX_PKTFLAG_FREE)
5427 || (!queue_IsEnd(&call->tq, nxp)
5428 && (nxp->flags & RX_PKTFLAG_FREE))
5429 || (p == (struct rx_packet *)&rx_freePacketQueue)
5430 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5431 osi_Panic("rxi_Start: xmit queue clobbered");
5433 if (p->flags & RX_PKTFLAG_ACKED) {
5434 /* Since we may block, don't trust this */
5435 usenow.sec = usenow.usec = 0;
5436 if (rx_stats_active)
5437 rx_AtomicIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5438 continue; /* Ignore this packet if it has been acknowledged */
5441 /* Turn off all flags except these ones, which are the same
5442 * on each transmission */
5443 p->header.flags &= RX_PRESET_FLAGS;
5445 if (p->header.seq >=
5446 call->tfirst + MIN((int)call->twind,
5447 (int)(call->nSoftAcked +
5449 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5450 /* Note: if we're waiting for more window space, we can
5451 * still send retransmits; hence we don't return here, but
5452 * break out to schedule a retransmit event */
5453 dpf(("call %d waiting for window",
5454 *(call->callNumber)));
5458 /* Transmit the packet if it needs to be sent. */
5459 if (!clock_Lt(&now, &p->retryTime)) {
5460 if (nXmitPackets == maxXmitPackets) {
5461 rxi_SendXmitList(call, xmitList, nXmitPackets,
5462 istack, &now, &retryTime,
5464 osi_Free(xmitList, maxXmitPackets *
5465 sizeof(struct rx_packet *));
5468 xmitList[nXmitPackets++] = p;
5472 /* xmitList now hold pointers to all of the packets that are
5473 * ready to send. Now we loop to send the packets */
5474 if (nXmitPackets > 0) {
5475 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5476 &now, &retryTime, resending);
5479 maxXmitPackets * sizeof(struct rx_packet *));
5481 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5483 * TQ references no longer protected by this flag; they must remain
5484 * protected by the global lock.
5486 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5487 call->flags &= ~RX_CALL_TQ_BUSY;
5488 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5489 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5490 #ifdef RX_ENABLE_LOCKS
5491 osirx_AssertMine(&call->lock, "rxi_Start start");
5492 CV_BROADCAST(&call->cv_tq);
5493 #else /* RX_ENABLE_LOCKS */
5494 osi_rxWakeup(&call->tq);
5495 #endif /* RX_ENABLE_LOCKS */
5500 /* We went into the error state while sending packets. Now is
5501 * the time to reset the call. This will also inform the using
5502 * process that the call is in an error state.
5504 if (rx_stats_active)
5505 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5506 call->flags &= ~RX_CALL_TQ_BUSY;
5507 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5508 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5509 #ifdef RX_ENABLE_LOCKS
5510 osirx_AssertMine(&call->lock, "rxi_Start middle");
5511 CV_BROADCAST(&call->cv_tq);
5512 #else /* RX_ENABLE_LOCKS */
5513 osi_rxWakeup(&call->tq);
5514 #endif /* RX_ENABLE_LOCKS */
5516 rxi_CallError(call, call->error);
5519 #ifdef RX_ENABLE_LOCKS
5520 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5522 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5523 /* Some packets have received acks. If they all have, we can clear
5524 * the transmit queue.
5527 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5528 if (p->header.seq < call->tfirst
5529 && (p->flags & RX_PKTFLAG_ACKED)) {
5531 p->flags &= ~RX_PKTFLAG_TQ;
5532 #ifdef RXDEBUG_PACKET
5540 call->flags |= RX_CALL_TQ_CLEARME;
5542 #endif /* RX_ENABLE_LOCKS */
5543 /* Don't bother doing retransmits if the TQ is cleared. */
5544 if (call->flags & RX_CALL_TQ_CLEARME) {
5545 rxi_ClearTransmitQueue(call, 1);
5547 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5550 /* Always post a resend event, if there is anything in the
5551 * queue, and resend is possible. There should be at least
5552 * one unacknowledged packet in the queue ... otherwise none
5553 * of these packets should be on the queue in the first place.
5555 if (call->resendEvent) {
5556 /* Cancel the existing event and post a new one */
5557 rxevent_Cancel(call->resendEvent, call,
5558 RX_CALL_REFCOUNT_RESEND);
5561 /* The retry time is the retry time on the first unacknowledged
5562 * packet inside the current window */
5564 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5565 /* Don't set timers for packets outside the window */
5566 if (p->header.seq >= call->tfirst + call->twind) {
5570 if (!(p->flags & RX_PKTFLAG_ACKED)
5571 && !clock_IsZero(&p->retryTime)) {
5573 retryTime = p->retryTime;
5578 /* Post a new event to re-run rxi_Start when retries may be needed */
5579 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5580 #ifdef RX_ENABLE_LOCKS
5581 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5583 rxevent_PostNow2(&retryTime, &usenow,
5585 (void *)call, 0, istack);
5586 #else /* RX_ENABLE_LOCKS */
5588 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5589 (void *)call, 0, istack);
5590 #endif /* RX_ENABLE_LOCKS */
5593 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5594 } while (call->flags & RX_CALL_NEED_START);
5596 * TQ references no longer protected by this flag; they must remain
5597 * protected by the global lock.
5599 call->flags &= ~RX_CALL_TQ_BUSY;
5600 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5601 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5602 #ifdef RX_ENABLE_LOCKS
5603 osirx_AssertMine(&call->lock, "rxi_Start end");
5604 CV_BROADCAST(&call->cv_tq);
5605 #else /* RX_ENABLE_LOCKS */
5606 osi_rxWakeup(&call->tq);
5607 #endif /* RX_ENABLE_LOCKS */
5610 call->flags |= RX_CALL_NEED_START;
5612 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5614 if (call->resendEvent) {
5615 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5620 /* Also adjusts the keep alive parameters for the call, to reflect
5621 * that we have just sent a packet (so keep alives aren't sent
5624 rxi_Send(struct rx_call *call, struct rx_packet *p,
5627 struct rx_connection *conn = call->conn;
5629 /* Stamp each packet with the user supplied status */
5630 p->header.userStatus = call->localStatus;
5632 /* Allow the security object controlling this call's security to
5633 * make any last-minute changes to the packet */
5634 RXS_SendPacket(conn->securityObject, call, p);
5636 /* Since we're about to send SOME sort of packet to the peer, it's
5637 * safe to nuke any scheduled end-of-packets ack */
5638 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5640 /* Actually send the packet, filling in more connection-specific fields */
5641 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5642 MUTEX_EXIT(&call->lock);
5643 rxi_SendPacket(call, conn, p, istack);
5644 MUTEX_ENTER(&call->lock);
5645 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5647 /* Update last send time for this call (for keep-alive
5648 * processing), and for the connection (so that we can discover
5649 * idle connections) */
5650 conn->lastSendTime = call->lastSendTime = clock_Sec();
5651 /* Don't count keepalives here, so idleness can be tracked. */
5652 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5653 call->lastSendData = call->lastSendTime;
5657 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5658 * that things are fine. Also called periodically to guarantee that nothing
5659 * falls through the cracks (e.g. (error + dally) connections have keepalive
5660 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5662 * haveCTLock Set if calling from rxi_ReapConnections
5664 #ifdef RX_ENABLE_LOCKS
5666 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5667 #else /* RX_ENABLE_LOCKS */
5669 rxi_CheckCall(struct rx_call *call)
5670 #endif /* RX_ENABLE_LOCKS */
5672 struct rx_connection *conn = call->conn;
5674 afs_uint32 deadTime;
5676 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5677 if (call->flags & RX_CALL_TQ_BUSY) {
5678 /* Call is active and will be reset by rxi_Start if it's
5679 * in an error state.
5684 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5686 (((afs_uint32) rx_ConnSecondsUntilDead(conn) << 10) +
5687 ((afs_uint32) conn->peer->rtt >> 3) +
5688 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5690 /* These are computed to the second (+- 1 second). But that's
5691 * good enough for these values, which should be a significant
5692 * number of seconds. */
5693 if (now > (call->lastReceiveTime + deadTime)) {
5694 if (call->state == RX_STATE_ACTIVE) {
5696 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5698 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5699 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5700 ip_stack_t *ipst = ns->netstack_ip;
5702 ire = ire_cache_lookup(call->conn->peer->host
5703 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5705 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5707 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5714 if (ire && ire->ire_max_frag > 0)
5715 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5716 #if defined(GLOBAL_NETSTACKID)
5720 #endif /* ADAPT_PMTU */
5721 rxi_CallError(call, RX_CALL_DEAD);
5724 #ifdef RX_ENABLE_LOCKS
5725 /* Cancel pending events */
5726 rxevent_Cancel(call->delayedAckEvent, call,
5727 RX_CALL_REFCOUNT_DELAY);
5728 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5729 rxevent_Cancel(call->keepAliveEvent, call,
5730 RX_CALL_REFCOUNT_ALIVE);
5731 if (call->refCount == 0) {
5732 rxi_FreeCall(call, haveCTLock);
5736 #else /* RX_ENABLE_LOCKS */
5739 #endif /* RX_ENABLE_LOCKS */
5741 /* Non-active calls are destroyed if they are not responding
5742 * to pings; active calls are simply flagged in error, so the
5743 * attached process can die reasonably gracefully. */
5745 /* see if we have a non-activity timeout */
5746 if (call->startWait && rx_ConnIdleDeadTime(conn)
5747 && ((call->startWait + rx_ConnIdleDeadTime(conn)) < now)) {
5748 if (call->state == RX_STATE_ACTIVE) {
5749 rxi_CallError(call, RX_CALL_TIMEOUT);
5753 if (call->lastSendData && rx_ConnIdleDeadTime(conn)
5754 && (rx_ConnIdleDeadErr(conn) != 0)
5755 && ((call->lastSendData + rx_ConnIdleDeadTime(conn)) < now)) {
5756 if (call->state == RX_STATE_ACTIVE) {
5757 rxi_CallError(call, conn->idleDeadErr);
5761 /* see if we have a hard timeout */
5762 if (rx_ConnHardDeadTime(conn)
5763 && (now > (rx_ConnHardDeadTime(conn) + call->startTime.sec))) {
5764 if (call->state == RX_STATE_ACTIVE)
5765 rxi_CallError(call, RX_CALL_TIMEOUT);
5772 /* When a call is in progress, this routine is called occasionally to
5773 * make sure that some traffic has arrived (or been sent to) the peer.
5774 * If nothing has arrived in a reasonable amount of time, the call is
5775 * declared dead; if nothing has been sent for a while, we send a
5776 * keep-alive packet (if we're actually trying to keep the call alive)
5779 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5781 struct rx_call *call = arg1;
5782 struct rx_connection *conn;
5785 MUTEX_ENTER(&call->lock);
5786 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5787 if (event == call->keepAliveEvent)
5788 call->keepAliveEvent = NULL;
5791 #ifdef RX_ENABLE_LOCKS
5792 if (rxi_CheckCall(call, 0)) {
5793 MUTEX_EXIT(&call->lock);
5796 #else /* RX_ENABLE_LOCKS */
5797 if (rxi_CheckCall(call))
5799 #endif /* RX_ENABLE_LOCKS */
5801 /* Don't try to keep alive dallying calls */
5802 if (call->state == RX_STATE_DALLY) {
5803 MUTEX_EXIT(&call->lock);
5808 if ((now - call->lastSendTime) > rx_ConnSecondsUntilPing(conn)) {
5809 /* Don't try to send keepalives if there is unacknowledged data */
5810 /* the rexmit code should be good enough, this little hack
5811 * doesn't quite work XXX */
5812 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5814 rxi_ScheduleKeepAliveEvent(call);
5815 MUTEX_EXIT(&call->lock);
5820 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
5822 if (!call->keepAliveEvent) {
5823 struct clock when, now;
5824 clock_GetTime(&now);
5826 when.sec += rx_ConnSecondsUntilPing(call->conn);
5827 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5828 call->keepAliveEvent =
5829 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5833 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5835 rxi_KeepAliveOn(struct rx_call *call)
5837 /* Pretend last packet received was received now--i.e. if another
5838 * packet isn't received within the keep alive time, then the call
5839 * will die; Initialize last send time to the current time--even
5840 * if a packet hasn't been sent yet. This will guarantee that a
5841 * keep-alive is sent within the ping time */
5842 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5843 rxi_ScheduleKeepAliveEvent(call);
5846 /* This routine is called to send connection abort messages
5847 * that have been delayed to throttle looping clients. */
5849 rxi_SendDelayedConnAbort(struct rxevent *event,
5850 void *arg1, void *unused)
5852 struct rx_connection *conn = arg1;
5855 struct rx_packet *packet;
5857 MUTEX_ENTER(&conn->conn_data_lock);
5858 conn->delayedAbortEvent = NULL;
5859 error = htonl(rx_ConnError(conn));
5861 MUTEX_EXIT(&conn->conn_data_lock);
5862 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5865 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5866 RX_PACKET_TYPE_ABORT, (char *)&error,
5868 rxi_FreePacket(packet);
5872 /* This routine is called to send call abort messages
5873 * that have been delayed to throttle looping clients. */
5875 rxi_SendDelayedCallAbort(struct rxevent *event,
5876 void *arg1, void *dummy)
5878 struct rx_call *call = arg1;
5881 struct rx_packet *packet;
5883 MUTEX_ENTER(&call->lock);
5884 call->delayedAbortEvent = NULL;
5885 error = htonl(call->error);
5887 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5890 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5891 (char *)&error, sizeof(error), 0);
5892 rxi_FreePacket(packet);
5894 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5895 MUTEX_EXIT(&call->lock);
5898 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5899 * seconds) to ask the client to authenticate itself. The routine
5900 * issues a challenge to the client, which is obtained from the
5901 * security object associated with the connection */
5903 rxi_ChallengeEvent(struct rxevent *event,
5904 void *arg0, void *arg1, int tries)
5906 struct rx_connection *conn = arg0;
5908 conn->challengeEvent = NULL;
5909 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5910 struct rx_packet *packet;
5911 struct clock when, now;
5914 /* We've failed to authenticate for too long.
5915 * Reset any calls waiting for authentication;
5916 * they are all in RX_STATE_PRECALL.
5920 MUTEX_ENTER(&conn->conn_call_lock);
5921 for (i = 0; i < RX_MAXCALLS; i++) {
5922 struct rx_call *call = conn->call[i];
5924 MUTEX_ENTER(&call->lock);
5925 if (call->state == RX_STATE_PRECALL) {
5926 rxi_CallError(call, RX_CALL_DEAD);
5927 rxi_SendCallAbort(call, NULL, 0, 0);
5929 MUTEX_EXIT(&call->lock);
5932 MUTEX_EXIT(&conn->conn_call_lock);
5936 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5938 /* If there's no packet available, do this later. */
5939 RXS_GetChallenge(conn->securityObject, conn, packet);
5940 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5941 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5942 rxi_FreePacket(packet);
5944 clock_GetTime(&now);
5946 when.sec += RX_CHALLENGE_TIMEOUT;
5947 conn->challengeEvent =
5948 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5953 /* Call this routine to start requesting the client to authenticate
5954 * itself. This will continue until authentication is established,
5955 * the call times out, or an invalid response is returned. The
5956 * security object associated with the connection is asked to create
5957 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5958 * defined earlier. */
5960 rxi_ChallengeOn(struct rx_connection *conn)
5962 if (!conn->challengeEvent) {
5963 RXS_CreateChallenge(conn->securityObject, conn);
5964 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5969 /* Compute round trip time of the packet provided, in *rttp.
5972 /* rxi_ComputeRoundTripTime is called with peer locked. */
5973 /* sentp and/or peer may be null */
5975 rxi_ComputeRoundTripTime(struct rx_packet *p,
5976 struct clock *sentp,
5977 struct rx_peer *peer)
5979 struct clock thisRtt, *rttp = &thisRtt;
5983 clock_GetTime(rttp);
5985 if (clock_Lt(rttp, sentp)) {
5987 return; /* somebody set the clock back, don't count this time. */
5989 clock_Sub(rttp, sentp);
5990 if (rx_stats_active) {
5991 MUTEX_ENTER(&rx_stats_mutex);
5992 if (clock_Lt(rttp, &rx_stats.minRtt))
5993 rx_stats.minRtt = *rttp;
5994 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5995 if (rttp->sec > 60) {
5996 MUTEX_EXIT(&rx_stats_mutex);
5997 return; /* somebody set the clock ahead */
5999 rx_stats.maxRtt = *rttp;
6001 clock_Add(&rx_stats.totalRtt, rttp);
6002 rx_AtomicIncrement_NL(rx_stats.nRttSamples);
6003 MUTEX_EXIT(&rx_stats_mutex);
6006 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6008 /* Apply VanJacobson round-trip estimations */
6013 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6014 * srtt is stored as fixed point with 3 bits after the binary
6015 * point (i.e., scaled by 8). The following magic is
6016 * equivalent to the smoothing algorithm in rfc793 with an
6017 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6018 * srtt*8 = srtt*8 + rtt - srtt
6019 * srtt = srtt + rtt/8 - srtt/8
6022 delta = MSEC(rttp) - (peer->rtt >> 3);
6026 * We accumulate a smoothed rtt variance (actually, a smoothed
6027 * mean difference), then set the retransmit timer to smoothed
6028 * rtt + 4 times the smoothed variance (was 2x in van's original
6029 * paper, but 4x works better for me, and apparently for him as
6031 * rttvar is stored as
6032 * fixed point with 2 bits after the binary point (scaled by
6033 * 4). The following is equivalent to rfc793 smoothing with
6034 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
6035 * replaces rfc793's wired-in beta.
6036 * dev*4 = dev*4 + (|actual - expected| - dev)
6042 delta -= (peer->rtt_dev >> 2);
6043 peer->rtt_dev += delta;
6045 /* I don't have a stored RTT so I start with this value. Since I'm
6046 * probably just starting a call, and will be pushing more data down
6047 * this, I expect congestion to increase rapidly. So I fudge a
6048 * little, and I set deviance to half the rtt. In practice,
6049 * deviance tends to approach something a little less than
6050 * half the smoothed rtt. */
6051 peer->rtt = (MSEC(rttp) << 3) + 8;
6052 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6054 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
6055 * the other of these connections is usually in a user process, and can
6056 * be switched and/or swapped out. So on fast, reliable networks, the
6057 * timeout would otherwise be too short.
6059 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
6060 clock_Zero(&(peer->timeout));
6061 clock_Addmsec(&(peer->timeout), rtt_timeout);
6063 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)));
6067 /* Find all server connections that have not been active for a long time, and
6070 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6072 struct clock now, when;
6073 clock_GetTime(&now);
6075 /* Find server connection structures that haven't been used for
6076 * greater than rx_idleConnectionTime */
6078 struct rx_connection **conn_ptr, **conn_end;
6079 int i, havecalls = 0;
6080 MUTEX_ENTER(&rx_connHashTable_lock);
6081 for (conn_ptr = &rx_connHashTable[0], conn_end =
6082 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6084 struct rx_connection *conn, *next;
6085 struct rx_call *call;
6089 for (conn = *conn_ptr; conn; conn = next) {
6090 /* XXX -- Shouldn't the connection be locked? */
6093 for (i = 0; i < RX_MAXCALLS; i++) {
6094 call = conn->call[i];
6098 code = MUTEX_TRYENTER(&call->lock);
6101 #ifdef RX_ENABLE_LOCKS
6102 result = rxi_CheckCall(call, 1);
6103 #else /* RX_ENABLE_LOCKS */
6104 result = rxi_CheckCall(call);
6105 #endif /* RX_ENABLE_LOCKS */
6106 MUTEX_EXIT(&call->lock);
6108 /* If CheckCall freed the call, it might
6109 * have destroyed the connection as well,
6110 * which screws up the linked lists.
6116 if (conn->type == RX_SERVER_CONNECTION) {
6117 /* This only actually destroys the connection if
6118 * there are no outstanding calls */
6119 MUTEX_ENTER(&conn->conn_data_lock);
6120 if (!havecalls && (rx_AtomicPeek_NL(conn->refCount) == 0)
6121 && ((conn->lastSendTime + rx_idleConnectionTime) <
6123 rx_AtomicIncrement_NL(conn->refCount); /* it will be decr in rx_DestroyConn */
6124 MUTEX_EXIT(&conn->conn_data_lock);
6125 #ifdef RX_ENABLE_LOCKS
6126 rxi_DestroyConnectionNoLock(conn);
6127 #else /* RX_ENABLE_LOCKS */
6128 rxi_DestroyConnection(conn);
6129 #endif /* RX_ENABLE_LOCKS */
6131 #ifdef RX_ENABLE_LOCKS
6133 MUTEX_EXIT(&conn->conn_data_lock);
6135 #endif /* RX_ENABLE_LOCKS */
6139 #ifdef RX_ENABLE_LOCKS
6140 while (rx_connCleanup_list) {
6141 struct rx_connection *conn;
6142 conn = rx_connCleanup_list;
6143 rx_connCleanup_list = rx_connCleanup_list->next;
6144 MUTEX_EXIT(&rx_connHashTable_lock);
6145 rxi_CleanupConnection(conn);
6146 MUTEX_ENTER(&rx_connHashTable_lock);
6148 MUTEX_EXIT(&rx_connHashTable_lock);
6149 #endif /* RX_ENABLE_LOCKS */
6152 /* Find any peer structures that haven't been used (haven't had an
6153 * associated connection) for greater than rx_idlePeerTime */
6155 struct rx_peer **peer_ptr, **peer_end;
6157 MUTEX_ENTER(&rx_rpc_stats);
6158 MUTEX_ENTER(&rx_peerHashTable_lock);
6159 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6160 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6162 struct rx_peer *peer, *next, *prev;
6163 for (prev = peer = *peer_ptr; peer; peer = next) {
6165 code = MUTEX_TRYENTER(&peer->peer_lock);
6166 if ((code) && (rx_AtomicPeek_NL(peer->refCount) == 0)
6167 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6168 rx_interface_stat_p rpc_stat, nrpc_stat;
6170 MUTEX_EXIT(&peer->peer_lock);
6171 MUTEX_DESTROY(&peer->peer_lock);
6173 (&peer->rpcStats, rpc_stat, nrpc_stat,
6174 rx_interface_stat)) {
6175 unsigned int num_funcs;
6178 queue_Remove(&rpc_stat->queue_header);
6179 queue_Remove(&rpc_stat->all_peers);
6180 num_funcs = rpc_stat->stats[0].func_total;
6182 sizeof(rx_interface_stat_t) +
6183 rpc_stat->stats[0].func_total *
6184 sizeof(rx_function_entry_v1_t);
6186 rxi_Free(rpc_stat, space);
6187 rxi_rpc_peer_stat_cnt -= num_funcs;
6190 if (rx_stats_active)
6191 rx_AtomicDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6192 if (peer == *peer_ptr) {
6199 MUTEX_EXIT(&peer->peer_lock);
6205 MUTEX_EXIT(&rx_peerHashTable_lock);
6206 MUTEX_EXIT(&rx_rpc_stats);
6209 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6210 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6211 * GC, just below. Really, we shouldn't have to keep moving packets from
6212 * one place to another, but instead ought to always know if we can
6213 * afford to hold onto a packet in its particular use. */
6214 MUTEX_ENTER(&rx_freePktQ_lock);
6215 if (rx_waitingForPackets) {
6216 rx_waitingForPackets = 0;
6217 #ifdef RX_ENABLE_LOCKS
6218 CV_BROADCAST(&rx_waitingForPackets_cv);
6220 osi_rxWakeup(&rx_waitingForPackets);
6223 MUTEX_EXIT(&rx_freePktQ_lock);
6226 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6227 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6231 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6232 * rx.h is sort of strange this is better. This is called with a security
6233 * object before it is discarded. Each connection using a security object has
6234 * its own refcount to the object so it won't actually be freed until the last
6235 * connection is destroyed.
6237 * This is the only rxs module call. A hold could also be written but no one
6241 rxs_Release(struct rx_securityClass *aobj)
6243 return RXS_Close(aobj);
6247 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6248 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6249 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6250 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6252 /* Adjust our estimate of the transmission rate to this peer, given
6253 * that the packet p was just acked. We can adjust peer->timeout and
6254 * call->twind. Pragmatically, this is called
6255 * only with packets of maximal length.
6256 * Called with peer and call locked.
6260 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6261 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6263 afs_int32 xferSize, xferMs;
6267 /* Count down packets */
6268 if (peer->rateFlag > 0)
6270 /* Do nothing until we're enabled */
6271 if (peer->rateFlag != 0)
6276 /* Count only when the ack seems legitimate */
6277 switch (ackReason) {
6278 case RX_ACK_REQUESTED:
6280 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6284 case RX_ACK_PING_RESPONSE:
6285 if (p) /* want the response to ping-request, not data send */
6287 clock_GetTime(&newTO);
6288 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6289 clock_Sub(&newTO, &call->pingRequestTime);
6290 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6294 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6301 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));
6303 /* Track only packets that are big enough. */
6304 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6308 /* absorb RTT data (in milliseconds) for these big packets */
6309 if (peer->smRtt == 0) {
6310 peer->smRtt = xferMs;
6312 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6317 if (peer->countDown) {
6321 peer->countDown = 10; /* recalculate only every so often */
6323 /* In practice, we can measure only the RTT for full packets,
6324 * because of the way Rx acks the data that it receives. (If it's
6325 * smaller than a full packet, it often gets implicitly acked
6326 * either by the call response (from a server) or by the next call
6327 * (from a client), and either case confuses transmission times
6328 * with processing times.) Therefore, replace the above
6329 * more-sophisticated processing with a simpler version, where the
6330 * smoothed RTT is kept for full-size packets, and the time to
6331 * transmit a windowful of full-size packets is simply RTT *
6332 * windowSize. Again, we take two steps:
6333 - ensure the timeout is large enough for a single packet's RTT;
6334 - ensure that the window is small enough to fit in the desired timeout.*/
6336 /* First, the timeout check. */
6337 minTime = peer->smRtt;
6338 /* Get a reasonable estimate for a timeout period */
6340 newTO.sec = minTime / 1000;
6341 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6343 /* Increase the timeout period so that we can always do at least
6344 * one packet exchange */
6345 if (clock_Gt(&newTO, &peer->timeout)) {
6347 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));
6349 peer->timeout = newTO;
6352 /* Now, get an estimate for the transmit window size. */
6353 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6354 /* Now, convert to the number of full packets that could fit in a
6355 * reasonable fraction of that interval */
6356 minTime /= (peer->smRtt << 1);
6357 xferSize = minTime; /* (make a copy) */
6359 /* Now clamp the size to reasonable bounds. */
6362 else if (minTime > rx_Window)
6363 minTime = rx_Window;
6364 /* if (minTime != peer->maxWindow) {
6365 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6366 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6367 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6369 peer->maxWindow = minTime;
6370 elide... call->twind = minTime;
6374 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6375 * Discern this by calculating the timeout necessary for rx_Window
6377 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6378 /* calculate estimate for transmission interval in milliseconds */
6379 minTime = rx_Window * peer->smRtt;
6380 if (minTime < 1000) {
6381 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
6382 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6383 peer->timeout.usec, peer->smRtt, peer->packetSize));
6385 newTO.sec = 0; /* cut back on timeout by half a second */
6386 newTO.usec = 500000;
6387 clock_Sub(&peer->timeout, &newTO);
6392 } /* end of rxi_ComputeRate */
6393 #endif /* ADAPT_WINDOW */
6401 #define TRACE_OPTION_RX_DEBUG 16
6409 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6410 0, KEY_QUERY_VALUE, &parmKey);
6411 if (code != ERROR_SUCCESS)
6414 dummyLen = sizeof(TraceOption);
6415 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6416 (BYTE *) &TraceOption, &dummyLen);
6417 if (code == ERROR_SUCCESS) {
6418 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6420 RegCloseKey (parmKey);
6421 #endif /* AFS_NT40_ENV */
6426 rx_DebugOnOff(int on)
6430 rxdebug_active = on;
6436 rx_StatsOnOff(int on)
6439 rx_stats_active = on;
6444 /* Don't call this debugging routine directly; use dpf */
6446 rxi_DebugPrint(char *format, ...)
6455 va_start(ap, format);
6457 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6460 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6462 if (msg[len-1] != '\n') {
6466 OutputDebugString(msg);
6473 va_start(ap, format);
6475 clock_GetTime(&now);
6476 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
6477 (unsigned int)now.usec / 1000);
6478 vfprintf(rx_Log, format, ap);
6487 * This function is used to process the rx_stats structure that is local
6488 * to a process as well as an rx_stats structure received from a remote
6489 * process (via rxdebug). Therefore, it needs to do minimal version
6493 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6494 afs_int32 freePackets, char version)
6499 if (size != sizeof(struct rx_statistics)) {
6501 "Unexpected size of stats structure: was %d, expected %lud\n",
6502 size, sizeof(struct rx_statistics));
6505 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6506 rx_AtomicPeek_NL(s->packetRequests));
6508 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6509 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
6510 rx_AtomicPeek_NL(s->receivePktAllocFailures),
6511 rx_AtomicPeek_NL(s->receiveCbufPktAllocFailures),
6512 rx_AtomicPeek_NL(s->sendPktAllocFailures),
6513 rx_AtomicPeek_NL(s->sendCbufPktAllocFailures),
6514 rx_AtomicPeek_NL(s->specialPktAllocFailures));
6516 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
6517 rx_AtomicPeek_NL(s->receivePktAllocFailures),
6518 rx_AtomicPeek_NL(s->sendPktAllocFailures),
6519 rx_AtomicPeek_NL(s->specialPktAllocFailures));
6523 " greedy %d, " "bogusReads %d (last from host %x), "
6524 "noPackets %d, " "noBuffers %d, " "selects %d, "
6526 rx_AtomicPeek_NL(s->socketGreedy),
6527 rx_AtomicPeek_NL(s->bogusPacketOnRead),
6528 rx_AtomicPeek_NL(s->bogusHost),
6529 rx_AtomicPeek_NL(s->noPacketOnRead),
6530 rx_AtomicPeek_NL(s->noPacketBuffersOnRead),
6531 rx_AtomicPeek_NL(s->selects),
6532 rx_AtomicPeek_NL(s->sendSelects));
6534 fprintf(file, " packets read: ");
6535 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6536 fprintf(file, "%s %d ", rx_packetTypes[i], rx_AtomicPeek_NL(s->packetsRead[i]));
6538 fprintf(file, "\n");
6541 " other read counters: data %d, " "ack %d, " "dup %d "
6542 "spurious %d " "dally %d\n", rx_AtomicPeek_NL(s->dataPacketsRead),
6543 rx_AtomicPeek_NL(s->ackPacketsRead),
6544 rx_AtomicPeek_NL(s->dupPacketsRead),
6545 rx_AtomicPeek_NL(s->spuriousPacketsRead),
6546 rx_AtomicPeek_NL(s->ignorePacketDally));
6548 fprintf(file, " packets sent: ");
6549 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6550 fprintf(file, "%s %d ", rx_packetTypes[i], rx_AtomicPeek_NL(s->packetsSent[i]));
6552 fprintf(file, "\n");
6555 " other send counters: ack %d, " "data %d (not resends), "
6556 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6557 rx_AtomicPeek_NL(s->ackPacketsSent),
6558 rx_AtomicPeek_NL(s->dataPacketsSent),
6559 rx_AtomicPeek_NL(s->dataPacketsReSent),
6560 rx_AtomicPeek_NL(s->dataPacketsPushed),
6561 rx_AtomicPeek_NL(s->ignoreAckedPacket));
6564 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6565 rx_AtomicPeek_NL(s->netSendFailures), rx_AtomicPeek_NL(s->fatalErrors));
6567 if (rx_AtomicPeek_NL(s->nRttSamples)) {
6568 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6569 clock_Float(&s->totalRtt) / rx_AtomicPeek_NL(s->nRttSamples), rx_AtomicPeek_NL(s->nRttSamples));
6571 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6572 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6576 " %d server connections, " "%d client connections, "
6577 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6578 rx_AtomicPeek_NL(s->nServerConns),
6579 rx_AtomicPeek_NL(s->nClientConns),
6580 rx_AtomicPeek_NL(s->nPeerStructs),
6581 rx_AtomicPeek_NL(s->nCallStructs),
6582 rx_AtomicPeek_NL(s->nFreeCallStructs));
6584 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6585 fprintf(file, " %d clock updates\n", clock_nUpdates);
6588 fprintf(file, "ERROR: compiled without RXDEBUG\n");
6592 /* for backward compatibility */
6594 rx_PrintStats(FILE * file)
6596 MUTEX_ENTER(&rx_stats_mutex);
6597 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6599 MUTEX_EXIT(&rx_stats_mutex);
6603 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6605 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6606 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6607 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6610 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6611 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6612 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6615 " Packet size %d, " "max in packet skew %d, "
6616 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6617 (int)peer->outPacketSkew);
6621 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
6623 * This mutex protects the following static variables:
6627 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
6628 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
6630 #define LOCK_RX_DEBUG
6631 #define UNLOCK_RX_DEBUG
6632 #endif /* AFS_PTHREAD_ENV */
6636 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6637 u_char type, void *inputData, size_t inputLength,
6638 void *outputData, size_t outputLength)
6640 static afs_int32 counter = 100;
6641 time_t waitTime, waitCount, startTime;
6642 struct rx_header theader;
6645 struct timeval tv_now, tv_wake, tv_delta;
6646 struct sockaddr_in taddr, faddr;
6655 startTime = time(0);
6661 tp = &tbuffer[sizeof(struct rx_header)];
6662 taddr.sin_family = AF_INET;
6663 taddr.sin_port = remotePort;
6664 taddr.sin_addr.s_addr = remoteAddr;
6665 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6666 taddr.sin_len = sizeof(struct sockaddr_in);
6669 memset(&theader, 0, sizeof(theader));
6670 theader.epoch = htonl(999);
6672 theader.callNumber = htonl(counter);
6675 theader.type = type;
6676 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6677 theader.serviceId = 0;
6679 memcpy(tbuffer, &theader, sizeof(theader));
6680 memcpy(tp, inputData, inputLength);
6682 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6683 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6685 /* see if there's a packet available */
6686 gettimeofday(&tv_wake,0);
6687 tv_wake.tv_sec += waitTime;
6690 FD_SET(socket, &imask);
6691 tv_delta.tv_sec = tv_wake.tv_sec;
6692 tv_delta.tv_usec = tv_wake.tv_usec;
6693 gettimeofday(&tv_now, 0);
6695 if (tv_delta.tv_usec < tv_now.tv_usec) {
6697 tv_delta.tv_usec += 1000000;
6700 tv_delta.tv_usec -= tv_now.tv_usec;
6702 if (tv_delta.tv_sec < tv_now.tv_sec) {
6706 tv_delta.tv_sec -= tv_now.tv_sec;
6708 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6709 if (code == 1 && FD_ISSET(socket, &imask)) {
6710 /* now receive a packet */
6711 faddrLen = sizeof(struct sockaddr_in);
6713 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6714 (struct sockaddr *)&faddr, &faddrLen);
6717 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6718 if (counter == ntohl(theader.callNumber))
6726 /* see if we've timed out */
6734 code -= sizeof(struct rx_header);
6735 if (code > outputLength)
6736 code = outputLength;
6737 memcpy(outputData, tp, code);
6740 #endif /* RXDEBUG */
6743 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6744 afs_uint16 remotePort, struct rx_debugStats * stat,
6745 afs_uint32 * supportedValues)
6751 struct rx_debugIn in;
6753 *supportedValues = 0;
6754 in.type = htonl(RX_DEBUGI_GETSTATS);
6757 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6758 &in, sizeof(in), stat, sizeof(*stat));
6761 * If the call was successful, fixup the version and indicate
6762 * what contents of the stat structure are valid.
6763 * Also do net to host conversion of fields here.
6767 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6768 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6770 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6771 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6773 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6774 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6776 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6777 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6779 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6780 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6782 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6783 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6785 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6786 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6788 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6789 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6791 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6792 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6794 stat->nFreePackets = ntohl(stat->nFreePackets);
6795 stat->packetReclaims = ntohl(stat->packetReclaims);
6796 stat->callsExecuted = ntohl(stat->callsExecuted);
6797 stat->nWaiting = ntohl(stat->nWaiting);
6798 stat->idleThreads = ntohl(stat->idleThreads);
6799 stat->nWaited = ntohl(stat->nWaited);
6800 stat->nPackets = ntohl(stat->nPackets);
6807 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6808 afs_uint16 remotePort, struct rx_statistics * stat,
6809 afs_uint32 * supportedValues)
6815 struct rx_debugIn in;
6817 afs_int32 *lp = (afs_int32 *) stat;
6820 * supportedValues is currently unused, but added to allow future
6821 * versioning of this function.
6824 *supportedValues = 0;
6825 in.type = htonl(RX_DEBUGI_RXSTATS);
6827 memset(stat, 0, sizeof(*stat));
6829 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6830 &in, sizeof(in), stat, sizeof(*stat));
6835 * Do net to host conversion here
6838 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6847 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6848 afs_uint16 remotePort, size_t version_length,
6853 return MakeDebugCall(socket, remoteAddr, remotePort,
6854 RX_PACKET_TYPE_VERSION, a, 1, version,
6862 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6863 afs_uint16 remotePort, afs_int32 * nextConnection,
6864 int allConnections, afs_uint32 debugSupportedValues,
6865 struct rx_debugConn * conn,
6866 afs_uint32 * supportedValues)
6872 struct rx_debugIn in;
6876 * supportedValues is currently unused, but added to allow future
6877 * versioning of this function.
6880 *supportedValues = 0;
6881 if (allConnections) {
6882 in.type = htonl(RX_DEBUGI_GETALLCONN);
6884 in.type = htonl(RX_DEBUGI_GETCONN);
6886 in.index = htonl(*nextConnection);
6887 memset(conn, 0, sizeof(*conn));
6889 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6890 &in, sizeof(in), conn, sizeof(*conn));
6893 *nextConnection += 1;
6896 * Convert old connection format to new structure.
6899 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6900 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6901 #define MOVEvL(a) (conn->a = vL->a)
6903 /* any old or unrecognized version... */
6904 for (i = 0; i < RX_MAXCALLS; i++) {
6905 MOVEvL(callState[i]);
6906 MOVEvL(callMode[i]);
6907 MOVEvL(callFlags[i]);
6908 MOVEvL(callOther[i]);
6910 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6911 MOVEvL(secStats.type);
6912 MOVEvL(secStats.level);
6913 MOVEvL(secStats.flags);
6914 MOVEvL(secStats.expires);
6915 MOVEvL(secStats.packetsReceived);
6916 MOVEvL(secStats.packetsSent);
6917 MOVEvL(secStats.bytesReceived);
6918 MOVEvL(secStats.bytesSent);
6923 * Do net to host conversion here
6925 * I don't convert host or port since we are most likely
6926 * going to want these in NBO.
6928 conn->cid = ntohl(conn->cid);
6929 conn->serial = ntohl(conn->serial);
6930 for (i = 0; i < RX_MAXCALLS; i++) {
6931 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6933 rx_SetConnError(conn, ntohl(rx_ConnError(conn)));
6934 conn->secStats.flags = ntohl(conn->secStats.flags);
6935 conn->secStats.expires = ntohl(conn->secStats.expires);
6936 conn->secStats.packetsReceived =
6937 ntohl(conn->secStats.packetsReceived);
6938 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6939 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6940 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6941 conn->epoch = ntohl(conn->epoch);
6942 conn->natMTU = ntohl(conn->natMTU);
6949 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6950 afs_uint16 remotePort, afs_int32 * nextPeer,
6951 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6952 afs_uint32 * supportedValues)
6958 struct rx_debugIn in;
6961 * supportedValues is currently unused, but added to allow future
6962 * versioning of this function.
6965 *supportedValues = 0;
6966 in.type = htonl(RX_DEBUGI_GETPEER);
6967 in.index = htonl(*nextPeer);
6968 memset(peer, 0, sizeof(*peer));
6970 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6971 &in, sizeof(in), peer, sizeof(*peer));
6977 * Do net to host conversion here
6979 * I don't convert host or port since we are most likely
6980 * going to want these in NBO.
6982 peer->ifMTU = ntohs(peer->ifMTU);
6983 peer->idleWhen = ntohl(peer->idleWhen);
6984 peer->refCount = ntohs(peer->refCount);
6985 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6986 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6987 peer->rtt = ntohl(peer->rtt);
6988 peer->rtt_dev = ntohl(peer->rtt_dev);
6989 peer->timeout.sec = ntohl(peer->timeout.sec);
6990 peer->timeout.usec = ntohl(peer->timeout.usec);
6991 peer->nSent = ntohl(peer->nSent);
6992 peer->reSends = ntohl(peer->reSends);
6993 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6994 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6995 peer->rateFlag = ntohl(peer->rateFlag);
6996 peer->natMTU = ntohs(peer->natMTU);
6997 peer->maxMTU = ntohs(peer->maxMTU);
6998 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6999 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7000 peer->MTU = ntohs(peer->MTU);
7001 peer->cwind = ntohs(peer->cwind);
7002 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7003 peer->congestSeq = ntohs(peer->congestSeq);
7004 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7005 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7006 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7007 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7016 struct rx_serverQueueEntry *np;
7019 struct rx_call *call;
7020 struct rx_serverQueueEntry *sq;
7024 if (rxinit_status == 1) {
7026 return; /* Already shutdown. */
7030 #ifndef AFS_PTHREAD_ENV
7031 FD_ZERO(&rx_selectMask);
7032 #endif /* AFS_PTHREAD_ENV */
7033 rxi_dataQuota = RX_MAX_QUOTA;
7034 #ifndef AFS_PTHREAD_ENV
7036 #endif /* AFS_PTHREAD_ENV */
7039 #ifndef AFS_PTHREAD_ENV
7040 #ifndef AFS_USE_GETTIMEOFDAY
7042 #endif /* AFS_USE_GETTIMEOFDAY */
7043 #endif /* AFS_PTHREAD_ENV */
7045 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7046 call = queue_First(&rx_freeCallQueue, rx_call);
7048 rxi_Free(call, sizeof(struct rx_call));
7051 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7052 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7058 struct rx_peer **peer_ptr, **peer_end;
7059 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7060 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7062 struct rx_peer *peer, *next;
7063 for (peer = *peer_ptr; peer; peer = next) {
7064 rx_interface_stat_p rpc_stat, nrpc_stat;
7067 (&peer->rpcStats, rpc_stat, nrpc_stat,
7068 rx_interface_stat)) {
7069 unsigned int num_funcs;
7072 queue_Remove(&rpc_stat->queue_header);
7073 queue_Remove(&rpc_stat->all_peers);
7074 num_funcs = rpc_stat->stats[0].func_total;
7076 sizeof(rx_interface_stat_t) +
7077 rpc_stat->stats[0].func_total *
7078 sizeof(rx_function_entry_v1_t);
7080 rxi_Free(rpc_stat, space);
7081 rx_MutexAdd(rxi_rpc_peer_stat_cnt, -num_funcs, rx_rpc_stats);
7085 if (rx_stats_active)
7086 rx_AtomicDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7090 for (i = 0; i < RX_MAX_SERVICES; i++) {
7092 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7094 for (i = 0; i < rx_hashTableSize; i++) {
7095 struct rx_connection *tc, *ntc;
7096 MUTEX_ENTER(&rx_connHashTable_lock);
7097 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7099 for (j = 0; j < RX_MAXCALLS; j++) {
7101 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7104 rxi_Free(tc, sizeof(*tc));
7106 MUTEX_EXIT(&rx_connHashTable_lock);
7109 MUTEX_ENTER(&freeSQEList_lock);
7111 while ((np = rx_FreeSQEList)) {
7112 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7113 MUTEX_DESTROY(&np->lock);
7114 rxi_Free(np, sizeof(*np));
7117 MUTEX_EXIT(&freeSQEList_lock);
7118 MUTEX_DESTROY(&freeSQEList_lock);
7119 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7120 MUTEX_DESTROY(&rx_connHashTable_lock);
7121 MUTEX_DESTROY(&rx_peerHashTable_lock);
7122 MUTEX_DESTROY(&rx_serverPool_lock);
7124 osi_Free(rx_connHashTable,
7125 rx_hashTableSize * sizeof(struct rx_connection *));
7126 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7128 UNPIN(rx_connHashTable,
7129 rx_hashTableSize * sizeof(struct rx_connection *));
7130 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7132 rxi_FreeAllPackets();
7134 MUTEX_ENTER(&rx_quota_mutex);
7135 rxi_dataQuota = RX_MAX_QUOTA;
7136 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7137 MUTEX_EXIT(&rx_quota_mutex);
7142 #ifdef RX_ENABLE_LOCKS
7144 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7146 if (!MUTEX_ISMINE(lockaddr))
7147 osi_Panic("Lock not held: %s", msg);
7149 #endif /* RX_ENABLE_LOCKS */
7154 * Routines to implement connection specific data.
7158 rx_KeyCreate(rx_destructor_t rtn)
7161 MUTEX_ENTER(&rxi_keyCreate_lock);
7162 key = rxi_keyCreate_counter++;
7163 rxi_keyCreate_destructor = (rx_destructor_t *)
7164 realloc((void *)rxi_keyCreate_destructor,
7165 (key + 1) * sizeof(rx_destructor_t));
7166 rxi_keyCreate_destructor[key] = rtn;
7167 MUTEX_EXIT(&rxi_keyCreate_lock);
7172 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7175 struct rx_connection *tconn =
7176 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7178 MUTEX_ENTER(&tconn->conn_data_lock);
7179 if (!tconn->specific) {
7180 tconn->specific = (void **)malloc((key + 1) * sizeof(void *));
7181 for (i = 0; i < key; i++)
7182 tconn->specific[i] = NULL;
7183 tconn->nSpecific = key + 1;
7184 tconn->specific[key] = ptr;
7185 } else if (key >= tconn->nSpecific) {
7186 tconn->specific = (void **)
7187 realloc(tconn->specific, (key + 1) * sizeof(void *));
7188 for (i = tconn->nSpecific; i < key; i++)
7189 tconn->specific[i] = NULL;
7190 tconn->nSpecific = key + 1;
7191 tconn->specific[key] = ptr;
7193 if (tconn->specific[key] && rxi_keyCreate_destructor[key])
7194 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7195 tconn->specific[key] = ptr;
7197 MUTEX_EXIT(&tconn->conn_data_lock);
7201 rx_GetSpecific(struct rx_connection *conn, int key)
7204 struct rx_connection *tconn =
7205 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7207 MUTEX_ENTER(&tconn->conn_data_lock);
7208 if (key >= tconn->nSpecific)
7211 ptr = tconn->specific[key];
7212 MUTEX_EXIT(&tconn->conn_data_lock);
7216 #endif /* !KERNEL */
7219 * processStats is a queue used to store the statistics for the local
7220 * process. Its contents are similar to the contents of the rpcStats
7221 * queue on a rx_peer structure, but the actual data stored within
7222 * this queue contains totals across the lifetime of the process (assuming
7223 * the stats have not been reset) - unlike the per peer structures
7224 * which can come and go based upon the peer lifetime.
7227 static struct rx_queue processStats = { &processStats, &processStats };
7230 * peerStats is a queue used to store the statistics for all peer structs.
7231 * Its contents are the union of all the peer rpcStats queues.
7234 static struct rx_queue peerStats = { &peerStats, &peerStats };
7237 * rxi_monitor_processStats is used to turn process wide stat collection
7241 static int rxi_monitor_processStats = 0;
7244 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7247 static int rxi_monitor_peerStats = 0;
7250 * rxi_AddRpcStat - given all of the information for a particular rpc
7251 * call, create (if needed) and update the stat totals for the rpc.
7255 * IN stats - the queue of stats that will be updated with the new value
7257 * IN rxInterface - a unique number that identifies the rpc interface
7259 * IN currentFunc - the index of the function being invoked
7261 * IN totalFunc - the total number of functions in this interface
7263 * IN queueTime - the amount of time this function waited for a thread
7265 * IN execTime - the amount of time this function invocation took to execute
7267 * IN bytesSent - the number bytes sent by this invocation
7269 * IN bytesRcvd - the number bytes received by this invocation
7271 * IN isServer - if true, this invocation was made to a server
7273 * IN remoteHost - the ip address of the remote host
7275 * IN remotePort - the port of the remote host
7277 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7279 * INOUT counter - if a new stats structure is allocated, the counter will
7280 * be updated with the new number of allocated stat structures
7288 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7289 afs_uint32 currentFunc, afs_uint32 totalFunc,
7290 struct clock *queueTime, struct clock *execTime,
7291 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7292 afs_uint32 remoteHost, afs_uint32 remotePort,
7293 int addToPeerList, unsigned int *counter)
7296 rx_interface_stat_p rpc_stat, nrpc_stat;
7299 * See if there's already a structure for this interface
7302 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7303 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7304 && (rpc_stat->stats[0].remote_is_server == isServer))
7309 * Didn't find a match so allocate a new structure and add it to the
7313 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7314 || (rpc_stat->stats[0].interfaceId != rxInterface)
7315 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7320 sizeof(rx_interface_stat_t) +
7321 totalFunc * sizeof(rx_function_entry_v1_t);
7323 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7324 if (rpc_stat == NULL) {
7328 *counter += totalFunc;
7329 for (i = 0; i < totalFunc; i++) {
7330 rpc_stat->stats[i].remote_peer = remoteHost;
7331 rpc_stat->stats[i].remote_port = remotePort;
7332 rpc_stat->stats[i].remote_is_server = isServer;
7333 rpc_stat->stats[i].interfaceId = rxInterface;
7334 rpc_stat->stats[i].func_total = totalFunc;
7335 rpc_stat->stats[i].func_index = i;
7336 hzero(rpc_stat->stats[i].invocations);
7337 hzero(rpc_stat->stats[i].bytes_sent);
7338 hzero(rpc_stat->stats[i].bytes_rcvd);
7339 rpc_stat->stats[i].queue_time_sum.sec = 0;
7340 rpc_stat->stats[i].queue_time_sum.usec = 0;
7341 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7342 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7343 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7344 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7345 rpc_stat->stats[i].queue_time_max.sec = 0;
7346 rpc_stat->stats[i].queue_time_max.usec = 0;
7347 rpc_stat->stats[i].execution_time_sum.sec = 0;
7348 rpc_stat->stats[i].execution_time_sum.usec = 0;
7349 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7350 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7351 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7352 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7353 rpc_stat->stats[i].execution_time_max.sec = 0;
7354 rpc_stat->stats[i].execution_time_max.usec = 0;
7356 queue_Prepend(stats, rpc_stat);
7357 if (addToPeerList) {
7358 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7363 * Increment the stats for this function
7366 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7367 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7368 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7369 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7370 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7371 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7372 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7374 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7375 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7377 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7378 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7380 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7381 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7383 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7384 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7392 * rx_IncrementTimeAndCount - increment the times and count for a particular
7397 * IN peer - the peer who invoked the rpc
7399 * IN rxInterface - a unique number that identifies the rpc interface
7401 * IN currentFunc - the index of the function being invoked
7403 * IN totalFunc - the total number of functions in this interface
7405 * IN queueTime - the amount of time this function waited for a thread
7407 * IN execTime - the amount of time this function invocation took to execute
7409 * IN bytesSent - the number bytes sent by this invocation
7411 * IN bytesRcvd - the number bytes received by this invocation
7413 * IN isServer - if true, this invocation was made to a server
7421 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7422 afs_uint32 currentFunc, afs_uint32 totalFunc,
7423 struct clock *queueTime, struct clock *execTime,
7424 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7428 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7431 MUTEX_ENTER(&rx_rpc_stats);
7432 MUTEX_ENTER(&peer->peer_lock);
7434 if (rxi_monitor_peerStats) {
7435 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7436 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7437 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7440 if (rxi_monitor_processStats) {
7441 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7442 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7443 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7446 MUTEX_EXIT(&peer->peer_lock);
7447 MUTEX_EXIT(&rx_rpc_stats);
7452 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7456 * IN callerVersion - the rpc stat version of the caller.
7458 * IN count - the number of entries to marshall.
7460 * IN stats - pointer to stats to be marshalled.
7462 * OUT ptr - Where to store the marshalled data.
7469 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7470 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7476 * We only support the first version
7478 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7479 *(ptr++) = stats->remote_peer;
7480 *(ptr++) = stats->remote_port;
7481 *(ptr++) = stats->remote_is_server;
7482 *(ptr++) = stats->interfaceId;
7483 *(ptr++) = stats->func_total;
7484 *(ptr++) = stats->func_index;
7485 *(ptr++) = hgethi(stats->invocations);
7486 *(ptr++) = hgetlo(stats->invocations);
7487 *(ptr++) = hgethi(stats->bytes_sent);
7488 *(ptr++) = hgetlo(stats->bytes_sent);
7489 *(ptr++) = hgethi(stats->bytes_rcvd);
7490 *(ptr++) = hgetlo(stats->bytes_rcvd);
7491 *(ptr++) = stats->queue_time_sum.sec;
7492 *(ptr++) = stats->queue_time_sum.usec;
7493 *(ptr++) = stats->queue_time_sum_sqr.sec;
7494 *(ptr++) = stats->queue_time_sum_sqr.usec;
7495 *(ptr++) = stats->queue_time_min.sec;
7496 *(ptr++) = stats->queue_time_min.usec;
7497 *(ptr++) = stats->queue_time_max.sec;
7498 *(ptr++) = stats->queue_time_max.usec;
7499 *(ptr++) = stats->execution_time_sum.sec;
7500 *(ptr++) = stats->execution_time_sum.usec;
7501 *(ptr++) = stats->execution_time_sum_sqr.sec;
7502 *(ptr++) = stats->execution_time_sum_sqr.usec;
7503 *(ptr++) = stats->execution_time_min.sec;
7504 *(ptr++) = stats->execution_time_min.usec;
7505 *(ptr++) = stats->execution_time_max.sec;
7506 *(ptr++) = stats->execution_time_max.usec;
7512 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7517 * IN callerVersion - the rpc stat version of the caller
7519 * OUT myVersion - the rpc stat version of this function
7521 * OUT clock_sec - local time seconds
7523 * OUT clock_usec - local time microseconds
7525 * OUT allocSize - the number of bytes allocated to contain stats
7527 * OUT statCount - the number stats retrieved from this process.
7529 * OUT stats - the actual stats retrieved from this process.
7533 * Returns void. If successful, stats will != NULL.
7537 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7538 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7539 size_t * allocSize, afs_uint32 * statCount,
7540 afs_uint32 ** stats)
7550 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7553 * Check to see if stats are enabled
7556 MUTEX_ENTER(&rx_rpc_stats);
7557 if (!rxi_monitor_processStats) {
7558 MUTEX_EXIT(&rx_rpc_stats);
7562 clock_GetTime(&now);
7563 *clock_sec = now.sec;
7564 *clock_usec = now.usec;
7567 * Allocate the space based upon the caller version
7569 * If the client is at an older version than we are,
7570 * we return the statistic data in the older data format, but
7571 * we still return our version number so the client knows we
7572 * are maintaining more data than it can retrieve.
7575 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7576 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7577 *statCount = rxi_rpc_process_stat_cnt;
7580 * This can't happen yet, but in the future version changes
7581 * can be handled by adding additional code here
7585 if (space > (size_t) 0) {
7587 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7590 rx_interface_stat_p rpc_stat, nrpc_stat;
7594 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7596 * Copy the data based upon the caller version
7598 rx_MarshallProcessRPCStats(callerVersion,
7599 rpc_stat->stats[0].func_total,
7600 rpc_stat->stats, &ptr);
7606 MUTEX_EXIT(&rx_rpc_stats);
7611 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7615 * IN callerVersion - the rpc stat version of the caller
7617 * OUT myVersion - the rpc stat version of this function
7619 * OUT clock_sec - local time seconds
7621 * OUT clock_usec - local time microseconds
7623 * OUT allocSize - the number of bytes allocated to contain stats
7625 * OUT statCount - the number of stats retrieved from the individual
7628 * OUT stats - the actual stats retrieved from the individual peer structures.
7632 * Returns void. If successful, stats will != NULL.
7636 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7637 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7638 size_t * allocSize, afs_uint32 * statCount,
7639 afs_uint32 ** stats)
7649 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7652 * Check to see if stats are enabled
7655 MUTEX_ENTER(&rx_rpc_stats);
7656 if (!rxi_monitor_peerStats) {
7657 MUTEX_EXIT(&rx_rpc_stats);
7661 clock_GetTime(&now);
7662 *clock_sec = now.sec;
7663 *clock_usec = now.usec;
7666 * Allocate the space based upon the caller version
7668 * If the client is at an older version than we are,
7669 * we return the statistic data in the older data format, but
7670 * we still return our version number so the client knows we
7671 * are maintaining more data than it can retrieve.
7674 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7675 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7676 *statCount = rxi_rpc_peer_stat_cnt;
7679 * This can't happen yet, but in the future version changes
7680 * can be handled by adding additional code here
7684 if (space > (size_t) 0) {
7686 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7689 rx_interface_stat_p rpc_stat, nrpc_stat;
7693 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7695 * We have to fix the offset of rpc_stat since we are
7696 * keeping this structure on two rx_queues. The rx_queue
7697 * package assumes that the rx_queue member is the first
7698 * member of the structure. That is, rx_queue assumes that
7699 * any one item is only on one queue at a time. We are
7700 * breaking that assumption and so we have to do a little
7701 * math to fix our pointers.
7704 fix_offset = (char *)rpc_stat;
7705 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7706 rpc_stat = (rx_interface_stat_p) fix_offset;
7709 * Copy the data based upon the caller version
7711 rx_MarshallProcessRPCStats(callerVersion,
7712 rpc_stat->stats[0].func_total,
7713 rpc_stat->stats, &ptr);
7719 MUTEX_EXIT(&rx_rpc_stats);
7724 * rx_FreeRPCStats - free memory allocated by
7725 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7729 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7730 * rx_RetrievePeerRPCStats
7732 * IN allocSize - the number of bytes in stats.
7740 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7742 rxi_Free(stats, allocSize);
7746 * rx_queryProcessRPCStats - see if process rpc stat collection is
7747 * currently enabled.
7753 * Returns 0 if stats are not enabled != 0 otherwise
7757 rx_queryProcessRPCStats(void)
7760 MUTEX_ENTER(&rx_rpc_stats);
7761 rc = rxi_monitor_processStats;
7762 MUTEX_EXIT(&rx_rpc_stats);
7767 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7773 * Returns 0 if stats are not enabled != 0 otherwise
7777 rx_queryPeerRPCStats(void)
7780 MUTEX_ENTER(&rx_rpc_stats);
7781 rc = rxi_monitor_peerStats;
7782 MUTEX_EXIT(&rx_rpc_stats);
7787 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7797 rx_enableProcessRPCStats(void)
7799 MUTEX_ENTER(&rx_rpc_stats);
7800 rx_enable_stats = 1;
7801 rxi_monitor_processStats = 1;
7802 MUTEX_EXIT(&rx_rpc_stats);
7806 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7816 rx_enablePeerRPCStats(void)
7818 MUTEX_ENTER(&rx_rpc_stats);
7819 rx_enable_stats = 1;
7820 rxi_monitor_peerStats = 1;
7821 MUTEX_EXIT(&rx_rpc_stats);
7825 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7835 rx_disableProcessRPCStats(void)
7837 rx_interface_stat_p rpc_stat, nrpc_stat;
7840 MUTEX_ENTER(&rx_rpc_stats);
7843 * Turn off process statistics and if peer stats is also off, turn
7847 rxi_monitor_processStats = 0;
7848 if (rxi_monitor_peerStats == 0) {
7849 rx_enable_stats = 0;
7852 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7853 unsigned int num_funcs = 0;
7856 queue_Remove(rpc_stat);
7857 num_funcs = rpc_stat->stats[0].func_total;
7859 sizeof(rx_interface_stat_t) +
7860 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7862 rxi_Free(rpc_stat, space);
7863 rxi_rpc_process_stat_cnt -= num_funcs;
7865 MUTEX_EXIT(&rx_rpc_stats);
7869 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7879 rx_disablePeerRPCStats(void)
7881 struct rx_peer **peer_ptr, **peer_end;
7884 MUTEX_ENTER(&rx_rpc_stats);
7887 * Turn off peer statistics and if process stats is also off, turn
7891 rxi_monitor_peerStats = 0;
7892 if (rxi_monitor_processStats == 0) {
7893 rx_enable_stats = 0;
7896 MUTEX_ENTER(&rx_peerHashTable_lock);
7897 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7898 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7900 struct rx_peer *peer, *next, *prev;
7901 for (prev = peer = *peer_ptr; peer; peer = next) {
7903 code = MUTEX_TRYENTER(&peer->peer_lock);
7905 rx_interface_stat_p rpc_stat, nrpc_stat;
7908 (&peer->rpcStats, rpc_stat, nrpc_stat,
7909 rx_interface_stat)) {
7910 unsigned int num_funcs = 0;
7913 queue_Remove(&rpc_stat->queue_header);
7914 queue_Remove(&rpc_stat->all_peers);
7915 num_funcs = rpc_stat->stats[0].func_total;
7917 sizeof(rx_interface_stat_t) +
7918 rpc_stat->stats[0].func_total *
7919 sizeof(rx_function_entry_v1_t);
7921 rxi_Free(rpc_stat, space);
7922 rxi_rpc_peer_stat_cnt -= num_funcs;
7924 MUTEX_EXIT(&peer->peer_lock);
7925 if (prev == *peer_ptr) {
7935 MUTEX_EXIT(&rx_peerHashTable_lock);
7936 MUTEX_EXIT(&rx_rpc_stats);
7940 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7945 * IN clearFlag - flag indicating which stats to clear
7953 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7955 rx_interface_stat_p rpc_stat, nrpc_stat;
7957 MUTEX_ENTER(&rx_rpc_stats);
7959 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7960 unsigned int num_funcs = 0, i;
7961 num_funcs = rpc_stat->stats[0].func_total;
7962 for (i = 0; i < num_funcs; i++) {
7963 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7964 hzero(rpc_stat->stats[i].invocations);
7966 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7967 hzero(rpc_stat->stats[i].bytes_sent);
7969 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7970 hzero(rpc_stat->stats[i].bytes_rcvd);
7972 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7973 rpc_stat->stats[i].queue_time_sum.sec = 0;
7974 rpc_stat->stats[i].queue_time_sum.usec = 0;
7976 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7977 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7978 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7980 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7981 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7982 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7984 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7985 rpc_stat->stats[i].queue_time_max.sec = 0;
7986 rpc_stat->stats[i].queue_time_max.usec = 0;
7988 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7989 rpc_stat->stats[i].execution_time_sum.sec = 0;
7990 rpc_stat->stats[i].execution_time_sum.usec = 0;
7992 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7993 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7994 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7996 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7997 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7998 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8000 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8001 rpc_stat->stats[i].execution_time_max.sec = 0;
8002 rpc_stat->stats[i].execution_time_max.usec = 0;
8007 MUTEX_EXIT(&rx_rpc_stats);
8011 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8016 * IN clearFlag - flag indicating which stats to clear
8024 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8026 rx_interface_stat_p rpc_stat, nrpc_stat;
8028 MUTEX_ENTER(&rx_rpc_stats);
8030 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8031 unsigned int num_funcs = 0, i;
8034 * We have to fix the offset of rpc_stat since we are
8035 * keeping this structure on two rx_queues. The rx_queue
8036 * package assumes that the rx_queue member is the first
8037 * member of the structure. That is, rx_queue assumes that
8038 * any one item is only on one queue at a time. We are
8039 * breaking that assumption and so we have to do a little
8040 * math to fix our pointers.
8043 fix_offset = (char *)rpc_stat;
8044 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8045 rpc_stat = (rx_interface_stat_p) fix_offset;
8047 num_funcs = rpc_stat->stats[0].func_total;
8048 for (i = 0; i < num_funcs; i++) {
8049 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8050 hzero(rpc_stat->stats[i].invocations);
8052 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8053 hzero(rpc_stat->stats[i].bytes_sent);
8055 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8056 hzero(rpc_stat->stats[i].bytes_rcvd);
8058 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8059 rpc_stat->stats[i].queue_time_sum.sec = 0;
8060 rpc_stat->stats[i].queue_time_sum.usec = 0;
8062 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8063 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8064 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8066 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8067 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8068 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8070 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8071 rpc_stat->stats[i].queue_time_max.sec = 0;
8072 rpc_stat->stats[i].queue_time_max.usec = 0;
8074 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8075 rpc_stat->stats[i].execution_time_sum.sec = 0;
8076 rpc_stat->stats[i].execution_time_sum.usec = 0;
8078 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8079 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8080 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8082 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8083 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8084 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8086 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8087 rpc_stat->stats[i].execution_time_max.sec = 0;
8088 rpc_stat->stats[i].execution_time_max.usec = 0;
8093 MUTEX_EXIT(&rx_rpc_stats);
8097 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8098 * is authorized to enable/disable/clear RX statistics.
8100 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8103 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8105 rxi_rxstat_userok = proc;
8109 rx_RxStatUserOk(struct rx_call *call)
8111 if (!rxi_rxstat_userok)
8113 return rxi_rxstat_userok(call);
8118 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8119 * function in the MSVC runtime DLL (msvcrt.dll).
8121 * Note: the system serializes calls to this function.
8124 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8125 DWORD reason, /* reason function is being called */
8126 LPVOID reserved) /* reserved for future use */
8129 case DLL_PROCESS_ATTACH:
8130 /* library is being attached to a process */
8134 case DLL_PROCESS_DETACH:
8143 int rx_DumpCalls(FILE *outputFile, char *cookie)
8145 #ifdef RXDEBUG_PACKET
8147 #ifdef KDUMP_RX_LOCK
8148 struct rx_call_rx_lock *c;
8154 sprintf(output, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8155 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8157 for (c = rx_allCallsp; c; c = c->allNextp) {
8158 u_short rqc, tqc, iovqc;
8159 struct rx_packet *p, *np;
8161 MUTEX_ENTER(&c->lock);
8162 queue_Count(&c->rq, p, np, rx_packet, rqc);
8163 queue_Count(&c->tq, p, np, rx_packet, tqc);
8164 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8166 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, "
8167 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8168 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8169 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8170 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8171 #ifdef RX_ENABLE_LOCKS
8174 #ifdef RX_REFCOUNT_CHECK
8175 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8176 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8179 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,
8180 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8181 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8182 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8183 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8184 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8185 #ifdef RX_ENABLE_LOCKS
8186 , (afs_uint32)c->refCount
8188 #ifdef RX_REFCOUNT_CHECK
8189 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8192 MUTEX_EXIT(&c->lock);
8194 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8196 sprintf(output, "%s - End dumping all Rx Calls\r\n", cookie);
8197 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8198 #endif /* RXDEBUG_PACKET */
8201 #endif /* AFS_NT40_ENV */