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(register struct rx_connection *conn);
128 #ifdef RX_ENABLE_LOCKS
129 static void rxi_SetAcksInTransmitQueue(register 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(register 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(register 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(register 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 register 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 register 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 tconn->refCount++; /* no lock required since only this thread knows */
871 tconn->next = rx_connHashTable[hashindex];
872 rx_connHashTable[hashindex] = tconn;
874 rx_MutexIncrement(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 int rxi_lowPeerRefCount = 0;
895 int 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 (conn->peer->refCount < 2) {
918 conn->peer->idleWhen = clock_Sec();
919 if (conn->peer->refCount < 1) {
920 conn->peer->refCount = 1;
922 rx_MutexIncrement(rxi_lowPeerRefCount, rx_stats_mutex);
925 conn->peer->refCount--;
926 MUTEX_EXIT(&rx_peerHashTable_lock);
930 if (conn->type == RX_SERVER_CONNECTION)
931 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
933 rx_MutexDecrement(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(register struct rx_connection *conn)
960 register 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(register struct rx_connection *conn)
1007 register struct rx_connection **conn_ptr;
1008 register int havecalls = 0;
1009 struct rx_packet *packet;
1016 MUTEX_ENTER(&conn->conn_data_lock);
1017 if (conn->refCount > 0)
1020 if (rx_stats_active) {
1021 MUTEX_ENTER(&rx_stats_mutex);
1022 rxi_lowConnRefCount++;
1023 MUTEX_EXIT(&rx_stats_mutex);
1027 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1028 /* Busy; wait till the last guy before proceeding */
1029 MUTEX_EXIT(&conn->conn_data_lock);
1034 /* If the client previously called rx_NewCall, but it is still
1035 * waiting, treat this as a running call, and wait to destroy the
1036 * connection later when the call completes. */
1037 if ((conn->type == RX_CLIENT_CONNECTION)
1038 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
1039 conn->flags |= RX_CONN_DESTROY_ME;
1040 MUTEX_EXIT(&conn->conn_data_lock);
1044 MUTEX_EXIT(&conn->conn_data_lock);
1046 /* Check for extant references to this connection */
1047 for (i = 0; i < RX_MAXCALLS; i++) {
1048 register struct rx_call *call = conn->call[i];
1051 if (conn->type == RX_CLIENT_CONNECTION) {
1052 MUTEX_ENTER(&call->lock);
1053 if (call->delayedAckEvent) {
1054 /* Push the final acknowledgment out now--there
1055 * won't be a subsequent call to acknowledge the
1056 * last reply packets */
1057 rxevent_Cancel(call->delayedAckEvent, call,
1058 RX_CALL_REFCOUNT_DELAY);
1059 if (call->state == RX_STATE_PRECALL
1060 || call->state == RX_STATE_ACTIVE) {
1061 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1063 rxi_AckAll(NULL, call, 0);
1066 MUTEX_EXIT(&call->lock);
1070 #ifdef RX_ENABLE_LOCKS
1072 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1073 MUTEX_EXIT(&conn->conn_data_lock);
1075 /* Someone is accessing a packet right now. */
1079 #endif /* RX_ENABLE_LOCKS */
1082 /* Don't destroy the connection if there are any call
1083 * structures still in use */
1084 rx_MutexOr(conn->flags, RX_CONN_DESTROY_ME, conn->conn_data_lock);
1089 if (conn->delayedAbortEvent) {
1090 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1091 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1093 MUTEX_ENTER(&conn->conn_data_lock);
1094 rxi_SendConnectionAbort(conn, packet, 0, 1);
1095 MUTEX_EXIT(&conn->conn_data_lock);
1096 rxi_FreePacket(packet);
1100 /* Remove from connection hash table before proceeding */
1102 &rx_connHashTable[CONN_HASH
1103 (peer->host, peer->port, conn->cid, conn->epoch,
1105 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1106 if (*conn_ptr == conn) {
1107 *conn_ptr = conn->next;
1111 /* if the conn that we are destroying was the last connection, then we
1112 * clear rxLastConn as well */
1113 if (rxLastConn == conn)
1116 /* Make sure the connection is completely reset before deleting it. */
1117 /* get rid of pending events that could zap us later */
1118 if (conn->challengeEvent)
1119 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1120 if (conn->checkReachEvent)
1121 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1123 /* Add the connection to the list of destroyed connections that
1124 * need to be cleaned up. This is necessary to avoid deadlocks
1125 * in the routines we call to inform others that this connection is
1126 * being destroyed. */
1127 conn->next = rx_connCleanup_list;
1128 rx_connCleanup_list = conn;
1131 /* Externally available version */
1133 rx_DestroyConnection(register struct rx_connection *conn)
1138 rxi_DestroyConnection(conn);
1143 rx_GetConnection(register struct rx_connection *conn)
1148 rx_MutexIncrement(conn->refCount, conn->conn_data_lock);
1152 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1153 /* Wait for the transmit queue to no longer be busy.
1154 * requires the call->lock to be held */
1155 static void rxi_WaitforTQBusy(struct rx_call *call) {
1156 while (call->flags & RX_CALL_TQ_BUSY) {
1157 call->flags |= RX_CALL_TQ_WAIT;
1159 #ifdef RX_ENABLE_LOCKS
1160 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1161 CV_WAIT(&call->cv_tq, &call->lock);
1162 #else /* RX_ENABLE_LOCKS */
1163 osi_rxSleep(&call->tq);
1164 #endif /* RX_ENABLE_LOCKS */
1166 if (call->tqWaiters == 0) {
1167 call->flags &= ~RX_CALL_TQ_WAIT;
1173 /* Start a new rx remote procedure call, on the specified connection.
1174 * If wait is set to 1, wait for a free call channel; otherwise return
1175 * 0. Maxtime gives the maximum number of seconds this call may take,
1176 * after rx_NewCall returns. After this time interval, a call to any
1177 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1178 * For fine grain locking, we hold the conn_call_lock in order to
1179 * to ensure that we don't get signalle after we found a call in an active
1180 * state and before we go to sleep.
1183 rx_NewCall(register struct rx_connection *conn)
1186 register struct rx_call *call;
1187 struct clock queueTime;
1191 dpf(("rx_NewCall(conn %x)\n", conn));
1194 clock_GetTime(&queueTime);
1195 MUTEX_ENTER(&conn->conn_call_lock);
1198 * Check if there are others waiting for a new call.
1199 * If so, let them go first to avoid starving them.
1200 * This is a fairly simple scheme, and might not be
1201 * a complete solution for large numbers of waiters.
1203 * makeCallWaiters keeps track of the number of
1204 * threads waiting to make calls and the
1205 * RX_CONN_MAKECALL_WAITING flag bit is used to
1206 * indicate that there are indeed calls waiting.
1207 * The flag is set when the waiter is incremented.
1208 * It is only cleared in rx_EndCall when
1209 * makeCallWaiters is 0. This prevents us from
1210 * accidently destroying the connection while it
1211 * is potentially about to be used.
1213 MUTEX_ENTER(&conn->conn_data_lock);
1214 if (conn->makeCallWaiters) {
1215 conn->flags |= RX_CONN_MAKECALL_WAITING;
1216 conn->makeCallWaiters++;
1217 MUTEX_EXIT(&conn->conn_data_lock);
1219 #ifdef RX_ENABLE_LOCKS
1220 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1224 rx_MutexDecrement(conn->makeCallWaiters, conn->conn_data_lock);
1226 MUTEX_EXIT(&conn->conn_data_lock);
1229 /* search for next free call on this connection or
1230 * its clones, if any */
1232 register struct rx_connection *tconn;
1234 for (tconn = conn; tconn; tconn = tconn->next_clone) {
1235 for (i = 0; i < RX_MAXCALLS; i++) {
1236 call = tconn->call[i];
1238 MUTEX_ENTER(&call->lock);
1239 if (call->state == RX_STATE_DALLY) {
1240 rxi_ResetCall(call, 0);
1241 (*call->callNumber)++;
1244 MUTEX_EXIT(&call->lock);
1246 call = rxi_NewCall(tconn, i);
1249 } /* for i < RX_MAXCALLS */
1253 * to be here, all available calls for this connection (and all
1254 * of its clones) must be in use
1257 MUTEX_ENTER(&conn->conn_data_lock);
1258 conn->flags |= RX_CONN_MAKECALL_WAITING;
1259 conn->makeCallWaiters++;
1260 MUTEX_EXIT(&conn->conn_data_lock);
1262 #ifdef RX_ENABLE_LOCKS
1263 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1267 rx_MutexDecrement(conn->makeCallWaiters, conn->conn_data_lock);
1272 * Wake up anyone else who might be giving us a chance to
1273 * run (see code above that avoids resource starvation).
1275 #ifdef RX_ENABLE_LOCKS
1276 CV_BROADCAST(&conn->conn_call_cv);
1281 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1283 /* Client is initially in send mode */
1284 call->state = RX_STATE_ACTIVE;
1285 call->error = rx_ConnError(conn);
1287 call->mode = RX_MODE_ERROR;
1289 call->mode = RX_MODE_SENDING;
1291 /* remember start time for call in case we have hard dead time limit */
1292 call->queueTime = queueTime;
1293 clock_GetTime(&call->startTime);
1294 hzero(call->bytesSent);
1295 hzero(call->bytesRcvd);
1297 /* Turn on busy protocol. */
1298 rxi_KeepAliveOn(call);
1300 MUTEX_EXIT(&call->lock);
1301 MUTEX_EXIT(&conn->conn_call_lock);
1304 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1305 /* Now, if TQ wasn't cleared earlier, do it now. */
1306 MUTEX_ENTER(&call->lock);
1307 rxi_WaitforTQBusy(call);
1308 if (call->flags & RX_CALL_TQ_CLEARME) {
1309 rxi_ClearTransmitQueue(call, 1);
1310 /*queue_Init(&call->tq);*/
1312 MUTEX_EXIT(&call->lock);
1313 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1315 dpf(("rx_NewCall(call %x)\n", call));
1320 rxi_HasActiveCalls(register struct rx_connection *aconn)
1323 register struct rx_call *tcall;
1327 for (i = 0; i < RX_MAXCALLS; i++) {
1328 if ((tcall = aconn->call[i])) {
1329 if ((tcall->state == RX_STATE_ACTIVE)
1330 || (tcall->state == RX_STATE_PRECALL)) {
1341 rxi_GetCallNumberVector(register struct rx_connection *aconn,
1342 register afs_int32 * aint32s)
1345 register struct rx_call *tcall;
1349 for (i = 0; i < RX_MAXCALLS; i++) {
1350 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1351 aint32s[i] = aconn->callNumber[i] + 1;
1353 aint32s[i] = aconn->callNumber[i];
1360 rxi_SetCallNumberVector(register struct rx_connection *aconn,
1361 register afs_int32 * aint32s)
1364 register struct rx_call *tcall;
1368 for (i = 0; i < RX_MAXCALLS; i++) {
1369 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1370 aconn->callNumber[i] = aint32s[i] - 1;
1372 aconn->callNumber[i] = aint32s[i];
1378 /* Advertise a new service. A service is named locally by a UDP port
1379 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1382 char *serviceName; Name for identification purposes (e.g. the
1383 service name might be used for probing for
1386 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1387 char *serviceName, struct rx_securityClass **securityObjects,
1388 int nSecurityObjects,
1389 afs_int32(*serviceProc) (struct rx_call * acall))
1391 osi_socket socket = OSI_NULLSOCKET;
1392 register struct rx_service *tservice;
1398 if (serviceId == 0) {
1400 "rx_NewService: service id for service %s is not non-zero.\n",
1407 "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",
1415 tservice = rxi_AllocService();
1417 for (i = 0; i < RX_MAX_SERVICES; i++) {
1418 register struct rx_service *service = rx_services[i];
1420 if (port == service->servicePort && host == service->serviceHost) {
1421 if (service->serviceId == serviceId) {
1422 /* The identical service has already been
1423 * installed; if the caller was intending to
1424 * change the security classes used by this
1425 * service, he/she loses. */
1427 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1428 serviceName, serviceId, service->serviceName);
1430 rxi_FreeService(tservice);
1433 /* Different service, same port: re-use the socket
1434 * which is bound to the same port */
1435 socket = service->socket;
1438 if (socket == OSI_NULLSOCKET) {
1439 /* If we don't already have a socket (from another
1440 * service on same port) get a new one */
1441 socket = rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
1442 if (socket == OSI_NULLSOCKET) {
1444 rxi_FreeService(tservice);
1449 service->socket = socket;
1450 service->serviceHost = host;
1451 service->servicePort = port;
1452 service->serviceId = serviceId;
1453 service->serviceName = serviceName;
1454 service->nSecurityObjects = nSecurityObjects;
1455 service->securityObjects = securityObjects;
1456 service->minProcs = 0;
1457 service->maxProcs = 1;
1458 service->idleDeadTime = 60;
1459 service->idleDeadErr = 0;
1460 service->connDeadTime = rx_connDeadTime;
1461 service->executeRequestProc = serviceProc;
1462 service->checkReach = 0;
1463 rx_services[i] = service; /* not visible until now */
1469 rxi_FreeService(tservice);
1470 (osi_Msg "rx_NewService: cannot support > %d services\n",
1475 /* Set configuration options for all of a service's security objects */
1478 rx_SetSecurityConfiguration(struct rx_service *service,
1479 rx_securityConfigVariables type,
1483 for (i = 0; i<service->nSecurityObjects; i++) {
1484 if (service->securityObjects[i]) {
1485 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1493 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1494 struct rx_securityClass **securityObjects, int nSecurityObjects,
1495 afs_int32(*serviceProc) (struct rx_call * acall))
1497 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1500 /* Generic request processing loop. This routine should be called
1501 * by the implementation dependent rx_ServerProc. If socketp is
1502 * non-null, it will be set to the file descriptor that this thread
1503 * is now listening on. If socketp is null, this routine will never
1506 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1508 register struct rx_call *call;
1509 register afs_int32 code;
1510 register struct rx_service *tservice = NULL;
1517 call = rx_GetCall(threadID, tservice, socketp);
1518 if (socketp && *socketp != OSI_NULLSOCKET) {
1519 /* We are now a listener thread */
1524 /* if server is restarting( typically smooth shutdown) then do not
1525 * allow any new calls.
1528 if (rx_tranquil && (call != NULL)) {
1532 MUTEX_ENTER(&call->lock);
1534 rxi_CallError(call, RX_RESTARTING);
1535 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1537 MUTEX_EXIT(&call->lock);
1541 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1542 #ifdef RX_ENABLE_LOCKS
1544 #endif /* RX_ENABLE_LOCKS */
1545 afs_termState = AFSOP_STOP_AFS;
1546 afs_osi_Wakeup(&afs_termState);
1547 #ifdef RX_ENABLE_LOCKS
1549 #endif /* RX_ENABLE_LOCKS */
1554 tservice = call->conn->service;
1556 if (tservice->beforeProc)
1557 (*tservice->beforeProc) (call);
1559 code = call->conn->service->executeRequestProc(call);
1561 if (tservice->afterProc)
1562 (*tservice->afterProc) (call, code);
1564 rx_EndCall(call, code);
1565 if (rx_stats_active)
1566 rx_MutexIncrement(rxi_nCalls, rx_stats_mutex);
1572 rx_WakeupServerProcs(void)
1574 struct rx_serverQueueEntry *np, *tqp;
1578 MUTEX_ENTER(&rx_serverPool_lock);
1580 #ifdef RX_ENABLE_LOCKS
1581 if (rx_waitForPacket)
1582 CV_BROADCAST(&rx_waitForPacket->cv);
1583 #else /* RX_ENABLE_LOCKS */
1584 if (rx_waitForPacket)
1585 osi_rxWakeup(rx_waitForPacket);
1586 #endif /* RX_ENABLE_LOCKS */
1587 MUTEX_ENTER(&freeSQEList_lock);
1588 for (np = rx_FreeSQEList; np; np = tqp) {
1589 tqp = *(struct rx_serverQueueEntry **)np;
1590 #ifdef RX_ENABLE_LOCKS
1591 CV_BROADCAST(&np->cv);
1592 #else /* RX_ENABLE_LOCKS */
1594 #endif /* RX_ENABLE_LOCKS */
1596 MUTEX_EXIT(&freeSQEList_lock);
1597 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1598 #ifdef RX_ENABLE_LOCKS
1599 CV_BROADCAST(&np->cv);
1600 #else /* RX_ENABLE_LOCKS */
1602 #endif /* RX_ENABLE_LOCKS */
1604 MUTEX_EXIT(&rx_serverPool_lock);
1609 * One thing that seems to happen is that all the server threads get
1610 * tied up on some empty or slow call, and then a whole bunch of calls
1611 * arrive at once, using up the packet pool, so now there are more
1612 * empty calls. The most critical resources here are server threads
1613 * and the free packet pool. The "doreclaim" code seems to help in
1614 * general. I think that eventually we arrive in this state: there
1615 * are lots of pending calls which do have all their packets present,
1616 * so they won't be reclaimed, are multi-packet calls, so they won't
1617 * be scheduled until later, and thus are tying up most of the free
1618 * packet pool for a very long time.
1620 * 1. schedule multi-packet calls if all the packets are present.
1621 * Probably CPU-bound operation, useful to return packets to pool.
1622 * Do what if there is a full window, but the last packet isn't here?
1623 * 3. preserve one thread which *only* runs "best" calls, otherwise
1624 * it sleeps and waits for that type of call.
1625 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1626 * the current dataquota business is badly broken. The quota isn't adjusted
1627 * to reflect how many packets are presently queued for a running call.
1628 * So, when we schedule a queued call with a full window of packets queued
1629 * up for it, that *should* free up a window full of packets for other 2d-class
1630 * calls to be able to use from the packet pool. But it doesn't.
1632 * NB. Most of the time, this code doesn't run -- since idle server threads
1633 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1634 * as a new call arrives.
1636 /* Sleep until a call arrives. Returns a pointer to the call, ready
1637 * for an rx_Read. */
1638 #ifdef RX_ENABLE_LOCKS
1640 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1642 struct rx_serverQueueEntry *sq;
1643 register struct rx_call *call = (struct rx_call *)0;
1644 struct rx_service *service = NULL;
1647 MUTEX_ENTER(&freeSQEList_lock);
1649 if ((sq = rx_FreeSQEList)) {
1650 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1651 MUTEX_EXIT(&freeSQEList_lock);
1652 } else { /* otherwise allocate a new one and return that */
1653 MUTEX_EXIT(&freeSQEList_lock);
1654 sq = (struct rx_serverQueueEntry *)
1655 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1656 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1657 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1660 MUTEX_ENTER(&rx_serverPool_lock);
1661 if (cur_service != NULL) {
1662 ReturnToServerPool(cur_service);
1665 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1666 register struct rx_call *tcall, *ncall, *choice2 = NULL;
1668 /* Scan for eligible incoming calls. A call is not eligible
1669 * if the maximum number of calls for its service type are
1670 * already executing */
1671 /* One thread will process calls FCFS (to prevent starvation),
1672 * while the other threads may run ahead looking for calls which
1673 * have all their input data available immediately. This helps
1674 * keep threads from blocking, waiting for data from the client. */
1675 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1676 service = tcall->conn->service;
1677 if (!QuotaOK(service)) {
1680 if (tno == rxi_fcfs_thread_num
1681 || !tcall->queue_item_header.next) {
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;
1688 } else if (!queue_IsEmpty(&tcall->rq)) {
1689 struct rx_packet *rp;
1690 rp = queue_First(&tcall->rq, rx_packet);
1691 if (rp->header.seq == 1) {
1693 || (rp->header.flags & RX_LAST_PACKET)) {
1695 } else if (rxi_2dchoice && !choice2
1696 && !(tcall->flags & RX_CALL_CLEARED)
1697 && (tcall->rprev > rxi_HardAckRate)) {
1706 ReturnToServerPool(service);
1713 MUTEX_EXIT(&rx_serverPool_lock);
1714 MUTEX_ENTER(&call->lock);
1716 if (call->flags & RX_CALL_WAIT_PROC) {
1717 call->flags &= ~RX_CALL_WAIT_PROC;
1718 rx_MutexDecrement(rx_nWaiting, rx_waiting_mutex);
1721 if (call->state != RX_STATE_PRECALL || call->error) {
1722 MUTEX_EXIT(&call->lock);
1723 MUTEX_ENTER(&rx_serverPool_lock);
1724 ReturnToServerPool(service);
1729 if (queue_IsEmpty(&call->rq)
1730 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1731 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1733 CLEAR_CALL_QUEUE_LOCK(call);
1736 /* If there are no eligible incoming calls, add this process
1737 * to the idle server queue, to wait for one */
1741 *socketp = OSI_NULLSOCKET;
1743 sq->socketp = socketp;
1744 queue_Append(&rx_idleServerQueue, sq);
1745 #ifndef AFS_AIX41_ENV
1746 rx_waitForPacket = sq;
1748 rx_waitingForPacket = sq;
1749 #endif /* AFS_AIX41_ENV */
1751 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1753 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1754 MUTEX_EXIT(&rx_serverPool_lock);
1755 return (struct rx_call *)0;
1758 } while (!(call = sq->newcall)
1759 && !(socketp && *socketp != OSI_NULLSOCKET));
1760 MUTEX_EXIT(&rx_serverPool_lock);
1762 MUTEX_ENTER(&call->lock);
1768 MUTEX_ENTER(&freeSQEList_lock);
1769 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1770 rx_FreeSQEList = sq;
1771 MUTEX_EXIT(&freeSQEList_lock);
1774 clock_GetTime(&call->startTime);
1775 call->state = RX_STATE_ACTIVE;
1776 call->mode = RX_MODE_RECEIVING;
1777 #ifdef RX_KERNEL_TRACE
1778 if (ICL_SETACTIVE(afs_iclSetp)) {
1779 int glockOwner = ISAFS_GLOCK();
1782 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1783 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1790 rxi_calltrace(RX_CALL_START, call);
1791 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1792 call->conn->service->servicePort, call->conn->service->serviceId,
1795 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1796 MUTEX_EXIT(&call->lock);
1798 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1803 #else /* RX_ENABLE_LOCKS */
1805 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1807 struct rx_serverQueueEntry *sq;
1808 register struct rx_call *call = (struct rx_call *)0, *choice2;
1809 struct rx_service *service = NULL;
1813 MUTEX_ENTER(&freeSQEList_lock);
1815 if ((sq = rx_FreeSQEList)) {
1816 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1817 MUTEX_EXIT(&freeSQEList_lock);
1818 } else { /* otherwise allocate a new one and return that */
1819 MUTEX_EXIT(&freeSQEList_lock);
1820 sq = (struct rx_serverQueueEntry *)
1821 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1822 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1823 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1825 MUTEX_ENTER(&sq->lock);
1827 if (cur_service != NULL) {
1828 cur_service->nRequestsRunning--;
1829 if (cur_service->nRequestsRunning < cur_service->minProcs)
1833 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1834 register struct rx_call *tcall, *ncall;
1835 /* Scan for eligible incoming calls. A call is not eligible
1836 * if the maximum number of calls for its service type are
1837 * already executing */
1838 /* One thread will process calls FCFS (to prevent starvation),
1839 * while the other threads may run ahead looking for calls which
1840 * have all their input data available immediately. This helps
1841 * keep threads from blocking, waiting for data from the client. */
1842 choice2 = (struct rx_call *)0;
1843 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1844 service = tcall->conn->service;
1845 if (QuotaOK(service)) {
1846 if (tno == rxi_fcfs_thread_num
1847 || !tcall->queue_item_header.next) {
1848 /* If we're the fcfs thread, then we'll just use
1849 * this call. If we haven't been able to find an optimal
1850 * choice, and we're at the end of the list, then use a
1851 * 2d choice if one has been identified. Otherwise... */
1852 call = (choice2 ? choice2 : tcall);
1853 service = call->conn->service;
1854 } else if (!queue_IsEmpty(&tcall->rq)) {
1855 struct rx_packet *rp;
1856 rp = queue_First(&tcall->rq, rx_packet);
1857 if (rp->header.seq == 1
1859 || (rp->header.flags & RX_LAST_PACKET))) {
1861 } else if (rxi_2dchoice && !choice2
1862 && !(tcall->flags & RX_CALL_CLEARED)
1863 && (tcall->rprev > rxi_HardAckRate)) {
1876 /* we can't schedule a call if there's no data!!! */
1877 /* send an ack if there's no data, if we're missing the
1878 * first packet, or we're missing something between first
1879 * and last -- there's a "hole" in the incoming data. */
1880 if (queue_IsEmpty(&call->rq)
1881 || queue_First(&call->rq, rx_packet)->header.seq != 1
1882 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1883 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1885 call->flags &= (~RX_CALL_WAIT_PROC);
1886 service->nRequestsRunning++;
1887 /* just started call in minProcs pool, need fewer to maintain
1889 if (service->nRequestsRunning <= service->minProcs)
1893 /* MUTEX_EXIT(&call->lock); */
1895 /* If there are no eligible incoming calls, add this process
1896 * to the idle server queue, to wait for one */
1899 *socketp = OSI_NULLSOCKET;
1901 sq->socketp = socketp;
1902 queue_Append(&rx_idleServerQueue, sq);
1906 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1908 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1909 return (struct rx_call *)0;
1912 } while (!(call = sq->newcall)
1913 && !(socketp && *socketp != OSI_NULLSOCKET));
1915 MUTEX_EXIT(&sq->lock);
1917 MUTEX_ENTER(&freeSQEList_lock);
1918 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1919 rx_FreeSQEList = sq;
1920 MUTEX_EXIT(&freeSQEList_lock);
1923 clock_GetTime(&call->startTime);
1924 call->state = RX_STATE_ACTIVE;
1925 call->mode = RX_MODE_RECEIVING;
1926 #ifdef RX_KERNEL_TRACE
1927 if (ICL_SETACTIVE(afs_iclSetp)) {
1928 int glockOwner = ISAFS_GLOCK();
1931 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1932 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1939 rxi_calltrace(RX_CALL_START, call);
1940 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1941 call->conn->service->servicePort, call->conn->service->serviceId,
1944 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1951 #endif /* RX_ENABLE_LOCKS */
1955 /* Establish a procedure to be called when a packet arrives for a
1956 * call. This routine will be called at most once after each call,
1957 * and will also be called if there is an error condition on the or
1958 * the call is complete. Used by multi rx to build a selection
1959 * function which determines which of several calls is likely to be a
1960 * good one to read from.
1961 * NOTE: the way this is currently implemented it is probably only a
1962 * good idea to (1) use it immediately after a newcall (clients only)
1963 * and (2) only use it once. Other uses currently void your warranty
1966 rx_SetArrivalProc(register struct rx_call *call,
1967 register void (*proc) (register struct rx_call * call,
1969 register int index),
1970 register void * handle, register int arg)
1972 call->arrivalProc = proc;
1973 call->arrivalProcHandle = handle;
1974 call->arrivalProcArg = arg;
1977 /* Call is finished (possibly prematurely). Return rc to the peer, if
1978 * appropriate, and return the final error code from the conversation
1982 rx_EndCall(register struct rx_call *call, afs_int32 rc)
1984 register struct rx_connection *conn = call->conn;
1985 register struct rx_service *service;
1991 dpf(("rx_EndCall(call %x rc %d error %d abortCode %d)\n", call, rc, call->error, call->abortCode));
1994 MUTEX_ENTER(&call->lock);
1996 if (rc == 0 && call->error == 0) {
1997 call->abortCode = 0;
1998 call->abortCount = 0;
2001 call->arrivalProc = (void (*)())0;
2002 if (rc && call->error == 0) {
2003 rxi_CallError(call, rc);
2004 /* Send an abort message to the peer if this error code has
2005 * only just been set. If it was set previously, assume the
2006 * peer has already been sent the error code or will request it
2008 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2010 if (conn->type == RX_SERVER_CONNECTION) {
2011 /* Make sure reply or at least dummy reply is sent */
2012 if (call->mode == RX_MODE_RECEIVING) {
2013 rxi_WriteProc(call, 0, 0);
2015 if (call->mode == RX_MODE_SENDING) {
2016 rxi_FlushWrite(call);
2018 service = conn->service;
2019 rxi_calltrace(RX_CALL_END, call);
2020 /* Call goes to hold state until reply packets are acknowledged */
2021 if (call->tfirst + call->nSoftAcked < call->tnext) {
2022 call->state = RX_STATE_HOLD;
2024 call->state = RX_STATE_DALLY;
2025 rxi_ClearTransmitQueue(call, 0);
2026 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2027 rxevent_Cancel(call->keepAliveEvent, call,
2028 RX_CALL_REFCOUNT_ALIVE);
2030 } else { /* Client connection */
2032 /* Make sure server receives input packets, in the case where
2033 * no reply arguments are expected */
2034 if ((call->mode == RX_MODE_SENDING)
2035 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2036 (void)rxi_ReadProc(call, &dummy, 1);
2039 /* If we had an outstanding delayed ack, be nice to the server
2040 * and force-send it now.
2042 if (call->delayedAckEvent) {
2043 rxevent_Cancel(call->delayedAckEvent, call,
2044 RX_CALL_REFCOUNT_DELAY);
2045 call->delayedAckEvent = NULL;
2046 rxi_SendDelayedAck(NULL, call, NULL);
2049 /* We need to release the call lock since it's lower than the
2050 * conn_call_lock and we don't want to hold the conn_call_lock
2051 * over the rx_ReadProc call. The conn_call_lock needs to be held
2052 * here for the case where rx_NewCall is perusing the calls on
2053 * the connection structure. We don't want to signal until
2054 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2055 * have checked this call, found it active and by the time it
2056 * goes to sleep, will have missed the signal.
2058 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2059 * there are threads waiting to use the conn object.
2061 MUTEX_EXIT(&call->lock);
2062 MUTEX_ENTER(&conn->conn_call_lock);
2063 MUTEX_ENTER(&call->lock);
2064 MUTEX_ENTER(&conn->conn_data_lock);
2065 conn->flags |= RX_CONN_BUSY;
2066 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2067 if (conn->makeCallWaiters == 0)
2068 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2069 MUTEX_EXIT(&conn->conn_data_lock);
2070 #ifdef RX_ENABLE_LOCKS
2071 CV_BROADCAST(&conn->conn_call_cv);
2076 #ifdef RX_ENABLE_LOCKS
2078 MUTEX_EXIT(&conn->conn_data_lock);
2080 #endif /* RX_ENABLE_LOCKS */
2081 call->state = RX_STATE_DALLY;
2083 error = call->error;
2085 /* currentPacket, nLeft, and NFree must be zeroed here, because
2086 * ResetCall cannot: ResetCall may be called at splnet(), in the
2087 * kernel version, and may interrupt the macros rx_Read or
2088 * rx_Write, which run at normal priority for efficiency. */
2089 if (call->currentPacket) {
2090 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2091 rxi_FreePacket(call->currentPacket);
2092 call->currentPacket = (struct rx_packet *)0;
2095 call->nLeft = call->nFree = call->curlen = 0;
2097 /* Free any packets from the last call to ReadvProc/WritevProc */
2098 #ifdef RXDEBUG_PACKET
2100 #endif /* RXDEBUG_PACKET */
2101 rxi_FreePackets(0, &call->iovq);
2103 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2104 MUTEX_EXIT(&call->lock);
2105 if (conn->type == RX_CLIENT_CONNECTION) {
2106 MUTEX_EXIT(&conn->conn_call_lock);
2107 conn->flags &= ~RX_CONN_BUSY;
2111 * Map errors to the local host's errno.h format.
2113 error = ntoh_syserr_conv(error);
2117 #if !defined(KERNEL)
2119 /* Call this routine when shutting down a server or client (especially
2120 * clients). This will allow Rx to gracefully garbage collect server
2121 * connections, and reduce the number of retries that a server might
2122 * make to a dead client.
2123 * This is not quite right, since some calls may still be ongoing and
2124 * we can't lock them to destroy them. */
2128 register struct rx_connection **conn_ptr, **conn_end;
2132 if (rxinit_status == 1) {
2134 return; /* Already shutdown. */
2136 rxi_DeleteCachedConnections();
2137 if (rx_connHashTable) {
2138 MUTEX_ENTER(&rx_connHashTable_lock);
2139 for (conn_ptr = &rx_connHashTable[0], conn_end =
2140 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2142 struct rx_connection *conn, *next;
2143 for (conn = *conn_ptr; conn; conn = next) {
2145 if (conn->type == RX_CLIENT_CONNECTION) {
2146 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2148 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2149 #ifdef RX_ENABLE_LOCKS
2150 rxi_DestroyConnectionNoLock(conn);
2151 #else /* RX_ENABLE_LOCKS */
2152 rxi_DestroyConnection(conn);
2153 #endif /* RX_ENABLE_LOCKS */
2157 #ifdef RX_ENABLE_LOCKS
2158 while (rx_connCleanup_list) {
2159 struct rx_connection *conn;
2160 conn = rx_connCleanup_list;
2161 rx_connCleanup_list = rx_connCleanup_list->next;
2162 MUTEX_EXIT(&rx_connHashTable_lock);
2163 rxi_CleanupConnection(conn);
2164 MUTEX_ENTER(&rx_connHashTable_lock);
2166 MUTEX_EXIT(&rx_connHashTable_lock);
2167 #endif /* RX_ENABLE_LOCKS */
2172 afs_winsockCleanup();
2180 /* if we wakeup packet waiter too often, can get in loop with two
2181 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2183 rxi_PacketsUnWait(void)
2185 if (!rx_waitingForPackets) {
2189 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2190 return; /* still over quota */
2193 rx_waitingForPackets = 0;
2194 #ifdef RX_ENABLE_LOCKS
2195 CV_BROADCAST(&rx_waitingForPackets_cv);
2197 osi_rxWakeup(&rx_waitingForPackets);
2203 /* ------------------Internal interfaces------------------------- */
2205 /* Return this process's service structure for the
2206 * specified socket and service */
2208 rxi_FindService(register osi_socket socket, register u_short serviceId)
2210 register struct rx_service **sp;
2211 for (sp = &rx_services[0]; *sp; sp++) {
2212 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2219 #ifdef KDUMP_RX_LOCK
2220 static struct rx_call_rx_lock *rx_allCallsp = 0;
2222 static struct rx_call *rx_allCallsp = 0;
2226 /* Allocate a call structure, for the indicated channel of the
2227 * supplied connection. The mode and state of the call must be set by
2228 * the caller. Returns the call with mutex locked. */
2230 rxi_NewCall(register struct rx_connection *conn, register int channel)
2232 register struct rx_call *call;
2233 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2234 register struct rx_call *cp; /* Call pointer temp */
2235 register struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2236 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2238 dpf(("rxi_NewCall(conn %x, channel %d)\n", conn, channel));
2240 /* Grab an existing call structure, or allocate a new one.
2241 * Existing call structures are assumed to have been left reset by
2243 MUTEX_ENTER(&rx_freeCallQueue_lock);
2245 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2247 * EXCEPT that the TQ might not yet be cleared out.
2248 * Skip over those with in-use TQs.
2251 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2252 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2258 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2259 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2260 call = queue_First(&rx_freeCallQueue, rx_call);
2261 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2263 if (rx_stats_active)
2264 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2265 MUTEX_EXIT(&rx_freeCallQueue_lock);
2266 MUTEX_ENTER(&call->lock);
2267 CLEAR_CALL_QUEUE_LOCK(call);
2268 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2269 /* Now, if TQ wasn't cleared earlier, do it now. */
2270 if (call->flags & RX_CALL_TQ_CLEARME) {
2271 rxi_ClearTransmitQueue(call, 1);
2272 /*queue_Init(&call->tq);*/
2274 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2275 /* Bind the call to its connection structure */
2277 rxi_ResetCall(call, 1);
2280 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2281 #ifdef RXDEBUG_PACKET
2282 call->allNextp = rx_allCallsp;
2283 rx_allCallsp = call;
2285 #endif /* RXDEBUG_PACKET */
2286 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2288 MUTEX_EXIT(&rx_freeCallQueue_lock);
2289 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2290 MUTEX_ENTER(&call->lock);
2291 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2292 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2293 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2295 /* Initialize once-only items */
2296 queue_Init(&call->tq);
2297 queue_Init(&call->rq);
2298 queue_Init(&call->iovq);
2299 #ifdef RXDEBUG_PACKET
2300 call->rqc = call->tqc = call->iovqc = 0;
2301 #endif /* RXDEBUG_PACKET */
2302 /* Bind the call to its connection structure (prereq for reset) */
2304 rxi_ResetCall(call, 1);
2306 call->channel = channel;
2307 call->callNumber = &conn->callNumber[channel];
2308 call->rwind = conn->rwind[channel];
2309 call->twind = conn->twind[channel];
2310 /* Note that the next expected call number is retained (in
2311 * conn->callNumber[i]), even if we reallocate the call structure
2313 conn->call[channel] = call;
2314 /* if the channel's never been used (== 0), we should start at 1, otherwise
2315 * the call number is valid from the last time this channel was used */
2316 if (*call->callNumber == 0)
2317 *call->callNumber = 1;
2322 /* A call has been inactive long enough that so we can throw away
2323 * state, including the call structure, which is placed on the call
2325 * Call is locked upon entry.
2326 * haveCTLock set if called from rxi_ReapConnections
2328 #ifdef RX_ENABLE_LOCKS
2330 rxi_FreeCall(register struct rx_call *call, int haveCTLock)
2331 #else /* RX_ENABLE_LOCKS */
2333 rxi_FreeCall(register struct rx_call *call)
2334 #endif /* RX_ENABLE_LOCKS */
2336 register int channel = call->channel;
2337 register struct rx_connection *conn = call->conn;
2340 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2341 (*call->callNumber)++;
2342 rxi_ResetCall(call, 0);
2343 call->conn->call[channel] = (struct rx_call *)0;
2345 MUTEX_ENTER(&rx_freeCallQueue_lock);
2346 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2347 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2348 /* A call may be free even though its transmit queue is still in use.
2349 * Since we search the call list from head to tail, put busy calls at
2350 * the head of the list, and idle calls at the tail.
2352 if (call->flags & RX_CALL_TQ_BUSY)
2353 queue_Prepend(&rx_freeCallQueue, call);
2355 queue_Append(&rx_freeCallQueue, call);
2356 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2357 queue_Append(&rx_freeCallQueue, call);
2358 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2359 if (rx_stats_active)
2360 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2361 MUTEX_EXIT(&rx_freeCallQueue_lock);
2363 /* Destroy the connection if it was previously slated for
2364 * destruction, i.e. the Rx client code previously called
2365 * rx_DestroyConnection (client connections), or
2366 * rxi_ReapConnections called the same routine (server
2367 * connections). Only do this, however, if there are no
2368 * outstanding calls. Note that for fine grain locking, there appears
2369 * to be a deadlock in that rxi_FreeCall has a call locked and
2370 * DestroyConnectionNoLock locks each call in the conn. But note a
2371 * few lines up where we have removed this call from the conn.
2372 * If someone else destroys a connection, they either have no
2373 * call lock held or are going through this section of code.
2375 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2376 rx_MutexIncrement(conn->refCount, conn->conn_data_lock);
2377 #ifdef RX_ENABLE_LOCKS
2379 rxi_DestroyConnectionNoLock(conn);
2381 rxi_DestroyConnection(conn);
2382 #else /* RX_ENABLE_LOCKS */
2383 rxi_DestroyConnection(conn);
2384 #endif /* RX_ENABLE_LOCKS */
2388 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2390 rxi_Alloc(register size_t size)
2394 if (rx_stats_active)
2395 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2398 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2399 afs_osi_Alloc_NoSleep(size);
2404 osi_Panic("rxi_Alloc error");
2410 rxi_Free(void *addr, register size_t size)
2412 if (rx_stats_active)
2413 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2414 osi_Free(addr, size);
2418 rxi_SetPeerMtu(register afs_uint32 host, register afs_uint32 port, int mtu)
2420 struct rx_peer **peer_ptr, **peer_end;
2423 MUTEX_ENTER(&rx_peerHashTable_lock);
2425 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2426 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2428 struct rx_peer *peer, *next;
2429 for (peer = *peer_ptr; peer; peer = next) {
2431 if (host == peer->host) {
2432 MUTEX_ENTER(&peer->peer_lock);
2433 peer->ifMTU=MIN(mtu, peer->ifMTU);
2434 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2435 MUTEX_EXIT(&peer->peer_lock);
2440 struct rx_peer *peer;
2441 hashIndex = PEER_HASH(host, port);
2442 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2443 if ((peer->host == host) && (peer->port == port)) {
2444 MUTEX_ENTER(&peer->peer_lock);
2445 peer->ifMTU=MIN(mtu, peer->ifMTU);
2446 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2447 MUTEX_EXIT(&peer->peer_lock);
2451 MUTEX_EXIT(&rx_peerHashTable_lock);
2454 /* Find the peer process represented by the supplied (host,port)
2455 * combination. If there is no appropriate active peer structure, a
2456 * new one will be allocated and initialized
2457 * The origPeer, if set, is a pointer to a peer structure on which the
2458 * refcount will be be decremented. This is used to replace the peer
2459 * structure hanging off a connection structure */
2461 rxi_FindPeer(register afs_uint32 host, register u_short port,
2462 struct rx_peer *origPeer, int create)
2464 register struct rx_peer *pp;
2466 hashIndex = PEER_HASH(host, port);
2467 MUTEX_ENTER(&rx_peerHashTable_lock);
2468 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2469 if ((pp->host == host) && (pp->port == port))
2474 pp = rxi_AllocPeer(); /* This bzero's *pp */
2475 pp->host = host; /* set here or in InitPeerParams is zero */
2477 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2478 queue_Init(&pp->congestionQueue);
2479 queue_Init(&pp->rpcStats);
2480 pp->next = rx_peerHashTable[hashIndex];
2481 rx_peerHashTable[hashIndex] = pp;
2482 rxi_InitPeerParams(pp);
2483 if (rx_stats_active)
2484 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2491 origPeer->refCount--;
2492 MUTEX_EXIT(&rx_peerHashTable_lock);
2497 /* Find the connection at (host, port) started at epoch, and with the
2498 * given connection id. Creates the server connection if necessary.
2499 * The type specifies whether a client connection or a server
2500 * connection is desired. In both cases, (host, port) specify the
2501 * peer's (host, pair) pair. Client connections are not made
2502 * automatically by this routine. The parameter socket gives the
2503 * socket descriptor on which the packet was received. This is used,
2504 * in the case of server connections, to check that *new* connections
2505 * come via a valid (port, serviceId). Finally, the securityIndex
2506 * parameter must match the existing index for the connection. If a
2507 * server connection is created, it will be created using the supplied
2508 * index, if the index is valid for this service */
2509 struct rx_connection *
2510 rxi_FindConnection(osi_socket socket, register afs_int32 host,
2511 register u_short port, u_short serviceId, afs_uint32 cid,
2512 afs_uint32 epoch, int type, u_int securityIndex)
2514 int hashindex, flag, i;
2515 register struct rx_connection *conn;
2516 hashindex = CONN_HASH(host, port, cid, epoch, type);
2517 MUTEX_ENTER(&rx_connHashTable_lock);
2518 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2519 rx_connHashTable[hashindex],
2522 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2523 && (epoch == conn->epoch)) {
2524 register struct rx_peer *pp = conn->peer;
2525 if (securityIndex != conn->securityIndex) {
2526 /* this isn't supposed to happen, but someone could forge a packet
2527 * like this, and there seems to be some CM bug that makes this
2528 * happen from time to time -- in which case, the fileserver
2530 MUTEX_EXIT(&rx_connHashTable_lock);
2531 return (struct rx_connection *)0;
2533 if (pp->host == host && pp->port == port)
2535 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2537 /* So what happens when it's a callback connection? */
2538 if ( /*type == RX_CLIENT_CONNECTION && */
2539 (conn->epoch & 0x80000000))
2543 /* the connection rxLastConn that was used the last time is not the
2544 ** one we are looking for now. Hence, start searching in the hash */
2546 conn = rx_connHashTable[hashindex];
2551 struct rx_service *service;
2552 if (type == RX_CLIENT_CONNECTION) {
2553 MUTEX_EXIT(&rx_connHashTable_lock);
2554 return (struct rx_connection *)0;
2556 service = rxi_FindService(socket, serviceId);
2557 if (!service || (securityIndex >= service->nSecurityObjects)
2558 || (service->securityObjects[securityIndex] == 0)) {
2559 MUTEX_EXIT(&rx_connHashTable_lock);
2560 return (struct rx_connection *)0;
2562 conn = rxi_AllocConnection(); /* This bzero's the connection */
2563 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2564 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2565 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2566 conn->next = rx_connHashTable[hashindex];
2567 rx_connHashTable[hashindex] = conn;
2568 conn->peer = rxi_FindPeer(host, port, 0, 1);
2569 conn->type = RX_SERVER_CONNECTION;
2570 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2571 conn->epoch = epoch;
2572 conn->cid = cid & RX_CIDMASK;
2573 /* conn->serial = conn->lastSerial = 0; */
2574 /* conn->timeout = 0; */
2575 conn->ackRate = RX_FAST_ACK_RATE;
2576 conn->service = service;
2577 conn->serviceId = serviceId;
2578 conn->securityIndex = securityIndex;
2579 conn->securityObject = service->securityObjects[securityIndex];
2580 conn->nSpecific = 0;
2581 conn->specific = NULL;
2582 rx_SetConnDeadTime(conn, service->connDeadTime);
2583 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2584 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2585 for (i = 0; i < RX_MAXCALLS; i++) {
2586 conn->twind[i] = rx_initSendWindow;
2587 conn->rwind[i] = rx_initReceiveWindow;
2589 /* Notify security object of the new connection */
2590 RXS_NewConnection(conn->securityObject, conn);
2591 /* XXXX Connection timeout? */
2592 if (service->newConnProc)
2593 (*service->newConnProc) (conn);
2594 if (rx_stats_active)
2595 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2598 rx_MutexIncrement(conn->refCount, conn->conn_data_lock);
2600 rxLastConn = conn; /* store this connection as the last conn used */
2601 MUTEX_EXIT(&rx_connHashTable_lock);
2605 /* There are two packet tracing routines available for testing and monitoring
2606 * Rx. One is called just after every packet is received and the other is
2607 * called just before every packet is sent. Received packets, have had their
2608 * headers decoded, and packets to be sent have not yet had their headers
2609 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2610 * containing the network address. Both can be modified. The return value, if
2611 * non-zero, indicates that the packet should be dropped. */
2613 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2614 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2616 /* A packet has been received off the interface. Np is the packet, socket is
2617 * the socket number it was received from (useful in determining which service
2618 * this packet corresponds to), and (host, port) reflect the host,port of the
2619 * sender. This call returns the packet to the caller if it is finished with
2620 * it, rather than de-allocating it, just as a small performance hack */
2623 rxi_ReceivePacket(register struct rx_packet *np, osi_socket socket,
2624 afs_uint32 host, u_short port, int *tnop,
2625 struct rx_call **newcallp)
2627 register struct rx_call *call;
2628 register struct rx_connection *conn;
2630 afs_uint32 currentCallNumber;
2636 struct rx_packet *tnp;
2639 /* We don't print out the packet until now because (1) the time may not be
2640 * accurate enough until now in the lwp implementation (rx_Listener only gets
2641 * the time after the packet is read) and (2) from a protocol point of view,
2642 * this is the first time the packet has been seen */
2643 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2644 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2645 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2646 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2647 np->header.epoch, np->header.cid, np->header.callNumber,
2648 np->header.seq, np->header.flags, np));
2651 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2652 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2655 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2656 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2659 /* If an input tracer function is defined, call it with the packet and
2660 * network address. Note this function may modify its arguments. */
2661 if (rx_justReceived) {
2662 struct sockaddr_in addr;
2664 addr.sin_family = AF_INET;
2665 addr.sin_port = port;
2666 addr.sin_addr.s_addr = host;
2667 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2668 addr.sin_len = sizeof(addr);
2669 #endif /* AFS_OSF_ENV */
2670 drop = (*rx_justReceived) (np, &addr);
2671 /* drop packet if return value is non-zero */
2674 port = addr.sin_port; /* in case fcn changed addr */
2675 host = addr.sin_addr.s_addr;
2679 /* If packet was not sent by the client, then *we* must be the client */
2680 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2681 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2683 /* Find the connection (or fabricate one, if we're the server & if
2684 * necessary) associated with this packet */
2686 rxi_FindConnection(socket, host, port, np->header.serviceId,
2687 np->header.cid, np->header.epoch, type,
2688 np->header.securityIndex);
2691 /* If no connection found or fabricated, just ignore the packet.
2692 * (An argument could be made for sending an abort packet for
2697 MUTEX_ENTER(&conn->conn_data_lock);
2698 if (conn->maxSerial < np->header.serial)
2699 conn->maxSerial = np->header.serial;
2700 MUTEX_EXIT(&conn->conn_data_lock);
2702 /* If the connection is in an error state, send an abort packet and ignore
2703 * the incoming packet */
2704 if (rx_ConnError(conn)) {
2705 /* Don't respond to an abort packet--we don't want loops! */
2706 MUTEX_ENTER(&conn->conn_data_lock);
2707 if (np->header.type != RX_PACKET_TYPE_ABORT)
2708 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2710 MUTEX_EXIT(&conn->conn_data_lock);
2714 /* Check for connection-only requests (i.e. not call specific). */
2715 if (np->header.callNumber == 0) {
2716 switch (np->header.type) {
2717 case RX_PACKET_TYPE_ABORT: {
2718 /* What if the supplied error is zero? */
2719 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2720 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2721 rxi_ConnectionError(conn, errcode);
2722 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2725 case RX_PACKET_TYPE_CHALLENGE:
2726 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2727 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2729 case RX_PACKET_TYPE_RESPONSE:
2730 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2731 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2733 case RX_PACKET_TYPE_PARAMS:
2734 case RX_PACKET_TYPE_PARAMS + 1:
2735 case RX_PACKET_TYPE_PARAMS + 2:
2736 /* ignore these packet types for now */
2737 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2742 /* Should not reach here, unless the peer is broken: send an
2744 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2745 MUTEX_ENTER(&conn->conn_data_lock);
2746 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2748 MUTEX_EXIT(&conn->conn_data_lock);
2753 channel = np->header.cid & RX_CHANNELMASK;
2754 call = conn->call[channel];
2755 #ifdef RX_ENABLE_LOCKS
2757 MUTEX_ENTER(&call->lock);
2758 /* Test to see if call struct is still attached to conn. */
2759 if (call != conn->call[channel]) {
2761 MUTEX_EXIT(&call->lock);
2762 if (type == RX_SERVER_CONNECTION) {
2763 call = conn->call[channel];
2764 /* If we started with no call attached and there is one now,
2765 * another thread is also running this routine and has gotten
2766 * the connection channel. We should drop this packet in the tests
2767 * below. If there was a call on this connection and it's now
2768 * gone, then we'll be making a new call below.
2769 * If there was previously a call and it's now different then
2770 * the old call was freed and another thread running this routine
2771 * has created a call on this channel. One of these two threads
2772 * has a packet for the old call and the code below handles those
2776 MUTEX_ENTER(&call->lock);
2778 /* This packet can't be for this call. If the new call address is
2779 * 0 then no call is running on this channel. If there is a call
2780 * then, since this is a client connection we're getting data for
2781 * it must be for the previous call.
2783 if (rx_stats_active)
2784 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2785 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2790 currentCallNumber = conn->callNumber[channel];
2792 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2793 if (np->header.callNumber < currentCallNumber) {
2794 if (rx_stats_active)
2795 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2796 #ifdef RX_ENABLE_LOCKS
2798 MUTEX_EXIT(&call->lock);
2800 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2804 MUTEX_ENTER(&conn->conn_call_lock);
2805 call = rxi_NewCall(conn, channel);
2806 MUTEX_EXIT(&conn->conn_call_lock);
2807 *call->callNumber = np->header.callNumber;
2809 if (np->header.callNumber == 0)
2810 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));
2812 call->state = RX_STATE_PRECALL;
2813 clock_GetTime(&call->queueTime);
2814 hzero(call->bytesSent);
2815 hzero(call->bytesRcvd);
2817 * If the number of queued calls exceeds the overload
2818 * threshold then abort this call.
2820 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2821 struct rx_packet *tp;
2823 rxi_CallError(call, rx_BusyError);
2824 tp = rxi_SendCallAbort(call, np, 1, 0);
2825 MUTEX_EXIT(&call->lock);
2826 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2827 if (rx_stats_active)
2828 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2831 rxi_KeepAliveOn(call);
2832 } else if (np->header.callNumber != currentCallNumber) {
2833 /* Wait until the transmit queue is idle before deciding
2834 * whether to reset the current call. Chances are that the
2835 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2838 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2839 while ((call->state == RX_STATE_ACTIVE)
2840 && (call->flags & RX_CALL_TQ_BUSY)) {
2841 call->flags |= RX_CALL_TQ_WAIT;
2843 #ifdef RX_ENABLE_LOCKS
2844 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2845 CV_WAIT(&call->cv_tq, &call->lock);
2846 #else /* RX_ENABLE_LOCKS */
2847 osi_rxSleep(&call->tq);
2848 #endif /* RX_ENABLE_LOCKS */
2850 if (call->tqWaiters == 0)
2851 call->flags &= ~RX_CALL_TQ_WAIT;
2853 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2854 /* If the new call cannot be taken right now send a busy and set
2855 * the error condition in this call, so that it terminates as
2856 * quickly as possible */
2857 if (call->state == RX_STATE_ACTIVE) {
2858 struct rx_packet *tp;
2860 rxi_CallError(call, RX_CALL_DEAD);
2861 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2863 MUTEX_EXIT(&call->lock);
2864 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2867 rxi_ResetCall(call, 0);
2868 *call->callNumber = np->header.callNumber;
2870 if (np->header.callNumber == 0)
2871 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));
2873 call->state = RX_STATE_PRECALL;
2874 clock_GetTime(&call->queueTime);
2875 hzero(call->bytesSent);
2876 hzero(call->bytesRcvd);
2878 * If the number of queued calls exceeds the overload
2879 * threshold then abort this call.
2881 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2882 struct rx_packet *tp;
2884 rxi_CallError(call, rx_BusyError);
2885 tp = rxi_SendCallAbort(call, np, 1, 0);
2886 MUTEX_EXIT(&call->lock);
2887 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2888 if (rx_stats_active)
2889 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2892 rxi_KeepAliveOn(call);
2894 /* Continuing call; do nothing here. */
2896 } else { /* we're the client */
2897 /* Ignore all incoming acknowledgements for calls in DALLY state */
2898 if (call && (call->state == RX_STATE_DALLY)
2899 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2900 if (rx_stats_active)
2901 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2902 #ifdef RX_ENABLE_LOCKS
2904 MUTEX_EXIT(&call->lock);
2907 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2911 /* Ignore anything that's not relevant to the current call. If there
2912 * isn't a current call, then no packet is relevant. */
2913 if (!call || (np->header.callNumber != currentCallNumber)) {
2914 if (rx_stats_active)
2915 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2916 #ifdef RX_ENABLE_LOCKS
2918 MUTEX_EXIT(&call->lock);
2921 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2924 /* If the service security object index stamped in the packet does not
2925 * match the connection's security index, ignore the packet */
2926 if (np->header.securityIndex != conn->securityIndex) {
2927 #ifdef RX_ENABLE_LOCKS
2928 MUTEX_EXIT(&call->lock);
2930 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2934 /* If we're receiving the response, then all transmit packets are
2935 * implicitly acknowledged. Get rid of them. */
2936 if (np->header.type == RX_PACKET_TYPE_DATA) {
2937 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2938 /* XXX Hack. Because we must release the global rx lock when
2939 * sending packets (osi_NetSend) we drop all acks while we're
2940 * traversing the tq in rxi_Start sending packets out because
2941 * packets may move to the freePacketQueue as result of being here!
2942 * So we drop these packets until we're safely out of the
2943 * traversing. Really ugly!
2944 * For fine grain RX locking, we set the acked field in the
2945 * packets and let rxi_Start remove them from the transmit queue.
2947 if (call->flags & RX_CALL_TQ_BUSY) {
2948 #ifdef RX_ENABLE_LOCKS
2949 rxi_SetAcksInTransmitQueue(call);
2952 return np; /* xmitting; drop packet */
2955 rxi_ClearTransmitQueue(call, 0);
2957 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2958 rxi_ClearTransmitQueue(call, 0);
2959 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2961 if (np->header.type == RX_PACKET_TYPE_ACK) {
2962 /* now check to see if this is an ack packet acknowledging that the
2963 * server actually *lost* some hard-acked data. If this happens we
2964 * ignore this packet, as it may indicate that the server restarted in
2965 * the middle of a call. It is also possible that this is an old ack
2966 * packet. We don't abort the connection in this case, because this
2967 * *might* just be an old ack packet. The right way to detect a server
2968 * restart in the midst of a call is to notice that the server epoch
2970 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2971 * XXX unacknowledged. I think that this is off-by-one, but
2972 * XXX I don't dare change it just yet, since it will
2973 * XXX interact badly with the server-restart detection
2974 * XXX code in receiveackpacket. */
2975 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2976 if (rx_stats_active)
2977 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2978 MUTEX_EXIT(&call->lock);
2979 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2983 } /* else not a data packet */
2986 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2987 /* Set remote user defined status from packet */
2988 call->remoteStatus = np->header.userStatus;
2990 /* Note the gap between the expected next packet and the actual
2991 * packet that arrived, when the new packet has a smaller serial number
2992 * than expected. Rioses frequently reorder packets all by themselves,
2993 * so this will be quite important with very large window sizes.
2994 * Skew is checked against 0 here to avoid any dependence on the type of
2995 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2997 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2998 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2999 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3001 MUTEX_ENTER(&conn->conn_data_lock);
3002 skew = conn->lastSerial - np->header.serial;
3003 conn->lastSerial = np->header.serial;
3004 MUTEX_EXIT(&conn->conn_data_lock);
3006 register struct rx_peer *peer;
3008 if (skew > peer->inPacketSkew) {
3009 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
3011 peer->inPacketSkew = skew;
3015 /* Now do packet type-specific processing */
3016 switch (np->header.type) {
3017 case RX_PACKET_TYPE_DATA:
3018 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3021 case RX_PACKET_TYPE_ACK:
3022 /* Respond immediately to ack packets requesting acknowledgement
3024 if (np->header.flags & RX_REQUEST_ACK) {
3026 (void)rxi_SendCallAbort(call, 0, 1, 0);
3028 (void)rxi_SendAck(call, 0, np->header.serial,
3029 RX_ACK_PING_RESPONSE, 1);
3031 np = rxi_ReceiveAckPacket(call, np, 1);
3033 case RX_PACKET_TYPE_ABORT: {
3034 /* An abort packet: reset the call, passing the error up to the user. */
3035 /* What if error is zero? */
3036 /* What if the error is -1? the application will treat it as a timeout. */
3037 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3038 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3039 rxi_CallError(call, errdata);
3040 MUTEX_EXIT(&call->lock);
3041 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3042 return np; /* xmitting; drop packet */
3044 case RX_PACKET_TYPE_BUSY:
3047 case RX_PACKET_TYPE_ACKALL:
3048 /* All packets acknowledged, so we can drop all packets previously
3049 * readied for sending */
3050 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3051 /* XXX Hack. We because we can't release the global rx lock when
3052 * sending packets (osi_NetSend) we drop all ack pkts while we're
3053 * traversing the tq in rxi_Start sending packets out because
3054 * packets may move to the freePacketQueue as result of being
3055 * here! So we drop these packets until we're safely out of the
3056 * traversing. Really ugly!
3057 * For fine grain RX locking, we set the acked field in the packets
3058 * and let rxi_Start remove the packets from the transmit queue.
3060 if (call->flags & RX_CALL_TQ_BUSY) {
3061 #ifdef RX_ENABLE_LOCKS
3062 rxi_SetAcksInTransmitQueue(call);
3064 #else /* RX_ENABLE_LOCKS */
3065 MUTEX_EXIT(&call->lock);
3066 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3067 return np; /* xmitting; drop packet */
3068 #endif /* RX_ENABLE_LOCKS */
3070 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3071 rxi_ClearTransmitQueue(call, 0);
3072 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3075 /* Should not reach here, unless the peer is broken: send an abort
3077 rxi_CallError(call, RX_PROTOCOL_ERROR);
3078 np = rxi_SendCallAbort(call, np, 1, 0);
3081 /* Note when this last legitimate packet was received, for keep-alive
3082 * processing. Note, we delay getting the time until now in the hope that
3083 * the packet will be delivered to the user before any get time is required
3084 * (if not, then the time won't actually be re-evaluated here). */
3085 call->lastReceiveTime = clock_Sec();
3086 MUTEX_EXIT(&call->lock);
3087 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3091 /* return true if this is an "interesting" connection from the point of view
3092 of someone trying to debug the system */
3094 rxi_IsConnInteresting(struct rx_connection *aconn)
3097 register struct rx_call *tcall;
3099 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3101 for (i = 0; i < RX_MAXCALLS; i++) {
3102 tcall = aconn->call[i];
3104 if ((tcall->state == RX_STATE_PRECALL)
3105 || (tcall->state == RX_STATE_ACTIVE))
3107 if ((tcall->mode == RX_MODE_SENDING)
3108 || (tcall->mode == RX_MODE_RECEIVING))
3116 /* if this is one of the last few packets AND it wouldn't be used by the
3117 receiving call to immediately satisfy a read request, then drop it on
3118 the floor, since accepting it might prevent a lock-holding thread from
3119 making progress in its reading. If a call has been cleared while in
3120 the precall state then ignore all subsequent packets until the call
3121 is assigned to a thread. */
3124 TooLow(struct rx_packet *ap, struct rx_call *acall)
3128 MUTEX_ENTER(&rx_quota_mutex);
3129 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3130 && (acall->state == RX_STATE_PRECALL))
3131 || ((rx_nFreePackets < rxi_dataQuota + 2)
3132 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3133 && (acall->flags & RX_CALL_READER_WAIT)))) {
3136 MUTEX_EXIT(&rx_quota_mutex);
3142 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3144 struct rx_connection *conn = arg1;
3145 struct rx_call *acall = arg2;
3146 struct rx_call *call = acall;
3147 struct clock when, now;
3150 MUTEX_ENTER(&conn->conn_data_lock);
3151 conn->checkReachEvent = NULL;
3152 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3155 MUTEX_EXIT(&conn->conn_data_lock);
3159 MUTEX_ENTER(&conn->conn_call_lock);
3160 MUTEX_ENTER(&conn->conn_data_lock);
3161 for (i = 0; i < RX_MAXCALLS; i++) {
3162 struct rx_call *tc = conn->call[i];
3163 if (tc && tc->state == RX_STATE_PRECALL) {
3169 /* Indicate that rxi_CheckReachEvent is no longer running by
3170 * clearing the flag. Must be atomic under conn_data_lock to
3171 * avoid a new call slipping by: rxi_CheckConnReach holds
3172 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3174 conn->flags &= ~RX_CONN_ATTACHWAIT;
3175 MUTEX_EXIT(&conn->conn_data_lock);
3176 MUTEX_EXIT(&conn->conn_call_lock);
3181 MUTEX_ENTER(&call->lock);
3182 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3184 MUTEX_EXIT(&call->lock);
3186 clock_GetTime(&now);
3188 when.sec += RX_CHECKREACH_TIMEOUT;
3189 MUTEX_ENTER(&conn->conn_data_lock);
3190 if (!conn->checkReachEvent) {
3192 conn->checkReachEvent =
3193 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3196 MUTEX_EXIT(&conn->conn_data_lock);
3202 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3204 struct rx_service *service = conn->service;
3205 struct rx_peer *peer = conn->peer;
3206 afs_uint32 now, lastReach;
3208 if (service->checkReach == 0)
3212 MUTEX_ENTER(&peer->peer_lock);
3213 lastReach = peer->lastReachTime;
3214 MUTEX_EXIT(&peer->peer_lock);
3215 if (now - lastReach < RX_CHECKREACH_TTL)
3218 MUTEX_ENTER(&conn->conn_data_lock);
3219 if (conn->flags & RX_CONN_ATTACHWAIT) {
3220 MUTEX_EXIT(&conn->conn_data_lock);
3223 conn->flags |= RX_CONN_ATTACHWAIT;
3224 MUTEX_EXIT(&conn->conn_data_lock);
3225 if (!conn->checkReachEvent)
3226 rxi_CheckReachEvent(NULL, conn, call);
3231 /* try to attach call, if authentication is complete */
3233 TryAttach(register struct rx_call *acall, register osi_socket socket,
3234 register int *tnop, register struct rx_call **newcallp,
3237 struct rx_connection *conn = acall->conn;
3239 if (conn->type == RX_SERVER_CONNECTION
3240 && acall->state == RX_STATE_PRECALL) {
3241 /* Don't attach until we have any req'd. authentication. */
3242 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3243 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3244 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3245 /* Note: this does not necessarily succeed; there
3246 * may not any proc available
3249 rxi_ChallengeOn(acall->conn);
3254 /* A data packet has been received off the interface. This packet is
3255 * appropriate to the call (the call is in the right state, etc.). This
3256 * routine can return a packet to the caller, for re-use */
3259 rxi_ReceiveDataPacket(register struct rx_call *call,
3260 register struct rx_packet *np, int istack,
3261 osi_socket socket, afs_uint32 host, u_short port,
3262 int *tnop, struct rx_call **newcallp)
3264 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3268 afs_uint32 seq, serial, flags;
3270 struct rx_packet *tnp;
3271 struct clock when, now;
3272 if (rx_stats_active)
3273 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3276 /* If there are no packet buffers, drop this new packet, unless we can find
3277 * packet buffers from inactive calls */
3279 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3280 MUTEX_ENTER(&rx_freePktQ_lock);
3281 rxi_NeedMorePackets = TRUE;
3282 MUTEX_EXIT(&rx_freePktQ_lock);
3283 if (rx_stats_active)
3284 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3285 call->rprev = np->header.serial;
3286 rxi_calltrace(RX_TRACE_DROP, call);
3287 dpf(("packet %x dropped on receipt - quota problems", np));
3289 rxi_ClearReceiveQueue(call);
3290 clock_GetTime(&now);
3292 clock_Add(&when, &rx_softAckDelay);
3293 if (!call->delayedAckEvent
3294 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3295 rxevent_Cancel(call->delayedAckEvent, call,
3296 RX_CALL_REFCOUNT_DELAY);
3297 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3298 call->delayedAckEvent =
3299 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3301 /* we've damaged this call already, might as well do it in. */
3307 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3308 * packet is one of several packets transmitted as a single
3309 * datagram. Do not send any soft or hard acks until all packets
3310 * in a jumbogram have been processed. Send negative acks right away.
3312 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3313 /* tnp is non-null when there are more packets in the
3314 * current jumbo gram */
3321 seq = np->header.seq;
3322 serial = np->header.serial;
3323 flags = np->header.flags;
3325 /* If the call is in an error state, send an abort message */
3327 return rxi_SendCallAbort(call, np, istack, 0);
3329 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3330 * AFS 3.5 jumbogram. */
3331 if (flags & RX_JUMBO_PACKET) {
3332 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3337 if (np->header.spare != 0) {
3338 MUTEX_ENTER(&call->conn->conn_data_lock);
3339 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3340 MUTEX_EXIT(&call->conn->conn_data_lock);
3343 /* The usual case is that this is the expected next packet */
3344 if (seq == call->rnext) {
3346 /* Check to make sure it is not a duplicate of one already queued */
3347 if (queue_IsNotEmpty(&call->rq)
3348 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3349 if (rx_stats_active)
3350 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3351 dpf(("packet %x dropped on receipt - duplicate", np));
3352 rxevent_Cancel(call->delayedAckEvent, call,
3353 RX_CALL_REFCOUNT_DELAY);
3354 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3360 /* It's the next packet. Stick it on the receive queue
3361 * for this call. Set newPackets to make sure we wake
3362 * the reader once all packets have been processed */
3363 np->flags |= RX_PKTFLAG_RQ;
3364 queue_Prepend(&call->rq, np);
3365 #ifdef RXDEBUG_PACKET
3367 #endif /* RXDEBUG_PACKET */
3369 np = NULL; /* We can't use this anymore */
3372 /* If an ack is requested then set a flag to make sure we
3373 * send an acknowledgement for this packet */
3374 if (flags & RX_REQUEST_ACK) {
3375 ackNeeded = RX_ACK_REQUESTED;
3378 /* Keep track of whether we have received the last packet */
3379 if (flags & RX_LAST_PACKET) {
3380 call->flags |= RX_CALL_HAVE_LAST;
3384 /* Check whether we have all of the packets for this call */
3385 if (call->flags & RX_CALL_HAVE_LAST) {
3386 afs_uint32 tseq; /* temporary sequence number */
3387 struct rx_packet *tp; /* Temporary packet pointer */
3388 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3390 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3391 if (tseq != tp->header.seq)
3393 if (tp->header.flags & RX_LAST_PACKET) {
3394 call->flags |= RX_CALL_RECEIVE_DONE;
3401 /* Provide asynchronous notification for those who want it
3402 * (e.g. multi rx) */
3403 if (call->arrivalProc) {
3404 (*call->arrivalProc) (call, call->arrivalProcHandle,
3405 call->arrivalProcArg);
3406 call->arrivalProc = (void (*)())0;
3409 /* Update last packet received */
3412 /* If there is no server process serving this call, grab
3413 * one, if available. We only need to do this once. If a
3414 * server thread is available, this thread becomes a server
3415 * thread and the server thread becomes a listener thread. */
3417 TryAttach(call, socket, tnop, newcallp, 0);
3420 /* This is not the expected next packet. */
3422 /* Determine whether this is a new or old packet, and if it's
3423 * a new one, whether it fits into the current receive window.
3424 * Also figure out whether the packet was delivered in sequence.
3425 * We use the prev variable to determine whether the new packet
3426 * is the successor of its immediate predecessor in the
3427 * receive queue, and the missing flag to determine whether
3428 * any of this packets predecessors are missing. */
3430 afs_uint32 prev; /* "Previous packet" sequence number */
3431 struct rx_packet *tp; /* Temporary packet pointer */
3432 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3433 int missing; /* Are any predecessors missing? */
3435 /* If the new packet's sequence number has been sent to the
3436 * application already, then this is a duplicate */
3437 if (seq < call->rnext) {
3438 if (rx_stats_active)
3439 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3440 rxevent_Cancel(call->delayedAckEvent, call,
3441 RX_CALL_REFCOUNT_DELAY);
3442 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3448 /* If the sequence number is greater than what can be
3449 * accomodated by the current window, then send a negative
3450 * acknowledge and drop the packet */
3451 if ((call->rnext + call->rwind) <= seq) {
3452 rxevent_Cancel(call->delayedAckEvent, call,
3453 RX_CALL_REFCOUNT_DELAY);
3454 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3461 /* Look for the packet in the queue of old received packets */
3462 for (prev = call->rnext - 1, missing =
3463 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3464 /*Check for duplicate packet */
3465 if (seq == tp->header.seq) {
3466 if (rx_stats_active)
3467 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3468 rxevent_Cancel(call->delayedAckEvent, call,
3469 RX_CALL_REFCOUNT_DELAY);
3470 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3476 /* If we find a higher sequence packet, break out and
3477 * insert the new packet here. */
3478 if (seq < tp->header.seq)
3480 /* Check for missing packet */
3481 if (tp->header.seq != prev + 1) {
3485 prev = tp->header.seq;
3488 /* Keep track of whether we have received the last packet. */
3489 if (flags & RX_LAST_PACKET) {
3490 call->flags |= RX_CALL_HAVE_LAST;
3493 /* It's within the window: add it to the the receive queue.
3494 * tp is left by the previous loop either pointing at the
3495 * packet before which to insert the new packet, or at the
3496 * queue head if the queue is empty or the packet should be
3498 np->flags |= RX_PKTFLAG_RQ;
3499 #ifdef RXDEBUG_PACKET
3501 #endif /* RXDEBUG_PACKET */
3502 queue_InsertBefore(tp, np);
3506 /* Check whether we have all of the packets for this call */
3507 if ((call->flags & RX_CALL_HAVE_LAST)
3508 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3509 afs_uint32 tseq; /* temporary sequence number */
3512 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3513 if (tseq != tp->header.seq)
3515 if (tp->header.flags & RX_LAST_PACKET) {
3516 call->flags |= RX_CALL_RECEIVE_DONE;
3523 /* We need to send an ack of the packet is out of sequence,
3524 * or if an ack was requested by the peer. */
3525 if (seq != prev + 1 || missing) {
3526 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3527 } else if (flags & RX_REQUEST_ACK) {
3528 ackNeeded = RX_ACK_REQUESTED;
3531 /* Acknowledge the last packet for each call */
3532 if (flags & RX_LAST_PACKET) {
3543 * If the receiver is waiting for an iovec, fill the iovec
3544 * using the data from the receive queue */
3545 if (call->flags & RX_CALL_IOVEC_WAIT) {
3546 didHardAck = rxi_FillReadVec(call, serial);
3547 /* the call may have been aborted */
3556 /* Wakeup the reader if any */
3557 if ((call->flags & RX_CALL_READER_WAIT)
3558 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3559 || (call->iovNext >= call->iovMax)
3560 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3561 call->flags &= ~RX_CALL_READER_WAIT;
3562 #ifdef RX_ENABLE_LOCKS
3563 CV_BROADCAST(&call->cv_rq);
3565 osi_rxWakeup(&call->rq);
3571 * Send an ack when requested by the peer, or once every
3572 * rxi_SoftAckRate packets until the last packet has been
3573 * received. Always send a soft ack for the last packet in
3574 * the server's reply. */
3576 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3577 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3578 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3579 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3580 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3581 } else if (call->nSoftAcks) {
3582 clock_GetTime(&now);
3584 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3585 clock_Add(&when, &rx_lastAckDelay);
3587 clock_Add(&when, &rx_softAckDelay);
3589 if (!call->delayedAckEvent
3590 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3591 rxevent_Cancel(call->delayedAckEvent, call,
3592 RX_CALL_REFCOUNT_DELAY);
3593 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3594 call->delayedAckEvent =
3595 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3597 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3598 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3605 static void rxi_ComputeRate();
3609 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3611 struct rx_peer *peer = conn->peer;
3613 MUTEX_ENTER(&peer->peer_lock);
3614 peer->lastReachTime = clock_Sec();
3615 MUTEX_EXIT(&peer->peer_lock);
3617 MUTEX_ENTER(&conn->conn_data_lock);
3618 if (conn->flags & RX_CONN_ATTACHWAIT) {
3621 conn->flags &= ~RX_CONN_ATTACHWAIT;
3622 MUTEX_EXIT(&conn->conn_data_lock);
3624 for (i = 0; i < RX_MAXCALLS; i++) {
3625 struct rx_call *call = conn->call[i];
3628 MUTEX_ENTER(&call->lock);
3629 /* tnop can be null if newcallp is null */
3630 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3632 MUTEX_EXIT(&call->lock);
3636 MUTEX_EXIT(&conn->conn_data_lock);
3640 rx_ack_reason(int reason)
3643 case RX_ACK_REQUESTED:
3645 case RX_ACK_DUPLICATE:
3647 case RX_ACK_OUT_OF_SEQUENCE:
3649 case RX_ACK_EXCEEDS_WINDOW:
3651 case RX_ACK_NOSPACE:
3655 case RX_ACK_PING_RESPONSE:
3667 /* rxi_ComputePeerNetStats
3669 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3670 * estimates (like RTT and throughput) based on ack packets. Caller
3671 * must ensure that the packet in question is the right one (i.e.
3672 * serial number matches).
3675 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3676 struct rx_ackPacket *ap, struct rx_packet *np)
3678 struct rx_peer *peer = call->conn->peer;
3680 /* Use RTT if not delayed by client. */
3681 if (ap->reason != RX_ACK_DELAY)
3682 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3684 rxi_ComputeRate(peer, call, p, np, ap->reason);
3688 /* The real smarts of the whole thing. */
3690 rxi_ReceiveAckPacket(register struct rx_call *call, struct rx_packet *np,
3693 struct rx_ackPacket *ap;
3695 register struct rx_packet *tp;
3696 register struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3697 register struct rx_connection *conn = call->conn;
3698 struct rx_peer *peer = conn->peer;
3701 /* because there are CM's that are bogus, sending weird values for this. */
3702 afs_uint32 skew = 0;
3707 int newAckCount = 0;
3708 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3709 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3711 if (rx_stats_active)
3712 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3713 ap = (struct rx_ackPacket *)rx_DataOf(np);
3714 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3716 return np; /* truncated ack packet */
3718 /* depends on ack packet struct */
3719 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3720 first = ntohl(ap->firstPacket);
3721 serial = ntohl(ap->serial);
3722 /* temporarily disabled -- needs to degrade over time
3723 * skew = ntohs(ap->maxSkew); */
3725 /* Ignore ack packets received out of order */
3726 if (first < call->tfirst) {
3730 if (np->header.flags & RX_SLOW_START_OK) {
3731 call->flags |= RX_CALL_SLOW_START_OK;
3734 if (ap->reason == RX_ACK_PING_RESPONSE)
3735 rxi_UpdatePeerReach(conn, call);
3739 if (rxdebug_active) {
3743 len = _snprintf(msg, sizeof(msg),
3744 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3745 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3746 ntohl(ap->serial), ntohl(ap->previousPacket),
3747 (unsigned int)np->header.seq, (unsigned int)skew,
3748 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3752 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3753 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3757 OutputDebugString(msg);
3759 #else /* AFS_NT40_ENV */
3762 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3763 ap->reason, ntohl(ap->previousPacket),
3764 (unsigned int)np->header.seq, (unsigned int)serial,
3765 (unsigned int)skew, ntohl(ap->firstPacket));
3768 for (offset = 0; offset < nAcks; offset++)
3769 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3774 #endif /* AFS_NT40_ENV */
3777 /* Update the outgoing packet skew value to the latest value of
3778 * the peer's incoming packet skew value. The ack packet, of
3779 * course, could arrive out of order, but that won't affect things
3781 MUTEX_ENTER(&peer->peer_lock);
3782 peer->outPacketSkew = skew;
3784 /* Check for packets that no longer need to be transmitted, and
3785 * discard them. This only applies to packets positively
3786 * acknowledged as having been sent to the peer's upper level.
3787 * All other packets must be retained. So only packets with
3788 * sequence numbers < ap->firstPacket are candidates. */
3789 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3790 if (tp->header.seq >= first)
3792 call->tfirst = tp->header.seq + 1;
3794 && (tp->header.serial == serial || tp->firstSerial == serial))
3795 rxi_ComputePeerNetStats(call, tp, ap, np);
3796 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3799 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3800 /* XXX Hack. Because we have to release the global rx lock when sending
3801 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3802 * in rxi_Start sending packets out because packets may move to the
3803 * freePacketQueue as result of being here! So we drop these packets until
3804 * we're safely out of the traversing. Really ugly!
3805 * To make it even uglier, if we're using fine grain locking, we can
3806 * set the ack bits in the packets and have rxi_Start remove the packets
3807 * when it's done transmitting.
3809 if (call->flags & RX_CALL_TQ_BUSY) {
3810 #ifdef RX_ENABLE_LOCKS
3811 tp->flags |= RX_PKTFLAG_ACKED;
3812 call->flags |= RX_CALL_TQ_SOME_ACKED;
3813 #else /* RX_ENABLE_LOCKS */
3815 #endif /* RX_ENABLE_LOCKS */
3817 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3820 tp->flags &= ~RX_PKTFLAG_TQ;
3821 #ifdef RXDEBUG_PACKET
3823 #endif /* RXDEBUG_PACKET */
3824 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3829 /* Give rate detector a chance to respond to ping requests */
3830 if (ap->reason == RX_ACK_PING_RESPONSE) {
3831 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3835 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3837 /* Now go through explicit acks/nacks and record the results in
3838 * the waiting packets. These are packets that can't be released
3839 * yet, even with a positive acknowledge. This positive
3840 * acknowledge only means the packet has been received by the
3841 * peer, not that it will be retained long enough to be sent to
3842 * the peer's upper level. In addition, reset the transmit timers
3843 * of any missing packets (those packets that must be missing
3844 * because this packet was out of sequence) */
3846 call->nSoftAcked = 0;
3847 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3848 /* Update round trip time if the ack was stimulated on receipt
3850 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3851 #ifdef RX_ENABLE_LOCKS
3852 if (tp->header.seq >= first)
3853 #endif /* RX_ENABLE_LOCKS */
3854 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3856 && (tp->header.serial == serial || tp->firstSerial == serial))
3857 rxi_ComputePeerNetStats(call, tp, ap, np);
3859 /* Set the acknowledge flag per packet based on the
3860 * information in the ack packet. An acknowlegded packet can
3861 * be downgraded when the server has discarded a packet it
3862 * soacked previously, or when an ack packet is received
3863 * out of sequence. */
3864 if (tp->header.seq < first) {
3865 /* Implicit ack information */
3866 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3869 tp->flags |= RX_PKTFLAG_ACKED;
3870 } else if (tp->header.seq < first + nAcks) {
3871 /* Explicit ack information: set it in the packet appropriately */
3872 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3873 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3875 tp->flags |= RX_PKTFLAG_ACKED;
3882 } else /* RX_ACK_TYPE_NACK */ {
3883 tp->flags &= ~RX_PKTFLAG_ACKED;
3887 tp->flags &= ~RX_PKTFLAG_ACKED;
3891 /* If packet isn't yet acked, and it has been transmitted at least
3892 * once, reset retransmit time using latest timeout
3893 * ie, this should readjust the retransmit timer for all outstanding
3894 * packets... So we don't just retransmit when we should know better*/
3896 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3897 tp->retryTime = tp->timeSent;
3898 clock_Add(&tp->retryTime, &peer->timeout);
3899 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3900 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3904 /* If the window has been extended by this acknowledge packet,
3905 * then wakeup a sender waiting in alloc for window space, or try
3906 * sending packets now, if he's been sitting on packets due to
3907 * lack of window space */
3908 if (call->tnext < (call->tfirst + call->twind)) {
3909 #ifdef RX_ENABLE_LOCKS
3910 CV_SIGNAL(&call->cv_twind);
3912 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3913 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3914 osi_rxWakeup(&call->twind);
3917 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3918 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3922 /* if the ack packet has a receivelen field hanging off it,
3923 * update our state */
3924 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3927 /* If the ack packet has a "recommended" size that is less than
3928 * what I am using now, reduce my size to match */
3929 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3930 (int)sizeof(afs_int32), &tSize);
3931 tSize = (afs_uint32) ntohl(tSize);
3932 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3934 /* Get the maximum packet size to send to this peer */
3935 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3937 tSize = (afs_uint32) ntohl(tSize);
3938 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3939 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3941 /* sanity check - peer might have restarted with different params.
3942 * If peer says "send less", dammit, send less... Peer should never
3943 * be unable to accept packets of the size that prior AFS versions would
3944 * send without asking. */
3945 if (peer->maxMTU != tSize) {
3946 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3948 peer->maxMTU = tSize;
3949 peer->MTU = MIN(tSize, peer->MTU);
3950 call->MTU = MIN(call->MTU, tSize);
3953 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3956 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3957 (int)sizeof(afs_int32), &tSize);
3958 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3959 if (tSize < call->twind) { /* smaller than our send */
3960 call->twind = tSize; /* window, we must send less... */
3961 call->ssthresh = MIN(call->twind, call->ssthresh);
3962 call->conn->twind[call->channel] = call->twind;
3965 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3966 * network MTU confused with the loopback MTU. Calculate the
3967 * maximum MTU here for use in the slow start code below.
3969 maxMTU = peer->maxMTU;
3970 /* Did peer restart with older RX version? */
3971 if (peer->maxDgramPackets > 1) {
3972 peer->maxDgramPackets = 1;
3974 } else if (np->length >=
3975 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3978 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3979 sizeof(afs_int32), &tSize);
3980 tSize = (afs_uint32) ntohl(tSize);
3982 * As of AFS 3.5 we set the send window to match the receive window.
3984 if (tSize < call->twind) {
3985 call->twind = tSize;
3986 call->conn->twind[call->channel] = call->twind;
3987 call->ssthresh = MIN(call->twind, call->ssthresh);
3988 } else if (tSize > call->twind) {
3989 call->twind = tSize;
3990 call->conn->twind[call->channel] = call->twind;
3994 * As of AFS 3.5, a jumbogram is more than one fixed size
3995 * packet transmitted in a single UDP datagram. If the remote
3996 * MTU is smaller than our local MTU then never send a datagram
3997 * larger than the natural MTU.
4000 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
4001 sizeof(afs_int32), &tSize);
4002 maxDgramPackets = (afs_uint32) ntohl(tSize);
4003 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4004 maxDgramPackets = MIN(maxDgramPackets, peer->ifDgramPackets);
4005 if (peer->natMTU < peer->ifMTU)
4006 maxDgramPackets = MIN(maxDgramPackets, rxi_AdjustDgramPackets(1, peer->natMTU));
4007 if (maxDgramPackets > 1) {
4008 peer->maxDgramPackets = maxDgramPackets;
4009 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4011 peer->maxDgramPackets = 1;
4012 call->MTU = peer->natMTU;
4014 } else if (peer->maxDgramPackets > 1) {
4015 /* Restarted with lower version of RX */
4016 peer->maxDgramPackets = 1;
4018 } else if (peer->maxDgramPackets > 1
4019 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4020 /* Restarted with lower version of RX */
4021 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4022 peer->natMTU = OLD_MAX_PACKET_SIZE;
4023 peer->MTU = OLD_MAX_PACKET_SIZE;
4024 peer->maxDgramPackets = 1;
4025 peer->nDgramPackets = 1;
4027 call->MTU = OLD_MAX_PACKET_SIZE;
4032 * Calculate how many datagrams were successfully received after
4033 * the first missing packet and adjust the negative ack counter
4038 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4039 if (call->nNacks < nNacked) {
4040 call->nNacks = nNacked;
4043 call->nAcks += newAckCount;
4047 if (call->flags & RX_CALL_FAST_RECOVER) {
4049 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4051 call->flags &= ~RX_CALL_FAST_RECOVER;
4052 call->cwind = call->nextCwind;
4053 call->nextCwind = 0;
4056 call->nCwindAcks = 0;
4057 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4058 /* Three negative acks in a row trigger congestion recovery */
4059 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4060 MUTEX_EXIT(&peer->peer_lock);
4061 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4062 /* someone else is waiting to start recovery */
4065 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4066 rxi_WaitforTQBusy(call);
4067 MUTEX_ENTER(&peer->peer_lock);
4068 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4069 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4070 call->flags |= RX_CALL_FAST_RECOVER;
4071 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4073 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4074 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4075 call->nextCwind = call->ssthresh;
4078 peer->MTU = call->MTU;
4079 peer->cwind = call->nextCwind;
4080 peer->nDgramPackets = call->nDgramPackets;
4082 call->congestSeq = peer->congestSeq;
4083 /* Reset the resend times on the packets that were nacked
4084 * so we will retransmit as soon as the window permits*/
4085 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4087 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4088 clock_Zero(&tp->retryTime);
4090 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4095 /* If cwind is smaller than ssthresh, then increase
4096 * the window one packet for each ack we receive (exponential
4098 * If cwind is greater than or equal to ssthresh then increase
4099 * the congestion window by one packet for each cwind acks we
4100 * receive (linear growth). */
4101 if (call->cwind < call->ssthresh) {
4103 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4104 call->nCwindAcks = 0;
4106 call->nCwindAcks += newAckCount;
4107 if (call->nCwindAcks >= call->cwind) {
4108 call->nCwindAcks = 0;
4109 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4113 * If we have received several acknowledgements in a row then
4114 * it is time to increase the size of our datagrams
4116 if ((int)call->nAcks > rx_nDgramThreshold) {
4117 if (peer->maxDgramPackets > 1) {
4118 if (call->nDgramPackets < peer->maxDgramPackets) {
4119 call->nDgramPackets++;
4121 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4122 } else if (call->MTU < peer->maxMTU) {
4123 call->MTU += peer->natMTU;
4124 call->MTU = MIN(call->MTU, peer->maxMTU);
4130 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4132 /* Servers need to hold the call until all response packets have
4133 * been acknowledged. Soft acks are good enough since clients
4134 * are not allowed to clear their receive queues. */
4135 if (call->state == RX_STATE_HOLD
4136 && call->tfirst + call->nSoftAcked >= call->tnext) {
4137 call->state = RX_STATE_DALLY;
4138 rxi_ClearTransmitQueue(call, 0);
4139 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4140 } else if (!queue_IsEmpty(&call->tq)) {
4141 rxi_Start(0, call, 0, istack);
4146 /* Received a response to a challenge packet */
4148 rxi_ReceiveResponsePacket(register struct rx_connection *conn,
4149 register struct rx_packet *np, int istack)
4153 /* Ignore the packet if we're the client */
4154 if (conn->type == RX_CLIENT_CONNECTION)
4157 /* If already authenticated, ignore the packet (it's probably a retry) */
4158 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4161 /* Otherwise, have the security object evaluate the response packet */
4162 error = RXS_CheckResponse(conn->securityObject, conn, np);
4164 /* If the response is invalid, reset the connection, sending
4165 * an abort to the peer */
4169 rxi_ConnectionError(conn, error);
4170 MUTEX_ENTER(&conn->conn_data_lock);
4171 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4172 MUTEX_EXIT(&conn->conn_data_lock);
4175 /* If the response is valid, any calls waiting to attach
4176 * servers can now do so */
4179 for (i = 0; i < RX_MAXCALLS; i++) {
4180 struct rx_call *call = conn->call[i];
4182 MUTEX_ENTER(&call->lock);
4183 if (call->state == RX_STATE_PRECALL)
4184 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4185 /* tnop can be null if newcallp is null */
4186 MUTEX_EXIT(&call->lock);
4190 /* Update the peer reachability information, just in case
4191 * some calls went into attach-wait while we were waiting
4192 * for authentication..
4194 rxi_UpdatePeerReach(conn, NULL);
4199 /* A client has received an authentication challenge: the security
4200 * object is asked to cough up a respectable response packet to send
4201 * back to the server. The server is responsible for retrying the
4202 * challenge if it fails to get a response. */
4205 rxi_ReceiveChallengePacket(register struct rx_connection *conn,
4206 register struct rx_packet *np, int istack)
4210 /* Ignore the challenge if we're the server */
4211 if (conn->type == RX_SERVER_CONNECTION)
4214 /* Ignore the challenge if the connection is otherwise idle; someone's
4215 * trying to use us as an oracle. */
4216 if (!rxi_HasActiveCalls(conn))
4219 /* Send the security object the challenge packet. It is expected to fill
4220 * in the response. */
4221 error = RXS_GetResponse(conn->securityObject, conn, np);
4223 /* If the security object is unable to return a valid response, reset the
4224 * connection and send an abort to the peer. Otherwise send the response
4225 * packet to the peer connection. */
4227 rxi_ConnectionError(conn, error);
4228 MUTEX_ENTER(&conn->conn_data_lock);
4229 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4230 MUTEX_EXIT(&conn->conn_data_lock);
4232 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4233 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4239 /* Find an available server process to service the current request in
4240 * the given call structure. If one isn't available, queue up this
4241 * call so it eventually gets one */
4243 rxi_AttachServerProc(register struct rx_call *call,
4244 register osi_socket socket, register int *tnop,
4245 register struct rx_call **newcallp)
4247 register struct rx_serverQueueEntry *sq;
4248 register struct rx_service *service = call->conn->service;
4249 register int haveQuota = 0;
4251 /* May already be attached */
4252 if (call->state == RX_STATE_ACTIVE)
4255 MUTEX_ENTER(&rx_serverPool_lock);
4257 haveQuota = QuotaOK(service);
4258 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4259 /* If there are no processes available to service this call,
4260 * put the call on the incoming call queue (unless it's
4261 * already on the queue).
4263 #ifdef RX_ENABLE_LOCKS
4265 ReturnToServerPool(service);
4266 #endif /* RX_ENABLE_LOCKS */
4268 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4269 call->flags |= RX_CALL_WAIT_PROC;
4270 MUTEX_ENTER(&rx_waiting_mutex);
4273 MUTEX_EXIT(&rx_waiting_mutex);
4274 rxi_calltrace(RX_CALL_ARRIVAL, call);
4275 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4276 queue_Append(&rx_incomingCallQueue, call);
4279 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4281 /* If hot threads are enabled, and both newcallp and sq->socketp
4282 * are non-null, then this thread will process the call, and the
4283 * idle server thread will start listening on this threads socket.
4286 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4289 *sq->socketp = socket;
4290 clock_GetTime(&call->startTime);
4291 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4295 if (call->flags & RX_CALL_WAIT_PROC) {
4296 /* Conservative: I don't think this should happen */
4297 call->flags &= ~RX_CALL_WAIT_PROC;
4298 if (queue_IsOnQueue(call)) {
4301 MUTEX_ENTER(&rx_waiting_mutex);
4303 MUTEX_EXIT(&rx_waiting_mutex);
4306 call->state = RX_STATE_ACTIVE;
4307 call->mode = RX_MODE_RECEIVING;
4308 #ifdef RX_KERNEL_TRACE
4310 int glockOwner = ISAFS_GLOCK();
4313 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4314 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4320 if (call->flags & RX_CALL_CLEARED) {
4321 /* send an ack now to start the packet flow up again */
4322 call->flags &= ~RX_CALL_CLEARED;
4323 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4325 #ifdef RX_ENABLE_LOCKS
4328 service->nRequestsRunning++;
4329 if (service->nRequestsRunning <= service->minProcs)
4335 MUTEX_EXIT(&rx_serverPool_lock);
4338 /* Delay the sending of an acknowledge event for a short while, while
4339 * a new call is being prepared (in the case of a client) or a reply
4340 * is being prepared (in the case of a server). Rather than sending
4341 * an ack packet, an ACKALL packet is sent. */
4343 rxi_AckAll(struct rxevent *event, register struct rx_call *call, char *dummy)
4345 #ifdef RX_ENABLE_LOCKS
4347 MUTEX_ENTER(&call->lock);
4348 call->delayedAckEvent = NULL;
4349 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4351 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4352 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4354 MUTEX_EXIT(&call->lock);
4355 #else /* RX_ENABLE_LOCKS */
4357 call->delayedAckEvent = NULL;
4358 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4359 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4360 #endif /* RX_ENABLE_LOCKS */
4364 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4366 struct rx_call *call = arg1;
4367 #ifdef RX_ENABLE_LOCKS
4369 MUTEX_ENTER(&call->lock);
4370 if (event == call->delayedAckEvent)
4371 call->delayedAckEvent = NULL;
4372 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4374 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4376 MUTEX_EXIT(&call->lock);
4377 #else /* RX_ENABLE_LOCKS */
4379 call->delayedAckEvent = NULL;
4380 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4381 #endif /* RX_ENABLE_LOCKS */
4385 #ifdef RX_ENABLE_LOCKS
4386 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4387 * clearing them out.
4390 rxi_SetAcksInTransmitQueue(register struct rx_call *call)
4392 register struct rx_packet *p, *tp;
4395 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4396 p->flags |= RX_PKTFLAG_ACKED;
4400 call->flags |= RX_CALL_TQ_CLEARME;
4401 call->flags |= RX_CALL_TQ_SOME_ACKED;
4404 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4405 call->tfirst = call->tnext;
4406 call->nSoftAcked = 0;
4408 if (call->flags & RX_CALL_FAST_RECOVER) {
4409 call->flags &= ~RX_CALL_FAST_RECOVER;
4410 call->cwind = call->nextCwind;
4411 call->nextCwind = 0;
4414 CV_SIGNAL(&call->cv_twind);
4416 #endif /* RX_ENABLE_LOCKS */
4418 /* Clear out the transmit queue for the current call (all packets have
4419 * been received by peer) */
4421 rxi_ClearTransmitQueue(register struct rx_call *call, register int force)
4423 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4424 register struct rx_packet *p, *tp;
4426 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4428 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4429 p->flags |= RX_PKTFLAG_ACKED;
4433 call->flags |= RX_CALL_TQ_CLEARME;
4434 call->flags |= RX_CALL_TQ_SOME_ACKED;
4437 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4438 #ifdef RXDEBUG_PACKET
4440 #endif /* RXDEBUG_PACKET */
4441 rxi_FreePackets(0, &call->tq);
4442 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4443 call->flags &= ~RX_CALL_TQ_CLEARME;
4445 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4447 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4448 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4449 call->nSoftAcked = 0;
4451 if (call->flags & RX_CALL_FAST_RECOVER) {
4452 call->flags &= ~RX_CALL_FAST_RECOVER;
4453 call->cwind = call->nextCwind;
4455 #ifdef RX_ENABLE_LOCKS
4456 CV_SIGNAL(&call->cv_twind);
4458 osi_rxWakeup(&call->twind);
4463 rxi_ClearReceiveQueue(register struct rx_call *call)
4465 if (queue_IsNotEmpty(&call->rq)) {
4468 count = rxi_FreePackets(0, &call->rq);
4469 rx_packetReclaims += count;
4470 #ifdef RXDEBUG_PACKET
4472 if ( call->rqc != 0 )
4473 dpf(("rxi_ClearReceiveQueue call %x rqc %u != 0", call, call->rqc));
4475 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4477 if (call->state == RX_STATE_PRECALL) {
4478 call->flags |= RX_CALL_CLEARED;
4482 /* Send an abort packet for the specified call */
4484 rxi_SendCallAbort(register struct rx_call *call, struct rx_packet *packet,
4485 int istack, int force)
4488 struct clock when, now;
4493 /* Clients should never delay abort messages */
4494 if (rx_IsClientConn(call->conn))
4497 if (call->abortCode != call->error) {
4498 call->abortCode = call->error;
4499 call->abortCount = 0;
4502 if (force || rxi_callAbortThreshhold == 0
4503 || call->abortCount < rxi_callAbortThreshhold) {
4504 if (call->delayedAbortEvent) {
4505 rxevent_Cancel(call->delayedAbortEvent, call,
4506 RX_CALL_REFCOUNT_ABORT);
4508 error = htonl(call->error);
4511 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4512 (char *)&error, sizeof(error), istack);
4513 } else if (!call->delayedAbortEvent) {
4514 clock_GetTime(&now);
4516 clock_Addmsec(&when, rxi_callAbortDelay);
4517 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4518 call->delayedAbortEvent =
4519 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4524 /* Send an abort packet for the specified connection. Packet is an
4525 * optional pointer to a packet that can be used to send the abort.
4526 * Once the number of abort messages reaches the threshhold, an
4527 * event is scheduled to send the abort. Setting the force flag
4528 * overrides sending delayed abort messages.
4530 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4531 * to send the abort packet.
4534 rxi_SendConnectionAbort(register struct rx_connection *conn,
4535 struct rx_packet *packet, int istack, int force)
4538 struct clock when, now;
4540 if (!rx_ConnError(conn))
4543 /* Clients should never delay abort messages */
4544 if (rx_IsClientConn(conn))
4547 if (force || rxi_connAbortThreshhold == 0
4548 || conn->abortCount < rxi_connAbortThreshhold) {
4549 if (conn->delayedAbortEvent) {
4550 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4552 error = htonl(rx_ConnError(conn));
4554 MUTEX_EXIT(&conn->conn_data_lock);
4556 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4557 RX_PACKET_TYPE_ABORT, (char *)&error,
4558 sizeof(error), istack);
4559 MUTEX_ENTER(&conn->conn_data_lock);
4560 } else if (!conn->delayedAbortEvent) {
4561 clock_GetTime(&now);
4563 clock_Addmsec(&when, rxi_connAbortDelay);
4564 conn->delayedAbortEvent =
4565 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4571 * Associate an error all of the calls owned by a connection. Called
4572 * with error non-zero. This is only for really fatal things, like
4573 * bad authentication responses. The connection itself is set in
4574 * error at this point, so that future packets received will be
4578 rxi_ConnectionError(register struct rx_connection *conn,
4579 register afs_int32 error)
4583 struct rx_connection *tconn;
4585 dpf(("rxi_ConnectionError conn %x error %d", conn, error));
4587 MUTEX_ENTER(&conn->conn_data_lock);
4588 if (conn->challengeEvent)
4589 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4590 if (conn->checkReachEvent) {
4591 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4592 conn->checkReachEvent = 0;
4593 conn->flags &= ~RX_CONN_ATTACHWAIT;
4596 MUTEX_EXIT(&conn->conn_data_lock);
4598 for ( tconn = rx_IsClonedConn(conn) ? conn->parent : conn;
4600 tconn = tconn->next_clone) {
4601 for (i = 0; i < RX_MAXCALLS; i++) {
4602 struct rx_call *call = tconn->call[i];
4604 MUTEX_ENTER(&call->lock);
4605 rxi_CallError(call, error);
4606 MUTEX_EXIT(&call->lock);
4610 rx_SetConnError(conn, error);
4611 if (rx_stats_active)
4612 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4617 rxi_CallError(register struct rx_call *call, afs_int32 error)
4620 osirx_AssertMine(&call->lock, "rxi_CallError");
4622 dpf(("rxi_CallError call %x error %d call->error %d", call, error, call->error));
4624 error = call->error;
4626 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4627 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4628 rxi_ResetCall(call, 0);
4631 rxi_ResetCall(call, 0);
4633 call->error = error;
4634 call->mode = RX_MODE_ERROR;
4637 /* Reset various fields in a call structure, and wakeup waiting
4638 * processes. Some fields aren't changed: state & mode are not
4639 * touched (these must be set by the caller), and bufptr, nLeft, and
4640 * nFree are not reset, since these fields are manipulated by
4641 * unprotected macros, and may only be reset by non-interrupting code.
4644 /* this code requires that call->conn be set properly as a pre-condition. */
4645 #endif /* ADAPT_WINDOW */
4648 rxi_ResetCall(register struct rx_call *call, register int newcall)
4651 register struct rx_peer *peer;
4652 struct rx_packet *packet;
4654 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4656 dpf(("rxi_ResetCall(call %x, newcall %d)\n", call, newcall));
4658 /* Notify anyone who is waiting for asynchronous packet arrival */
4659 if (call->arrivalProc) {
4660 (*call->arrivalProc) (call, call->arrivalProcHandle,
4661 call->arrivalProcArg);
4662 call->arrivalProc = (void (*)())0;
4665 if (call->delayedAbortEvent) {
4666 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4667 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4669 rxi_SendCallAbort(call, packet, 0, 1);
4670 rxi_FreePacket(packet);
4675 * Update the peer with the congestion information in this call
4676 * so other calls on this connection can pick up where this call
4677 * left off. If the congestion sequence numbers don't match then
4678 * another call experienced a retransmission.
4680 peer = call->conn->peer;
4681 MUTEX_ENTER(&peer->peer_lock);
4683 if (call->congestSeq == peer->congestSeq) {
4684 peer->cwind = MAX(peer->cwind, call->cwind);
4685 peer->MTU = MAX(peer->MTU, call->MTU);
4686 peer->nDgramPackets =
4687 MAX(peer->nDgramPackets, call->nDgramPackets);
4690 call->abortCode = 0;
4691 call->abortCount = 0;
4693 if (peer->maxDgramPackets > 1) {
4694 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4696 call->MTU = peer->MTU;
4698 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4699 call->ssthresh = rx_maxSendWindow;
4700 call->nDgramPackets = peer->nDgramPackets;
4701 call->congestSeq = peer->congestSeq;
4702 MUTEX_EXIT(&peer->peer_lock);
4704 flags = call->flags;
4705 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4706 if (flags & RX_CALL_TQ_BUSY) {
4707 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4708 call->flags |= (flags & RX_CALL_TQ_WAIT);
4710 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4712 rxi_ClearTransmitQueue(call, 1);
4713 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4714 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4715 dpf(("rcall %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4718 while (call->tqWaiters) {
4719 #ifdef RX_ENABLE_LOCKS
4720 CV_BROADCAST(&call->cv_tq);
4721 #else /* RX_ENABLE_LOCKS */
4722 osi_rxWakeup(&call->tq);
4723 #endif /* RX_ENABLE_LOCKS */
4728 rxi_ClearReceiveQueue(call);
4729 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4731 if (call->currentPacket) {
4732 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4733 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4734 queue_Prepend(&call->iovq, call->currentPacket);
4735 #ifdef RXDEBUG_PACKET
4737 #endif /* RXDEBUG_PACKET */
4738 call->currentPacket = (struct rx_packet *)0;
4740 call->curlen = call->nLeft = call->nFree = 0;
4742 #ifdef RXDEBUG_PACKET
4745 rxi_FreePackets(0, &call->iovq);
4748 call->twind = call->conn->twind[call->channel];
4749 call->rwind = call->conn->rwind[call->channel];
4750 call->nSoftAcked = 0;
4751 call->nextCwind = 0;
4754 call->nCwindAcks = 0;
4755 call->nSoftAcks = 0;
4756 call->nHardAcks = 0;
4758 call->tfirst = call->rnext = call->tnext = 1;
4760 call->lastAcked = 0;
4761 call->localStatus = call->remoteStatus = 0;
4763 if (flags & RX_CALL_READER_WAIT) {
4764 #ifdef RX_ENABLE_LOCKS
4765 CV_BROADCAST(&call->cv_rq);
4767 osi_rxWakeup(&call->rq);
4770 if (flags & RX_CALL_WAIT_PACKETS) {
4771 MUTEX_ENTER(&rx_freePktQ_lock);
4772 rxi_PacketsUnWait(); /* XXX */
4773 MUTEX_EXIT(&rx_freePktQ_lock);
4775 #ifdef RX_ENABLE_LOCKS
4776 CV_SIGNAL(&call->cv_twind);
4778 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4779 osi_rxWakeup(&call->twind);
4782 #ifdef RX_ENABLE_LOCKS
4783 /* The following ensures that we don't mess with any queue while some
4784 * other thread might also be doing so. The call_queue_lock field is
4785 * is only modified under the call lock. If the call is in the process
4786 * of being removed from a queue, the call is not locked until the
4787 * the queue lock is dropped and only then is the call_queue_lock field
4788 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4789 * Note that any other routine which removes a call from a queue has to
4790 * obtain the queue lock before examing the queue and removing the call.
4792 if (call->call_queue_lock) {
4793 MUTEX_ENTER(call->call_queue_lock);
4794 if (queue_IsOnQueue(call)) {
4796 if (flags & RX_CALL_WAIT_PROC) {
4798 MUTEX_ENTER(&rx_waiting_mutex);
4800 MUTEX_EXIT(&rx_waiting_mutex);
4803 MUTEX_EXIT(call->call_queue_lock);
4804 CLEAR_CALL_QUEUE_LOCK(call);
4806 #else /* RX_ENABLE_LOCKS */
4807 if (queue_IsOnQueue(call)) {
4809 if (flags & RX_CALL_WAIT_PROC)
4812 #endif /* RX_ENABLE_LOCKS */
4814 rxi_KeepAliveOff(call);
4815 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4818 /* Send an acknowledge for the indicated packet (seq,serial) of the
4819 * indicated call, for the indicated reason (reason). This
4820 * acknowledge will specifically acknowledge receiving the packet, and
4821 * will also specify which other packets for this call have been
4822 * received. This routine returns the packet that was used to the
4823 * caller. The caller is responsible for freeing it or re-using it.
4824 * This acknowledgement also returns the highest sequence number
4825 * actually read out by the higher level to the sender; the sender
4826 * promises to keep around packets that have not been read by the
4827 * higher level yet (unless, of course, the sender decides to abort
4828 * the call altogether). Any of p, seq, serial, pflags, or reason may
4829 * be set to zero without ill effect. That is, if they are zero, they
4830 * will not convey any information.
4831 * NOW there is a trailer field, after the ack where it will safely be
4832 * ignored by mundanes, which indicates the maximum size packet this
4833 * host can swallow. */
4835 register struct rx_packet *optionalPacket; use to send ack (or null)
4836 int seq; Sequence number of the packet we are acking
4837 int serial; Serial number of the packet
4838 int pflags; Flags field from packet header
4839 int reason; Reason an acknowledge was prompted
4843 rxi_SendAck(register struct rx_call *call,
4844 register struct rx_packet *optionalPacket, int serial, int reason,
4847 struct rx_ackPacket *ap;
4848 register struct rx_packet *rqp;
4849 register struct rx_packet *nxp; /* For queue_Scan */
4850 register struct rx_packet *p;
4853 #ifdef RX_ENABLE_TSFPQ
4854 struct rx_ts_info_t * rx_ts_info;
4858 * Open the receive window once a thread starts reading packets
4860 if (call->rnext > 1) {
4861 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4864 call->nHardAcks = 0;
4865 call->nSoftAcks = 0;
4866 if (call->rnext > call->lastAcked)
4867 call->lastAcked = call->rnext;
4871 rx_computelen(p, p->length); /* reset length, you never know */
4872 } /* where that's been... */
4873 #ifdef RX_ENABLE_TSFPQ
4875 RX_TS_INFO_GET(rx_ts_info);
4876 if ((p = rx_ts_info->local_special_packet)) {
4877 rx_computelen(p, p->length);
4878 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4879 rx_ts_info->local_special_packet = p;
4880 } else { /* We won't send the ack, but don't panic. */
4881 return optionalPacket;
4885 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4886 /* We won't send the ack, but don't panic. */
4887 return optionalPacket;
4892 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4895 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4896 #ifndef RX_ENABLE_TSFPQ
4897 if (!optionalPacket)
4900 return optionalPacket;
4902 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4903 if (rx_Contiguous(p) < templ) {
4904 #ifndef RX_ENABLE_TSFPQ
4905 if (!optionalPacket)
4908 return optionalPacket;
4913 /* MTUXXX failing to send an ack is very serious. We should */
4914 /* try as hard as possible to send even a partial ack; it's */
4915 /* better than nothing. */
4916 ap = (struct rx_ackPacket *)rx_DataOf(p);
4917 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4918 ap->reason = reason;
4920 /* The skew computation used to be bogus, I think it's better now. */
4921 /* We should start paying attention to skew. XXX */
4922 ap->serial = htonl(serial);
4923 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4925 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4926 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4928 /* No fear of running out of ack packet here because there can only be at most
4929 * one window full of unacknowledged packets. The window size must be constrained
4930 * to be less than the maximum ack size, of course. Also, an ack should always
4931 * fit into a single packet -- it should not ever be fragmented. */
4932 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4933 if (!rqp || !call->rq.next
4934 || (rqp->header.seq > (call->rnext + call->rwind))) {
4935 #ifndef RX_ENABLE_TSFPQ
4936 if (!optionalPacket)
4939 rxi_CallError(call, RX_CALL_DEAD);
4940 return optionalPacket;
4943 while (rqp->header.seq > call->rnext + offset)
4944 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4945 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4947 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4948 #ifndef RX_ENABLE_TSFPQ
4949 if (!optionalPacket)
4952 rxi_CallError(call, RX_CALL_DEAD);
4953 return optionalPacket;
4958 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4960 /* these are new for AFS 3.3 */
4961 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4962 templ = htonl(templ);
4963 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4964 templ = htonl(call->conn->peer->ifMTU);
4965 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4966 sizeof(afs_int32), &templ);
4968 /* new for AFS 3.4 */
4969 templ = htonl(call->rwind);
4970 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4971 sizeof(afs_int32), &templ);
4973 /* new for AFS 3.5 */
4974 templ = htonl(call->conn->peer->ifDgramPackets);
4975 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4976 sizeof(afs_int32), &templ);
4978 p->header.serviceId = call->conn->serviceId;
4979 p->header.cid = (call->conn->cid | call->channel);
4980 p->header.callNumber = *call->callNumber;
4982 p->header.securityIndex = call->conn->securityIndex;
4983 p->header.epoch = call->conn->epoch;
4984 p->header.type = RX_PACKET_TYPE_ACK;
4985 p->header.flags = RX_SLOW_START_OK;
4986 if (reason == RX_ACK_PING) {
4987 p->header.flags |= RX_REQUEST_ACK;
4989 clock_GetTime(&call->pingRequestTime);
4992 if (call->conn->type == RX_CLIENT_CONNECTION)
4993 p->header.flags |= RX_CLIENT_INITIATED;
4997 if (rxdebug_active) {
5001 len = _snprintf(msg, sizeof(msg),
5002 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5003 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5004 ntohl(ap->serial), ntohl(ap->previousPacket),
5005 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5006 ap->nAcks, ntohs(ap->bufferSpace) );
5010 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5011 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5015 OutputDebugString(msg);
5017 #else /* AFS_NT40_ENV */
5019 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5020 ap->reason, ntohl(ap->previousPacket),
5021 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5023 for (offset = 0; offset < ap->nAcks; offset++)
5024 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5029 #endif /* AFS_NT40_ENV */
5032 register int i, nbytes = p->length;
5034 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5035 if (nbytes <= p->wirevec[i].iov_len) {
5036 register int savelen, saven;
5038 savelen = p->wirevec[i].iov_len;
5040 p->wirevec[i].iov_len = nbytes;
5042 rxi_Send(call, p, istack);
5043 p->wirevec[i].iov_len = savelen;
5047 nbytes -= p->wirevec[i].iov_len;
5050 if (rx_stats_active)
5051 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5052 #ifndef RX_ENABLE_TSFPQ
5053 if (!optionalPacket)
5056 return optionalPacket; /* Return packet for re-use by caller */
5059 /* Send all of the packets in the list in single datagram */
5061 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5062 int istack, int moreFlag, struct clock *now,
5063 struct clock *retryTime, int resending)
5068 struct rx_connection *conn = call->conn;
5069 struct rx_peer *peer = conn->peer;
5071 MUTEX_ENTER(&peer->peer_lock);
5074 peer->reSends += len;
5075 if (rx_stats_active)
5076 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5077 MUTEX_EXIT(&peer->peer_lock);
5079 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5083 /* Set the packet flags and schedule the resend events */
5084 /* Only request an ack for the last packet in the list */
5085 for (i = 0; i < len; i++) {
5086 list[i]->retryTime = *retryTime;
5087 if (list[i]->header.serial) {
5088 /* Exponentially backoff retry times */
5089 if (list[i]->backoff < MAXBACKOFF) {
5090 /* so it can't stay == 0 */
5091 list[i]->backoff = (list[i]->backoff << 1) + 1;
5094 clock_Addmsec(&(list[i]->retryTime),
5095 ((afs_uint32) list[i]->backoff) << 8);
5098 /* Wait a little extra for the ack on the last packet */
5099 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5100 clock_Addmsec(&(list[i]->retryTime), 400);
5103 /* Record the time sent */
5104 list[i]->timeSent = *now;
5106 /* Ask for an ack on retransmitted packets, on every other packet
5107 * if the peer doesn't support slow start. Ask for an ack on every
5108 * packet until the congestion window reaches the ack rate. */
5109 if (list[i]->header.serial) {
5111 if (rx_stats_active)
5112 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5114 /* improved RTO calculation- not Karn */
5115 list[i]->firstSent = *now;
5116 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5117 || (!(call->flags & RX_CALL_SLOW_START_OK)
5118 && (list[i]->header.seq & 1)))) {
5123 MUTEX_ENTER(&peer->peer_lock);
5127 if (rx_stats_active)
5128 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5129 MUTEX_EXIT(&peer->peer_lock);
5131 /* Tag this packet as not being the last in this group,
5132 * for the receiver's benefit */
5133 if (i < len - 1 || moreFlag) {
5134 list[i]->header.flags |= RX_MORE_PACKETS;
5137 /* Install the new retransmit time for the packet, and
5138 * record the time sent */
5139 list[i]->timeSent = *now;
5143 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5146 /* Since we're about to send a data packet to the peer, it's
5147 * safe to nuke any scheduled end-of-packets ack */
5148 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5150 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5151 MUTEX_EXIT(&call->lock);
5153 rxi_SendPacketList(call, conn, list, len, istack);
5155 rxi_SendPacket(call, conn, list[0], istack);
5157 MUTEX_ENTER(&call->lock);
5158 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5160 /* Update last send time for this call (for keep-alive
5161 * processing), and for the connection (so that we can discover
5162 * idle connections) */
5163 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5166 /* When sending packets we need to follow these rules:
5167 * 1. Never send more than maxDgramPackets in a jumbogram.
5168 * 2. Never send a packet with more than two iovecs in a jumbogram.
5169 * 3. Never send a retransmitted packet in a jumbogram.
5170 * 4. Never send more than cwind/4 packets in a jumbogram
5171 * We always keep the last list we should have sent so we
5172 * can set the RX_MORE_PACKETS flags correctly.
5175 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5176 int istack, struct clock *now, struct clock *retryTime,
5179 int i, cnt, lastCnt = 0;
5180 struct rx_packet **listP, **lastP = 0;
5181 struct rx_peer *peer = call->conn->peer;
5182 int morePackets = 0;
5184 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5185 /* Does the current packet force us to flush the current list? */
5187 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5188 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5190 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5192 /* If the call enters an error state stop sending, or if
5193 * we entered congestion recovery mode, stop sending */
5194 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5202 /* Add the current packet to the list if it hasn't been acked.
5203 * Otherwise adjust the list pointer to skip the current packet. */
5204 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5206 /* Do we need to flush the list? */
5207 if (cnt >= (int)peer->maxDgramPackets
5208 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5209 || list[i]->header.serial
5210 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5212 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5213 retryTime, resending);
5214 /* If the call enters an error state stop sending, or if
5215 * we entered congestion recovery mode, stop sending */
5217 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5222 listP = &list[i + 1];
5227 osi_Panic("rxi_SendList error");
5229 listP = &list[i + 1];
5233 /* Send the whole list when the call is in receive mode, when
5234 * the call is in eof mode, when we are in fast recovery mode,
5235 * and when we have the last packet */
5236 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5237 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5238 || (call->flags & RX_CALL_FAST_RECOVER)) {
5239 /* Check for the case where the current list contains
5240 * an acked packet. Since we always send retransmissions
5241 * in a separate packet, we only need to check the first
5242 * packet in the list */
5243 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5247 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5248 retryTime, resending);
5249 /* If the call enters an error state stop sending, or if
5250 * we entered congestion recovery mode, stop sending */
5251 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5255 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5258 } else if (lastCnt > 0) {
5259 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5264 #ifdef RX_ENABLE_LOCKS
5265 /* Call rxi_Start, below, but with the call lock held. */
5267 rxi_StartUnlocked(struct rxevent *event,
5268 void *arg0, void *arg1, int istack)
5270 struct rx_call *call = arg0;
5272 MUTEX_ENTER(&call->lock);
5273 rxi_Start(event, call, arg1, istack);
5274 MUTEX_EXIT(&call->lock);
5276 #endif /* RX_ENABLE_LOCKS */
5278 /* This routine is called when new packets are readied for
5279 * transmission and when retransmission may be necessary, or when the
5280 * transmission window or burst count are favourable. This should be
5281 * better optimized for new packets, the usual case, now that we've
5282 * got rid of queues of send packets. XXXXXXXXXXX */
5284 rxi_Start(struct rxevent *event,
5285 void *arg0, void *arg1, int istack)
5287 struct rx_call *call = arg0;
5289 struct rx_packet *p;
5290 register struct rx_packet *nxp; /* Next pointer for queue_Scan */
5291 struct rx_peer *peer = call->conn->peer;
5292 struct clock now, usenow, retryTime;
5296 struct rx_packet **xmitList;
5299 /* If rxi_Start is being called as a result of a resend event,
5300 * then make sure that the event pointer is removed from the call
5301 * structure, since there is no longer a per-call retransmission
5303 if (event && event == call->resendEvent) {
5304 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5305 call->resendEvent = NULL;
5307 if (queue_IsEmpty(&call->tq)) {
5311 /* Timeouts trigger congestion recovery */
5312 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5313 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5314 /* someone else is waiting to start recovery */
5317 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5318 rxi_WaitforTQBusy(call);
5319 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5320 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5321 call->flags |= RX_CALL_FAST_RECOVER;
5322 if (peer->maxDgramPackets > 1) {
5323 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5325 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5327 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5328 call->nDgramPackets = 1;
5330 call->nextCwind = 1;
5333 MUTEX_ENTER(&peer->peer_lock);
5334 peer->MTU = call->MTU;
5335 peer->cwind = call->cwind;
5336 peer->nDgramPackets = 1;
5338 call->congestSeq = peer->congestSeq;
5339 MUTEX_EXIT(&peer->peer_lock);
5340 /* Clear retry times on packets. Otherwise, it's possible for
5341 * some packets in the queue to force resends at rates faster
5342 * than recovery rates.
5344 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5345 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5346 clock_Zero(&p->retryTime);
5351 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5352 if (rx_stats_active)
5353 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5358 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5359 /* Get clock to compute the re-transmit time for any packets
5360 * in this burst. Note, if we back off, it's reasonable to
5361 * back off all of the packets in the same manner, even if
5362 * some of them have been retransmitted more times than more
5364 * Do a dance to avoid blocking after setting now. */
5365 clock_Zero(&retryTime);
5366 MUTEX_ENTER(&peer->peer_lock);
5367 clock_Add(&retryTime, &peer->timeout);
5368 MUTEX_EXIT(&peer->peer_lock);
5369 clock_GetTime(&now);
5370 clock_Add(&retryTime, &now);
5372 /* Send (or resend) any packets that need it, subject to
5373 * window restrictions and congestion burst control
5374 * restrictions. Ask for an ack on the last packet sent in
5375 * this burst. For now, we're relying upon the window being
5376 * considerably bigger than the largest number of packets that
5377 * are typically sent at once by one initial call to
5378 * rxi_Start. This is probably bogus (perhaps we should ask
5379 * for an ack when we're half way through the current
5380 * window?). Also, for non file transfer applications, this
5381 * may end up asking for an ack for every packet. Bogus. XXXX
5384 * But check whether we're here recursively, and let the other guy
5387 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5388 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5389 call->flags |= RX_CALL_TQ_BUSY;
5391 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5393 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5394 call->flags &= ~RX_CALL_NEED_START;
5395 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5397 maxXmitPackets = MIN(call->twind, call->cwind);
5398 xmitList = (struct rx_packet **)
5399 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5400 /* XXXX else we must drop any mtx we hold */
5401 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5403 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5405 if (xmitList == NULL)
5406 osi_Panic("rxi_Start, failed to allocate xmit list");
5407 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5408 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5409 /* We shouldn't be sending packets if a thread is waiting
5410 * to initiate congestion recovery */
5414 && (call->flags & RX_CALL_FAST_RECOVER)) {
5415 /* Only send one packet during fast recovery */
5418 if ((p->flags & RX_PKTFLAG_FREE)
5419 || (!queue_IsEnd(&call->tq, nxp)
5420 && (nxp->flags & RX_PKTFLAG_FREE))
5421 || (p == (struct rx_packet *)&rx_freePacketQueue)
5422 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5423 osi_Panic("rxi_Start: xmit queue clobbered");
5425 if (p->flags & RX_PKTFLAG_ACKED) {
5426 /* Since we may block, don't trust this */
5427 usenow.sec = usenow.usec = 0;
5428 if (rx_stats_active)
5429 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5430 continue; /* Ignore this packet if it has been acknowledged */
5433 /* Turn off all flags except these ones, which are the same
5434 * on each transmission */
5435 p->header.flags &= RX_PRESET_FLAGS;
5437 if (p->header.seq >=
5438 call->tfirst + MIN((int)call->twind,
5439 (int)(call->nSoftAcked +
5441 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5442 /* Note: if we're waiting for more window space, we can
5443 * still send retransmits; hence we don't return here, but
5444 * break out to schedule a retransmit event */
5445 dpf(("call %d waiting for window",
5446 *(call->callNumber)));
5450 /* Transmit the packet if it needs to be sent. */
5451 if (!clock_Lt(&now, &p->retryTime)) {
5452 if (nXmitPackets == maxXmitPackets) {
5453 rxi_SendXmitList(call, xmitList, nXmitPackets,
5454 istack, &now, &retryTime,
5456 osi_Free(xmitList, maxXmitPackets *
5457 sizeof(struct rx_packet *));
5460 xmitList[nXmitPackets++] = p;
5464 /* xmitList now hold pointers to all of the packets that are
5465 * ready to send. Now we loop to send the packets */
5466 if (nXmitPackets > 0) {
5467 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5468 &now, &retryTime, resending);
5471 maxXmitPackets * sizeof(struct rx_packet *));
5473 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5475 * TQ references no longer protected by this flag; they must remain
5476 * protected by the global lock.
5478 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5479 call->flags &= ~RX_CALL_TQ_BUSY;
5480 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5481 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5482 #ifdef RX_ENABLE_LOCKS
5483 osirx_AssertMine(&call->lock, "rxi_Start start");
5484 CV_BROADCAST(&call->cv_tq);
5485 #else /* RX_ENABLE_LOCKS */
5486 osi_rxWakeup(&call->tq);
5487 #endif /* RX_ENABLE_LOCKS */
5492 /* We went into the error state while sending packets. Now is
5493 * the time to reset the call. This will also inform the using
5494 * process that the call is in an error state.
5496 if (rx_stats_active)
5497 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5498 call->flags &= ~RX_CALL_TQ_BUSY;
5499 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5500 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5501 #ifdef RX_ENABLE_LOCKS
5502 osirx_AssertMine(&call->lock, "rxi_Start middle");
5503 CV_BROADCAST(&call->cv_tq);
5504 #else /* RX_ENABLE_LOCKS */
5505 osi_rxWakeup(&call->tq);
5506 #endif /* RX_ENABLE_LOCKS */
5508 rxi_CallError(call, call->error);
5511 #ifdef RX_ENABLE_LOCKS
5512 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5513 register int missing;
5514 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5515 /* Some packets have received acks. If they all have, we can clear
5516 * the transmit queue.
5519 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5520 if (p->header.seq < call->tfirst
5521 && (p->flags & RX_PKTFLAG_ACKED)) {
5523 p->flags &= ~RX_PKTFLAG_TQ;
5524 #ifdef RXDEBUG_PACKET
5532 call->flags |= RX_CALL_TQ_CLEARME;
5534 #endif /* RX_ENABLE_LOCKS */
5535 /* Don't bother doing retransmits if the TQ is cleared. */
5536 if (call->flags & RX_CALL_TQ_CLEARME) {
5537 rxi_ClearTransmitQueue(call, 1);
5539 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5542 /* Always post a resend event, if there is anything in the
5543 * queue, and resend is possible. There should be at least
5544 * one unacknowledged packet in the queue ... otherwise none
5545 * of these packets should be on the queue in the first place.
5547 if (call->resendEvent) {
5548 /* Cancel the existing event and post a new one */
5549 rxevent_Cancel(call->resendEvent, call,
5550 RX_CALL_REFCOUNT_RESEND);
5553 /* The retry time is the retry time on the first unacknowledged
5554 * packet inside the current window */
5556 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5557 /* Don't set timers for packets outside the window */
5558 if (p->header.seq >= call->tfirst + call->twind) {
5562 if (!(p->flags & RX_PKTFLAG_ACKED)
5563 && !clock_IsZero(&p->retryTime)) {
5565 retryTime = p->retryTime;
5570 /* Post a new event to re-run rxi_Start when retries may be needed */
5571 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5572 #ifdef RX_ENABLE_LOCKS
5573 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5575 rxevent_PostNow2(&retryTime, &usenow,
5577 (void *)call, 0, istack);
5578 #else /* RX_ENABLE_LOCKS */
5580 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5581 (void *)call, 0, istack);
5582 #endif /* RX_ENABLE_LOCKS */
5585 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5586 } while (call->flags & RX_CALL_NEED_START);
5588 * TQ references no longer protected by this flag; they must remain
5589 * protected by the global lock.
5591 call->flags &= ~RX_CALL_TQ_BUSY;
5592 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5593 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5594 #ifdef RX_ENABLE_LOCKS
5595 osirx_AssertMine(&call->lock, "rxi_Start end");
5596 CV_BROADCAST(&call->cv_tq);
5597 #else /* RX_ENABLE_LOCKS */
5598 osi_rxWakeup(&call->tq);
5599 #endif /* RX_ENABLE_LOCKS */
5602 call->flags |= RX_CALL_NEED_START;
5604 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5606 if (call->resendEvent) {
5607 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5612 /* Also adjusts the keep alive parameters for the call, to reflect
5613 * that we have just sent a packet (so keep alives aren't sent
5616 rxi_Send(register struct rx_call *call, register struct rx_packet *p,
5619 register struct rx_connection *conn = call->conn;
5621 /* Stamp each packet with the user supplied status */
5622 p->header.userStatus = call->localStatus;
5624 /* Allow the security object controlling this call's security to
5625 * make any last-minute changes to the packet */
5626 RXS_SendPacket(conn->securityObject, call, p);
5628 /* Since we're about to send SOME sort of packet to the peer, it's
5629 * safe to nuke any scheduled end-of-packets ack */
5630 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5632 /* Actually send the packet, filling in more connection-specific fields */
5633 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5634 MUTEX_EXIT(&call->lock);
5635 rxi_SendPacket(call, conn, p, istack);
5636 MUTEX_ENTER(&call->lock);
5637 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5639 /* Update last send time for this call (for keep-alive
5640 * processing), and for the connection (so that we can discover
5641 * idle connections) */
5642 conn->lastSendTime = call->lastSendTime = clock_Sec();
5643 /* Don't count keepalives here, so idleness can be tracked. */
5644 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5645 call->lastSendData = call->lastSendTime;
5649 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5650 * that things are fine. Also called periodically to guarantee that nothing
5651 * falls through the cracks (e.g. (error + dally) connections have keepalive
5652 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5654 * haveCTLock Set if calling from rxi_ReapConnections
5656 #ifdef RX_ENABLE_LOCKS
5658 rxi_CheckCall(register struct rx_call *call, int haveCTLock)
5659 #else /* RX_ENABLE_LOCKS */
5661 rxi_CheckCall(register struct rx_call *call)
5662 #endif /* RX_ENABLE_LOCKS */
5664 register struct rx_connection *conn = call->conn;
5666 afs_uint32 deadTime;
5668 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5669 if (call->flags & RX_CALL_TQ_BUSY) {
5670 /* Call is active and will be reset by rxi_Start if it's
5671 * in an error state.
5676 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5678 (((afs_uint32) rx_ConnSecondsUntilDead(conn) << 10) +
5679 ((afs_uint32) conn->peer->rtt >> 3) +
5680 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5682 /* These are computed to the second (+- 1 second). But that's
5683 * good enough for these values, which should be a significant
5684 * number of seconds. */
5685 if (now > (call->lastReceiveTime + deadTime)) {
5686 if (call->state == RX_STATE_ACTIVE) {
5688 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5690 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5691 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5692 ip_stack_t *ipst = ns->netstack_ip;
5694 ire = ire_cache_lookup(call->conn->peer->host
5695 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5697 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5699 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5706 if (ire && ire->ire_max_frag > 0)
5707 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5708 #if defined(GLOBAL_NETSTACKID)
5712 #endif /* ADAPT_PMTU */
5713 rxi_CallError(call, RX_CALL_DEAD);
5716 #ifdef RX_ENABLE_LOCKS
5717 /* Cancel pending events */
5718 rxevent_Cancel(call->delayedAckEvent, call,
5719 RX_CALL_REFCOUNT_DELAY);
5720 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5721 rxevent_Cancel(call->keepAliveEvent, call,
5722 RX_CALL_REFCOUNT_ALIVE);
5723 if (call->refCount == 0) {
5724 rxi_FreeCall(call, haveCTLock);
5728 #else /* RX_ENABLE_LOCKS */
5731 #endif /* RX_ENABLE_LOCKS */
5733 /* Non-active calls are destroyed if they are not responding
5734 * to pings; active calls are simply flagged in error, so the
5735 * attached process can die reasonably gracefully. */
5737 /* see if we have a non-activity timeout */
5738 if (call->startWait && rx_ConnIdleDeadTime(conn)
5739 && ((call->startWait + rx_ConnIdleDeadTime(conn)) < now)) {
5740 if (call->state == RX_STATE_ACTIVE) {
5741 rxi_CallError(call, RX_CALL_TIMEOUT);
5745 if (call->lastSendData && rx_ConnIdleDeadTime(conn)
5746 && (rx_ConnIdleDeadErr(conn) != 0)
5747 && ((call->lastSendData + rx_ConnIdleDeadTime(conn)) < now)) {
5748 if (call->state == RX_STATE_ACTIVE) {
5749 rxi_CallError(call, conn->idleDeadErr);
5753 /* see if we have a hard timeout */
5754 if (rx_ConnHardDeadTime(conn)
5755 && (now > (rx_ConnHardDeadTime(conn) + call->startTime.sec))) {
5756 if (call->state == RX_STATE_ACTIVE)
5757 rxi_CallError(call, RX_CALL_TIMEOUT);
5764 /* When a call is in progress, this routine is called occasionally to
5765 * make sure that some traffic has arrived (or been sent to) the peer.
5766 * If nothing has arrived in a reasonable amount of time, the call is
5767 * declared dead; if nothing has been sent for a while, we send a
5768 * keep-alive packet (if we're actually trying to keep the call alive)
5771 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5773 struct rx_call *call = arg1;
5774 struct rx_connection *conn;
5777 MUTEX_ENTER(&call->lock);
5778 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5779 if (event == call->keepAliveEvent)
5780 call->keepAliveEvent = NULL;
5783 #ifdef RX_ENABLE_LOCKS
5784 if (rxi_CheckCall(call, 0)) {
5785 MUTEX_EXIT(&call->lock);
5788 #else /* RX_ENABLE_LOCKS */
5789 if (rxi_CheckCall(call))
5791 #endif /* RX_ENABLE_LOCKS */
5793 /* Don't try to keep alive dallying calls */
5794 if (call->state == RX_STATE_DALLY) {
5795 MUTEX_EXIT(&call->lock);
5800 if ((now - call->lastSendTime) > rx_ConnSecondsUntilPing(conn)) {
5801 /* Don't try to send keepalives if there is unacknowledged data */
5802 /* the rexmit code should be good enough, this little hack
5803 * doesn't quite work XXX */
5804 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5806 rxi_ScheduleKeepAliveEvent(call);
5807 MUTEX_EXIT(&call->lock);
5812 rxi_ScheduleKeepAliveEvent(register struct rx_call *call)
5814 if (!call->keepAliveEvent) {
5815 struct clock when, now;
5816 clock_GetTime(&now);
5818 when.sec += rx_ConnSecondsUntilPing(call->conn);
5819 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5820 call->keepAliveEvent =
5821 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5825 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5827 rxi_KeepAliveOn(register struct rx_call *call)
5829 /* Pretend last packet received was received now--i.e. if another
5830 * packet isn't received within the keep alive time, then the call
5831 * will die; Initialize last send time to the current time--even
5832 * if a packet hasn't been sent yet. This will guarantee that a
5833 * keep-alive is sent within the ping time */
5834 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5835 rxi_ScheduleKeepAliveEvent(call);
5838 /* This routine is called to send connection abort messages
5839 * that have been delayed to throttle looping clients. */
5841 rxi_SendDelayedConnAbort(struct rxevent *event,
5842 void *arg1, void *unused)
5844 struct rx_connection *conn = arg1;
5847 struct rx_packet *packet;
5849 MUTEX_ENTER(&conn->conn_data_lock);
5850 conn->delayedAbortEvent = NULL;
5851 error = htonl(rx_ConnError(conn));
5853 MUTEX_EXIT(&conn->conn_data_lock);
5854 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5857 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5858 RX_PACKET_TYPE_ABORT, (char *)&error,
5860 rxi_FreePacket(packet);
5864 /* This routine is called to send call abort messages
5865 * that have been delayed to throttle looping clients. */
5867 rxi_SendDelayedCallAbort(struct rxevent *event,
5868 void *arg1, void *dummy)
5870 struct rx_call *call = arg1;
5873 struct rx_packet *packet;
5875 MUTEX_ENTER(&call->lock);
5876 call->delayedAbortEvent = NULL;
5877 error = htonl(call->error);
5879 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5882 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5883 (char *)&error, sizeof(error), 0);
5884 rxi_FreePacket(packet);
5886 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5887 MUTEX_EXIT(&call->lock);
5890 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5891 * seconds) to ask the client to authenticate itself. The routine
5892 * issues a challenge to the client, which is obtained from the
5893 * security object associated with the connection */
5895 rxi_ChallengeEvent(struct rxevent *event,
5896 void *arg0, void *arg1, int tries)
5898 struct rx_connection *conn = arg0;
5900 conn->challengeEvent = NULL;
5901 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5902 register struct rx_packet *packet;
5903 struct clock when, now;
5906 /* We've failed to authenticate for too long.
5907 * Reset any calls waiting for authentication;
5908 * they are all in RX_STATE_PRECALL.
5912 MUTEX_ENTER(&conn->conn_call_lock);
5913 for (i = 0; i < RX_MAXCALLS; i++) {
5914 struct rx_call *call = conn->call[i];
5916 MUTEX_ENTER(&call->lock);
5917 if (call->state == RX_STATE_PRECALL) {
5918 rxi_CallError(call, RX_CALL_DEAD);
5919 rxi_SendCallAbort(call, NULL, 0, 0);
5921 MUTEX_EXIT(&call->lock);
5924 MUTEX_EXIT(&conn->conn_call_lock);
5928 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5930 /* If there's no packet available, do this later. */
5931 RXS_GetChallenge(conn->securityObject, conn, packet);
5932 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5933 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5934 rxi_FreePacket(packet);
5936 clock_GetTime(&now);
5938 when.sec += RX_CHALLENGE_TIMEOUT;
5939 conn->challengeEvent =
5940 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5945 /* Call this routine to start requesting the client to authenticate
5946 * itself. This will continue until authentication is established,
5947 * the call times out, or an invalid response is returned. The
5948 * security object associated with the connection is asked to create
5949 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5950 * defined earlier. */
5952 rxi_ChallengeOn(register struct rx_connection *conn)
5954 if (!conn->challengeEvent) {
5955 RXS_CreateChallenge(conn->securityObject, conn);
5956 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5961 /* Compute round trip time of the packet provided, in *rttp.
5964 /* rxi_ComputeRoundTripTime is called with peer locked. */
5965 /* sentp and/or peer may be null */
5967 rxi_ComputeRoundTripTime(register struct rx_packet *p,
5968 register struct clock *sentp,
5969 register struct rx_peer *peer)
5971 struct clock thisRtt, *rttp = &thisRtt;
5973 register int rtt_timeout;
5975 clock_GetTime(rttp);
5977 if (clock_Lt(rttp, sentp)) {
5979 return; /* somebody set the clock back, don't count this time. */
5981 clock_Sub(rttp, sentp);
5982 if (rx_stats_active) {
5983 MUTEX_ENTER(&rx_stats_mutex);
5984 if (clock_Lt(rttp, &rx_stats.minRtt))
5985 rx_stats.minRtt = *rttp;
5986 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5987 if (rttp->sec > 60) {
5988 MUTEX_EXIT(&rx_stats_mutex);
5989 return; /* somebody set the clock ahead */
5991 rx_stats.maxRtt = *rttp;
5993 clock_Add(&rx_stats.totalRtt, rttp);
5994 rx_stats.nRttSamples++;
5995 MUTEX_EXIT(&rx_stats_mutex);
5998 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6000 /* Apply VanJacobson round-trip estimations */
6005 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6006 * srtt is stored as fixed point with 3 bits after the binary
6007 * point (i.e., scaled by 8). The following magic is
6008 * equivalent to the smoothing algorithm in rfc793 with an
6009 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6010 * srtt*8 = srtt*8 + rtt - srtt
6011 * srtt = srtt + rtt/8 - srtt/8
6014 delta = MSEC(rttp) - (peer->rtt >> 3);
6018 * We accumulate a smoothed rtt variance (actually, a smoothed
6019 * mean difference), then set the retransmit timer to smoothed
6020 * rtt + 4 times the smoothed variance (was 2x in van's original
6021 * paper, but 4x works better for me, and apparently for him as
6023 * rttvar is stored as
6024 * fixed point with 2 bits after the binary point (scaled by
6025 * 4). The following is equivalent to rfc793 smoothing with
6026 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
6027 * replaces rfc793's wired-in beta.
6028 * dev*4 = dev*4 + (|actual - expected| - dev)
6034 delta -= (peer->rtt_dev >> 2);
6035 peer->rtt_dev += delta;
6037 /* I don't have a stored RTT so I start with this value. Since I'm
6038 * probably just starting a call, and will be pushing more data down
6039 * this, I expect congestion to increase rapidly. So I fudge a
6040 * little, and I set deviance to half the rtt. In practice,
6041 * deviance tends to approach something a little less than
6042 * half the smoothed rtt. */
6043 peer->rtt = (MSEC(rttp) << 3) + 8;
6044 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6046 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
6047 * the other of these connections is usually in a user process, and can
6048 * be switched and/or swapped out. So on fast, reliable networks, the
6049 * timeout would otherwise be too short.
6051 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
6052 clock_Zero(&(peer->timeout));
6053 clock_Addmsec(&(peer->timeout), rtt_timeout);
6055 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)));
6059 /* Find all server connections that have not been active for a long time, and
6062 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6064 struct clock now, when;
6065 clock_GetTime(&now);
6067 /* Find server connection structures that haven't been used for
6068 * greater than rx_idleConnectionTime */
6070 struct rx_connection **conn_ptr, **conn_end;
6071 int i, havecalls = 0;
6072 MUTEX_ENTER(&rx_connHashTable_lock);
6073 for (conn_ptr = &rx_connHashTable[0], conn_end =
6074 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6076 struct rx_connection *conn, *next;
6077 struct rx_call *call;
6081 for (conn = *conn_ptr; conn; conn = next) {
6082 /* XXX -- Shouldn't the connection be locked? */
6085 for (i = 0; i < RX_MAXCALLS; i++) {
6086 call = conn->call[i];
6089 MUTEX_ENTER(&call->lock);
6090 #ifdef RX_ENABLE_LOCKS
6091 result = rxi_CheckCall(call, 1);
6092 #else /* RX_ENABLE_LOCKS */
6093 result = rxi_CheckCall(call);
6094 #endif /* RX_ENABLE_LOCKS */
6095 MUTEX_EXIT(&call->lock);
6097 /* If CheckCall freed the call, it might
6098 * have destroyed the connection as well,
6099 * which screws up the linked lists.
6105 if (conn->type == RX_SERVER_CONNECTION) {
6106 /* This only actually destroys the connection if
6107 * there are no outstanding calls */
6108 MUTEX_ENTER(&conn->conn_data_lock);
6109 if (!havecalls && !conn->refCount
6110 && ((conn->lastSendTime + rx_idleConnectionTime) <
6112 conn->refCount++; /* it will be decr in rx_DestroyConn */
6113 MUTEX_EXIT(&conn->conn_data_lock);
6114 #ifdef RX_ENABLE_LOCKS
6115 rxi_DestroyConnectionNoLock(conn);
6116 #else /* RX_ENABLE_LOCKS */
6117 rxi_DestroyConnection(conn);
6118 #endif /* RX_ENABLE_LOCKS */
6120 #ifdef RX_ENABLE_LOCKS
6122 MUTEX_EXIT(&conn->conn_data_lock);
6124 #endif /* RX_ENABLE_LOCKS */
6128 #ifdef RX_ENABLE_LOCKS
6129 while (rx_connCleanup_list) {
6130 struct rx_connection *conn;
6131 conn = rx_connCleanup_list;
6132 rx_connCleanup_list = rx_connCleanup_list->next;
6133 MUTEX_EXIT(&rx_connHashTable_lock);
6134 rxi_CleanupConnection(conn);
6135 MUTEX_ENTER(&rx_connHashTable_lock);
6137 MUTEX_EXIT(&rx_connHashTable_lock);
6138 #endif /* RX_ENABLE_LOCKS */
6141 /* Find any peer structures that haven't been used (haven't had an
6142 * associated connection) for greater than rx_idlePeerTime */
6144 struct rx_peer **peer_ptr, **peer_end;
6146 MUTEX_ENTER(&rx_rpc_stats);
6147 MUTEX_ENTER(&rx_peerHashTable_lock);
6148 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6149 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6151 struct rx_peer *peer, *next, *prev;
6152 for (prev = peer = *peer_ptr; peer; peer = next) {
6154 code = MUTEX_TRYENTER(&peer->peer_lock);
6155 if ((code) && (peer->refCount == 0)
6156 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6157 rx_interface_stat_p rpc_stat, nrpc_stat;
6159 MUTEX_EXIT(&peer->peer_lock);
6160 MUTEX_DESTROY(&peer->peer_lock);
6162 (&peer->rpcStats, rpc_stat, nrpc_stat,
6163 rx_interface_stat)) {
6164 unsigned int num_funcs;
6167 queue_Remove(&rpc_stat->queue_header);
6168 queue_Remove(&rpc_stat->all_peers);
6169 num_funcs = rpc_stat->stats[0].func_total;
6171 sizeof(rx_interface_stat_t) +
6172 rpc_stat->stats[0].func_total *
6173 sizeof(rx_function_entry_v1_t);
6175 rxi_Free(rpc_stat, space);
6176 rxi_rpc_peer_stat_cnt -= num_funcs;
6179 if (rx_stats_active)
6180 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6181 if (peer == *peer_ptr) {
6188 MUTEX_EXIT(&peer->peer_lock);
6194 MUTEX_EXIT(&rx_peerHashTable_lock);
6195 MUTEX_EXIT(&rx_rpc_stats);
6198 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6199 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6200 * GC, just below. Really, we shouldn't have to keep moving packets from
6201 * one place to another, but instead ought to always know if we can
6202 * afford to hold onto a packet in its particular use. */
6203 MUTEX_ENTER(&rx_freePktQ_lock);
6204 if (rx_waitingForPackets) {
6205 rx_waitingForPackets = 0;
6206 #ifdef RX_ENABLE_LOCKS
6207 CV_BROADCAST(&rx_waitingForPackets_cv);
6209 osi_rxWakeup(&rx_waitingForPackets);
6212 MUTEX_EXIT(&rx_freePktQ_lock);
6215 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6216 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6220 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6221 * rx.h is sort of strange this is better. This is called with a security
6222 * object before it is discarded. Each connection using a security object has
6223 * its own refcount to the object so it won't actually be freed until the last
6224 * connection is destroyed.
6226 * This is the only rxs module call. A hold could also be written but no one
6230 rxs_Release(struct rx_securityClass *aobj)
6232 return RXS_Close(aobj);
6236 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6237 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6238 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6239 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6241 /* Adjust our estimate of the transmission rate to this peer, given
6242 * that the packet p was just acked. We can adjust peer->timeout and
6243 * call->twind. Pragmatically, this is called
6244 * only with packets of maximal length.
6245 * Called with peer and call locked.
6249 rxi_ComputeRate(register struct rx_peer *peer, register struct rx_call *call,
6250 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6252 afs_int32 xferSize, xferMs;
6253 register afs_int32 minTime;
6256 /* Count down packets */
6257 if (peer->rateFlag > 0)
6259 /* Do nothing until we're enabled */
6260 if (peer->rateFlag != 0)
6265 /* Count only when the ack seems legitimate */
6266 switch (ackReason) {
6267 case RX_ACK_REQUESTED:
6269 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6273 case RX_ACK_PING_RESPONSE:
6274 if (p) /* want the response to ping-request, not data send */
6276 clock_GetTime(&newTO);
6277 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6278 clock_Sub(&newTO, &call->pingRequestTime);
6279 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6283 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6290 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));
6292 /* Track only packets that are big enough. */
6293 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6297 /* absorb RTT data (in milliseconds) for these big packets */
6298 if (peer->smRtt == 0) {
6299 peer->smRtt = xferMs;
6301 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6306 if (peer->countDown) {
6310 peer->countDown = 10; /* recalculate only every so often */
6312 /* In practice, we can measure only the RTT for full packets,
6313 * because of the way Rx acks the data that it receives. (If it's
6314 * smaller than a full packet, it often gets implicitly acked
6315 * either by the call response (from a server) or by the next call
6316 * (from a client), and either case confuses transmission times
6317 * with processing times.) Therefore, replace the above
6318 * more-sophisticated processing with a simpler version, where the
6319 * smoothed RTT is kept for full-size packets, and the time to
6320 * transmit a windowful of full-size packets is simply RTT *
6321 * windowSize. Again, we take two steps:
6322 - ensure the timeout is large enough for a single packet's RTT;
6323 - ensure that the window is small enough to fit in the desired timeout.*/
6325 /* First, the timeout check. */
6326 minTime = peer->smRtt;
6327 /* Get a reasonable estimate for a timeout period */
6329 newTO.sec = minTime / 1000;
6330 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6332 /* Increase the timeout period so that we can always do at least
6333 * one packet exchange */
6334 if (clock_Gt(&newTO, &peer->timeout)) {
6336 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));
6338 peer->timeout = newTO;
6341 /* Now, get an estimate for the transmit window size. */
6342 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6343 /* Now, convert to the number of full packets that could fit in a
6344 * reasonable fraction of that interval */
6345 minTime /= (peer->smRtt << 1);
6346 xferSize = minTime; /* (make a copy) */
6348 /* Now clamp the size to reasonable bounds. */
6351 else if (minTime > rx_Window)
6352 minTime = rx_Window;
6353 /* if (minTime != peer->maxWindow) {
6354 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6355 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6356 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6358 peer->maxWindow = minTime;
6359 elide... call->twind = minTime;
6363 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6364 * Discern this by calculating the timeout necessary for rx_Window
6366 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6367 /* calculate estimate for transmission interval in milliseconds */
6368 minTime = rx_Window * peer->smRtt;
6369 if (minTime < 1000) {
6370 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
6371 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6372 peer->timeout.usec, peer->smRtt, peer->packetSize));
6374 newTO.sec = 0; /* cut back on timeout by half a second */
6375 newTO.usec = 500000;
6376 clock_Sub(&peer->timeout, &newTO);
6381 } /* end of rxi_ComputeRate */
6382 #endif /* ADAPT_WINDOW */
6390 #define TRACE_OPTION_RX_DEBUG 16
6398 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6399 0, KEY_QUERY_VALUE, &parmKey);
6400 if (code != ERROR_SUCCESS)
6403 dummyLen = sizeof(TraceOption);
6404 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6405 (BYTE *) &TraceOption, &dummyLen);
6406 if (code == ERROR_SUCCESS) {
6407 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6409 RegCloseKey (parmKey);
6410 #endif /* AFS_NT40_ENV */
6415 rx_DebugOnOff(int on)
6419 rxdebug_active = on;
6425 rx_StatsOnOff(int on)
6428 rx_stats_active = on;
6433 /* Don't call this debugging routine directly; use dpf */
6435 rxi_DebugPrint(char *format, ...)
6444 va_start(ap, format);
6446 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6449 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6451 if (msg[len-1] != '\n') {
6455 OutputDebugString(msg);
6462 va_start(ap, format);
6464 clock_GetTime(&now);
6465 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
6466 (unsigned int)now.usec / 1000);
6467 vfprintf(rx_Log, format, ap);
6476 * This function is used to process the rx_stats structure that is local
6477 * to a process as well as an rx_stats structure received from a remote
6478 * process (via rxdebug). Therefore, it needs to do minimal version
6482 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6483 afs_int32 freePackets, char version)
6488 if (size != sizeof(struct rx_statistics)) {
6490 "Unexpected size of stats structure: was %d, expected %lud\n",
6491 size, sizeof(struct rx_statistics));
6494 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6497 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6498 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
6499 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6500 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6501 s->specialPktAllocFailures);
6503 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
6504 s->receivePktAllocFailures, s->sendPktAllocFailures,
6505 s->specialPktAllocFailures);
6509 " greedy %d, " "bogusReads %d (last from host %x), "
6510 "noPackets %d, " "noBuffers %d, " "selects %d, "
6511 "sendSelects %d\n", s->socketGreedy, s->bogusPacketOnRead,
6512 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6513 s->selects, s->sendSelects);
6515 fprintf(file, " packets read: ");
6516 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6517 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsRead[i]);
6519 fprintf(file, "\n");
6522 " other read counters: data %d, " "ack %d, " "dup %d "
6523 "spurious %d " "dally %d\n", s->dataPacketsRead,
6524 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6525 s->ignorePacketDally);
6527 fprintf(file, " packets sent: ");
6528 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6529 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsSent[i]);
6531 fprintf(file, "\n");
6534 " other send counters: ack %d, " "data %d (not resends), "
6535 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6536 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6537 s->dataPacketsPushed, s->ignoreAckedPacket);
6540 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6541 s->netSendFailures, (int)s->fatalErrors);
6543 if (s->nRttSamples) {
6544 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6545 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6547 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6548 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6552 " %d server connections, " "%d client connections, "
6553 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6554 s->nServerConns, s->nClientConns, s->nPeerStructs,
6555 s->nCallStructs, s->nFreeCallStructs);
6557 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6558 fprintf(file, " %d clock updates\n", clock_nUpdates);
6561 fprintf(file, "ERROR: compiled without RXDEBUG\n");
6565 /* for backward compatibility */
6567 rx_PrintStats(FILE * file)
6569 MUTEX_ENTER(&rx_stats_mutex);
6570 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6572 MUTEX_EXIT(&rx_stats_mutex);
6576 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6578 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6579 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6580 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6583 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6584 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6585 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6588 " Packet size %d, " "max in packet skew %d, "
6589 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6590 (int)peer->outPacketSkew);
6594 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
6596 * This mutex protects the following static variables:
6600 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
6601 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
6603 #define LOCK_RX_DEBUG
6604 #define UNLOCK_RX_DEBUG
6605 #endif /* AFS_PTHREAD_ENV */
6609 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6610 u_char type, void *inputData, size_t inputLength,
6611 void *outputData, size_t outputLength)
6613 static afs_int32 counter = 100;
6614 time_t waitTime, waitCount, startTime;
6615 struct rx_header theader;
6617 register afs_int32 code;
6618 struct timeval tv_now, tv_wake, tv_delta;
6619 struct sockaddr_in taddr, faddr;
6628 startTime = time(0);
6634 tp = &tbuffer[sizeof(struct rx_header)];
6635 taddr.sin_family = AF_INET;
6636 taddr.sin_port = remotePort;
6637 taddr.sin_addr.s_addr = remoteAddr;
6638 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6639 taddr.sin_len = sizeof(struct sockaddr_in);
6642 memset(&theader, 0, sizeof(theader));
6643 theader.epoch = htonl(999);
6645 theader.callNumber = htonl(counter);
6648 theader.type = type;
6649 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6650 theader.serviceId = 0;
6652 memcpy(tbuffer, &theader, sizeof(theader));
6653 memcpy(tp, inputData, inputLength);
6655 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6656 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6658 /* see if there's a packet available */
6659 gettimeofday(&tv_wake,0);
6660 tv_wake.tv_sec += waitTime;
6663 FD_SET(socket, &imask);
6664 tv_delta.tv_sec = tv_wake.tv_sec;
6665 tv_delta.tv_usec = tv_wake.tv_usec;
6666 gettimeofday(&tv_now, 0);
6668 if (tv_delta.tv_usec < tv_now.tv_usec) {
6670 tv_delta.tv_usec += 1000000;
6673 tv_delta.tv_usec -= tv_now.tv_usec;
6675 if (tv_delta.tv_sec < tv_now.tv_sec) {
6679 tv_delta.tv_sec -= tv_now.tv_sec;
6681 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6682 if (code == 1 && FD_ISSET(socket, &imask)) {
6683 /* now receive a packet */
6684 faddrLen = sizeof(struct sockaddr_in);
6686 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6687 (struct sockaddr *)&faddr, &faddrLen);
6690 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6691 if (counter == ntohl(theader.callNumber))
6699 /* see if we've timed out */
6707 code -= sizeof(struct rx_header);
6708 if (code > outputLength)
6709 code = outputLength;
6710 memcpy(outputData, tp, code);
6713 #endif /* RXDEBUG */
6716 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6717 afs_uint16 remotePort, struct rx_debugStats * stat,
6718 afs_uint32 * supportedValues)
6724 struct rx_debugIn in;
6726 *supportedValues = 0;
6727 in.type = htonl(RX_DEBUGI_GETSTATS);
6730 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6731 &in, sizeof(in), stat, sizeof(*stat));
6734 * If the call was successful, fixup the version and indicate
6735 * what contents of the stat structure are valid.
6736 * Also do net to host conversion of fields here.
6740 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6741 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6743 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6744 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6746 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6747 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6749 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6750 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6752 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6753 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6755 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6756 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6758 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6759 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6761 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6762 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6764 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6765 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6767 stat->nFreePackets = ntohl(stat->nFreePackets);
6768 stat->packetReclaims = ntohl(stat->packetReclaims);
6769 stat->callsExecuted = ntohl(stat->callsExecuted);
6770 stat->nWaiting = ntohl(stat->nWaiting);
6771 stat->idleThreads = ntohl(stat->idleThreads);
6772 stat->nWaited = ntohl(stat->nWaited);
6773 stat->nPackets = ntohl(stat->nPackets);
6780 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6781 afs_uint16 remotePort, struct rx_statistics * stat,
6782 afs_uint32 * supportedValues)
6788 struct rx_debugIn in;
6790 afs_int32 *lp = (afs_int32 *) stat;
6793 * supportedValues is currently unused, but added to allow future
6794 * versioning of this function.
6797 *supportedValues = 0;
6798 in.type = htonl(RX_DEBUGI_RXSTATS);
6800 memset(stat, 0, sizeof(*stat));
6802 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6803 &in, sizeof(in), stat, sizeof(*stat));
6808 * Do net to host conversion here
6811 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6820 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6821 afs_uint16 remotePort, size_t version_length,
6826 return MakeDebugCall(socket, remoteAddr, remotePort,
6827 RX_PACKET_TYPE_VERSION, a, 1, version,
6835 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6836 afs_uint16 remotePort, afs_int32 * nextConnection,
6837 int allConnections, afs_uint32 debugSupportedValues,
6838 struct rx_debugConn * conn,
6839 afs_uint32 * supportedValues)
6845 struct rx_debugIn in;
6849 * supportedValues is currently unused, but added to allow future
6850 * versioning of this function.
6853 *supportedValues = 0;
6854 if (allConnections) {
6855 in.type = htonl(RX_DEBUGI_GETALLCONN);
6857 in.type = htonl(RX_DEBUGI_GETCONN);
6859 in.index = htonl(*nextConnection);
6860 memset(conn, 0, sizeof(*conn));
6862 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6863 &in, sizeof(in), conn, sizeof(*conn));
6866 *nextConnection += 1;
6869 * Convert old connection format to new structure.
6872 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6873 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6874 #define MOVEvL(a) (conn->a = vL->a)
6876 /* any old or unrecognized version... */
6877 for (i = 0; i < RX_MAXCALLS; i++) {
6878 MOVEvL(callState[i]);
6879 MOVEvL(callMode[i]);
6880 MOVEvL(callFlags[i]);
6881 MOVEvL(callOther[i]);
6883 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6884 MOVEvL(secStats.type);
6885 MOVEvL(secStats.level);
6886 MOVEvL(secStats.flags);
6887 MOVEvL(secStats.expires);
6888 MOVEvL(secStats.packetsReceived);
6889 MOVEvL(secStats.packetsSent);
6890 MOVEvL(secStats.bytesReceived);
6891 MOVEvL(secStats.bytesSent);
6896 * Do net to host conversion here
6898 * I don't convert host or port since we are most likely
6899 * going to want these in NBO.
6901 conn->cid = ntohl(conn->cid);
6902 conn->serial = ntohl(conn->serial);
6903 for (i = 0; i < RX_MAXCALLS; i++) {
6904 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6906 rx_SetConnError(conn, ntohl(rx_ConnError(conn)));
6907 conn->secStats.flags = ntohl(conn->secStats.flags);
6908 conn->secStats.expires = ntohl(conn->secStats.expires);
6909 conn->secStats.packetsReceived =
6910 ntohl(conn->secStats.packetsReceived);
6911 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6912 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6913 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6914 conn->epoch = ntohl(conn->epoch);
6915 conn->natMTU = ntohl(conn->natMTU);
6922 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6923 afs_uint16 remotePort, afs_int32 * nextPeer,
6924 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6925 afs_uint32 * supportedValues)
6931 struct rx_debugIn in;
6934 * supportedValues is currently unused, but added to allow future
6935 * versioning of this function.
6938 *supportedValues = 0;
6939 in.type = htonl(RX_DEBUGI_GETPEER);
6940 in.index = htonl(*nextPeer);
6941 memset(peer, 0, sizeof(*peer));
6943 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6944 &in, sizeof(in), peer, sizeof(*peer));
6950 * Do net to host conversion here
6952 * I don't convert host or port since we are most likely
6953 * going to want these in NBO.
6955 peer->ifMTU = ntohs(peer->ifMTU);
6956 peer->idleWhen = ntohl(peer->idleWhen);
6957 peer->refCount = ntohs(peer->refCount);
6958 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6959 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6960 peer->rtt = ntohl(peer->rtt);
6961 peer->rtt_dev = ntohl(peer->rtt_dev);
6962 peer->timeout.sec = ntohl(peer->timeout.sec);
6963 peer->timeout.usec = ntohl(peer->timeout.usec);
6964 peer->nSent = ntohl(peer->nSent);
6965 peer->reSends = ntohl(peer->reSends);
6966 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6967 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6968 peer->rateFlag = ntohl(peer->rateFlag);
6969 peer->natMTU = ntohs(peer->natMTU);
6970 peer->maxMTU = ntohs(peer->maxMTU);
6971 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6972 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
6973 peer->MTU = ntohs(peer->MTU);
6974 peer->cwind = ntohs(peer->cwind);
6975 peer->nDgramPackets = ntohs(peer->nDgramPackets);
6976 peer->congestSeq = ntohs(peer->congestSeq);
6977 peer->bytesSent.high = ntohl(peer->bytesSent.high);
6978 peer->bytesSent.low = ntohl(peer->bytesSent.low);
6979 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
6980 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
6989 struct rx_serverQueueEntry *np;
6992 register struct rx_call *call;
6993 register struct rx_serverQueueEntry *sq;
6997 if (rxinit_status == 1) {
6999 return; /* Already shutdown. */
7003 #ifndef AFS_PTHREAD_ENV
7004 FD_ZERO(&rx_selectMask);
7005 #endif /* AFS_PTHREAD_ENV */
7006 rxi_dataQuota = RX_MAX_QUOTA;
7007 #ifndef AFS_PTHREAD_ENV
7009 #endif /* AFS_PTHREAD_ENV */
7012 #ifndef AFS_PTHREAD_ENV
7013 #ifndef AFS_USE_GETTIMEOFDAY
7015 #endif /* AFS_USE_GETTIMEOFDAY */
7016 #endif /* AFS_PTHREAD_ENV */
7018 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7019 call = queue_First(&rx_freeCallQueue, rx_call);
7021 rxi_Free(call, sizeof(struct rx_call));
7024 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7025 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7031 struct rx_peer **peer_ptr, **peer_end;
7032 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7033 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7035 struct rx_peer *peer, *next;
7036 for (peer = *peer_ptr; peer; peer = next) {
7037 rx_interface_stat_p rpc_stat, nrpc_stat;
7040 (&peer->rpcStats, rpc_stat, nrpc_stat,
7041 rx_interface_stat)) {
7042 unsigned int num_funcs;
7045 queue_Remove(&rpc_stat->queue_header);
7046 queue_Remove(&rpc_stat->all_peers);
7047 num_funcs = rpc_stat->stats[0].func_total;
7049 sizeof(rx_interface_stat_t) +
7050 rpc_stat->stats[0].func_total *
7051 sizeof(rx_function_entry_v1_t);
7053 rxi_Free(rpc_stat, space);
7054 rx_MutexAdd(rxi_rpc_peer_stat_cnt, -num_funcs, rx_rpc_stats);
7058 if (rx_stats_active)
7059 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7063 for (i = 0; i < RX_MAX_SERVICES; i++) {
7065 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7067 for (i = 0; i < rx_hashTableSize; i++) {
7068 register struct rx_connection *tc, *ntc;
7069 MUTEX_ENTER(&rx_connHashTable_lock);
7070 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7072 for (j = 0; j < RX_MAXCALLS; j++) {
7074 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7077 rxi_Free(tc, sizeof(*tc));
7079 MUTEX_EXIT(&rx_connHashTable_lock);
7082 MUTEX_ENTER(&freeSQEList_lock);
7084 while ((np = rx_FreeSQEList)) {
7085 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7086 MUTEX_DESTROY(&np->lock);
7087 rxi_Free(np, sizeof(*np));
7090 MUTEX_EXIT(&freeSQEList_lock);
7091 MUTEX_DESTROY(&freeSQEList_lock);
7092 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7093 MUTEX_DESTROY(&rx_connHashTable_lock);
7094 MUTEX_DESTROY(&rx_peerHashTable_lock);
7095 MUTEX_DESTROY(&rx_serverPool_lock);
7097 osi_Free(rx_connHashTable,
7098 rx_hashTableSize * sizeof(struct rx_connection *));
7099 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7101 UNPIN(rx_connHashTable,
7102 rx_hashTableSize * sizeof(struct rx_connection *));
7103 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7105 rxi_FreeAllPackets();
7107 MUTEX_ENTER(&rx_quota_mutex);
7108 rxi_dataQuota = RX_MAX_QUOTA;
7109 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7110 MUTEX_EXIT(&rx_quota_mutex);
7115 #ifdef RX_ENABLE_LOCKS
7117 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7119 if (!MUTEX_ISMINE(lockaddr))
7120 osi_Panic("Lock not held: %s", msg);
7122 #endif /* RX_ENABLE_LOCKS */
7127 * Routines to implement connection specific data.
7131 rx_KeyCreate(rx_destructor_t rtn)
7134 MUTEX_ENTER(&rxi_keyCreate_lock);
7135 key = rxi_keyCreate_counter++;
7136 rxi_keyCreate_destructor = (rx_destructor_t *)
7137 realloc((void *)rxi_keyCreate_destructor,
7138 (key + 1) * sizeof(rx_destructor_t));
7139 rxi_keyCreate_destructor[key] = rtn;
7140 MUTEX_EXIT(&rxi_keyCreate_lock);
7145 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7148 struct rx_connection *tconn =
7149 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7151 MUTEX_ENTER(&tconn->conn_data_lock);
7152 if (!tconn->specific) {
7153 tconn->specific = (void **)malloc((key + 1) * sizeof(void *));
7154 for (i = 0; i < key; i++)
7155 tconn->specific[i] = NULL;
7156 tconn->nSpecific = key + 1;
7157 tconn->specific[key] = ptr;
7158 } else if (key >= tconn->nSpecific) {
7159 tconn->specific = (void **)
7160 realloc(tconn->specific, (key + 1) * sizeof(void *));
7161 for (i = tconn->nSpecific; i < key; i++)
7162 tconn->specific[i] = NULL;
7163 tconn->nSpecific = key + 1;
7164 tconn->specific[key] = ptr;
7166 if (tconn->specific[key] && rxi_keyCreate_destructor[key])
7167 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7168 tconn->specific[key] = ptr;
7170 MUTEX_EXIT(&tconn->conn_data_lock);
7174 rx_GetSpecific(struct rx_connection *conn, int key)
7177 struct rx_connection *tconn =
7178 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7180 MUTEX_ENTER(&tconn->conn_data_lock);
7181 if (key >= tconn->nSpecific)
7184 ptr = tconn->specific[key];
7185 MUTEX_EXIT(&tconn->conn_data_lock);
7189 #endif /* !KERNEL */
7192 * processStats is a queue used to store the statistics for the local
7193 * process. Its contents are similar to the contents of the rpcStats
7194 * queue on a rx_peer structure, but the actual data stored within
7195 * this queue contains totals across the lifetime of the process (assuming
7196 * the stats have not been reset) - unlike the per peer structures
7197 * which can come and go based upon the peer lifetime.
7200 static struct rx_queue processStats = { &processStats, &processStats };
7203 * peerStats is a queue used to store the statistics for all peer structs.
7204 * Its contents are the union of all the peer rpcStats queues.
7207 static struct rx_queue peerStats = { &peerStats, &peerStats };
7210 * rxi_monitor_processStats is used to turn process wide stat collection
7214 static int rxi_monitor_processStats = 0;
7217 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7220 static int rxi_monitor_peerStats = 0;
7223 * rxi_AddRpcStat - given all of the information for a particular rpc
7224 * call, create (if needed) and update the stat totals for the rpc.
7228 * IN stats - the queue of stats that will be updated with the new value
7230 * IN rxInterface - a unique number that identifies the rpc interface
7232 * IN currentFunc - the index of the function being invoked
7234 * IN totalFunc - the total number of functions in this interface
7236 * IN queueTime - the amount of time this function waited for a thread
7238 * IN execTime - the amount of time this function invocation took to execute
7240 * IN bytesSent - the number bytes sent by this invocation
7242 * IN bytesRcvd - the number bytes received by this invocation
7244 * IN isServer - if true, this invocation was made to a server
7246 * IN remoteHost - the ip address of the remote host
7248 * IN remotePort - the port of the remote host
7250 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7252 * INOUT counter - if a new stats structure is allocated, the counter will
7253 * be updated with the new number of allocated stat structures
7261 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7262 afs_uint32 currentFunc, afs_uint32 totalFunc,
7263 struct clock *queueTime, struct clock *execTime,
7264 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7265 afs_uint32 remoteHost, afs_uint32 remotePort,
7266 int addToPeerList, unsigned int *counter)
7269 rx_interface_stat_p rpc_stat, nrpc_stat;
7272 * See if there's already a structure for this interface
7275 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7276 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7277 && (rpc_stat->stats[0].remote_is_server == isServer))
7282 * Didn't find a match so allocate a new structure and add it to the
7286 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7287 || (rpc_stat->stats[0].interfaceId != rxInterface)
7288 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7293 sizeof(rx_interface_stat_t) +
7294 totalFunc * sizeof(rx_function_entry_v1_t);
7296 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7297 if (rpc_stat == NULL) {
7301 *counter += totalFunc;
7302 for (i = 0; i < totalFunc; i++) {
7303 rpc_stat->stats[i].remote_peer = remoteHost;
7304 rpc_stat->stats[i].remote_port = remotePort;
7305 rpc_stat->stats[i].remote_is_server = isServer;
7306 rpc_stat->stats[i].interfaceId = rxInterface;
7307 rpc_stat->stats[i].func_total = totalFunc;
7308 rpc_stat->stats[i].func_index = i;
7309 hzero(rpc_stat->stats[i].invocations);
7310 hzero(rpc_stat->stats[i].bytes_sent);
7311 hzero(rpc_stat->stats[i].bytes_rcvd);
7312 rpc_stat->stats[i].queue_time_sum.sec = 0;
7313 rpc_stat->stats[i].queue_time_sum.usec = 0;
7314 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7315 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7316 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7317 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7318 rpc_stat->stats[i].queue_time_max.sec = 0;
7319 rpc_stat->stats[i].queue_time_max.usec = 0;
7320 rpc_stat->stats[i].execution_time_sum.sec = 0;
7321 rpc_stat->stats[i].execution_time_sum.usec = 0;
7322 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7323 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7324 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7325 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7326 rpc_stat->stats[i].execution_time_max.sec = 0;
7327 rpc_stat->stats[i].execution_time_max.usec = 0;
7329 queue_Prepend(stats, rpc_stat);
7330 if (addToPeerList) {
7331 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7336 * Increment the stats for this function
7339 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7340 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7341 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7342 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7343 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7344 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7345 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7347 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7348 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7350 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7351 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7353 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7354 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7356 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7357 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7365 * rx_IncrementTimeAndCount - increment the times and count for a particular
7370 * IN peer - the peer who invoked the rpc
7372 * IN rxInterface - a unique number that identifies the rpc interface
7374 * IN currentFunc - the index of the function being invoked
7376 * IN totalFunc - the total number of functions in this interface
7378 * IN queueTime - the amount of time this function waited for a thread
7380 * IN execTime - the amount of time this function invocation took to execute
7382 * IN bytesSent - the number bytes sent by this invocation
7384 * IN bytesRcvd - the number bytes received by this invocation
7386 * IN isServer - if true, this invocation was made to a server
7394 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7395 afs_uint32 currentFunc, afs_uint32 totalFunc,
7396 struct clock *queueTime, struct clock *execTime,
7397 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7401 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7404 MUTEX_ENTER(&rx_rpc_stats);
7405 MUTEX_ENTER(&peer->peer_lock);
7407 if (rxi_monitor_peerStats) {
7408 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7409 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7410 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7413 if (rxi_monitor_processStats) {
7414 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7415 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7416 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7419 MUTEX_EXIT(&peer->peer_lock);
7420 MUTEX_EXIT(&rx_rpc_stats);
7425 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7429 * IN callerVersion - the rpc stat version of the caller.
7431 * IN count - the number of entries to marshall.
7433 * IN stats - pointer to stats to be marshalled.
7435 * OUT ptr - Where to store the marshalled data.
7442 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7443 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7449 * We only support the first version
7451 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7452 *(ptr++) = stats->remote_peer;
7453 *(ptr++) = stats->remote_port;
7454 *(ptr++) = stats->remote_is_server;
7455 *(ptr++) = stats->interfaceId;
7456 *(ptr++) = stats->func_total;
7457 *(ptr++) = stats->func_index;
7458 *(ptr++) = hgethi(stats->invocations);
7459 *(ptr++) = hgetlo(stats->invocations);
7460 *(ptr++) = hgethi(stats->bytes_sent);
7461 *(ptr++) = hgetlo(stats->bytes_sent);
7462 *(ptr++) = hgethi(stats->bytes_rcvd);
7463 *(ptr++) = hgetlo(stats->bytes_rcvd);
7464 *(ptr++) = stats->queue_time_sum.sec;
7465 *(ptr++) = stats->queue_time_sum.usec;
7466 *(ptr++) = stats->queue_time_sum_sqr.sec;
7467 *(ptr++) = stats->queue_time_sum_sqr.usec;
7468 *(ptr++) = stats->queue_time_min.sec;
7469 *(ptr++) = stats->queue_time_min.usec;
7470 *(ptr++) = stats->queue_time_max.sec;
7471 *(ptr++) = stats->queue_time_max.usec;
7472 *(ptr++) = stats->execution_time_sum.sec;
7473 *(ptr++) = stats->execution_time_sum.usec;
7474 *(ptr++) = stats->execution_time_sum_sqr.sec;
7475 *(ptr++) = stats->execution_time_sum_sqr.usec;
7476 *(ptr++) = stats->execution_time_min.sec;
7477 *(ptr++) = stats->execution_time_min.usec;
7478 *(ptr++) = stats->execution_time_max.sec;
7479 *(ptr++) = stats->execution_time_max.usec;
7485 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7490 * IN callerVersion - the rpc stat version of the caller
7492 * OUT myVersion - the rpc stat version of this function
7494 * OUT clock_sec - local time seconds
7496 * OUT clock_usec - local time microseconds
7498 * OUT allocSize - the number of bytes allocated to contain stats
7500 * OUT statCount - the number stats retrieved from this process.
7502 * OUT stats - the actual stats retrieved from this process.
7506 * Returns void. If successful, stats will != NULL.
7510 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7511 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7512 size_t * allocSize, afs_uint32 * statCount,
7513 afs_uint32 ** stats)
7523 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7526 * Check to see if stats are enabled
7529 MUTEX_ENTER(&rx_rpc_stats);
7530 if (!rxi_monitor_processStats) {
7531 MUTEX_EXIT(&rx_rpc_stats);
7535 clock_GetTime(&now);
7536 *clock_sec = now.sec;
7537 *clock_usec = now.usec;
7540 * Allocate the space based upon the caller version
7542 * If the client is at an older version than we are,
7543 * we return the statistic data in the older data format, but
7544 * we still return our version number so the client knows we
7545 * are maintaining more data than it can retrieve.
7548 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7549 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7550 *statCount = rxi_rpc_process_stat_cnt;
7553 * This can't happen yet, but in the future version changes
7554 * can be handled by adding additional code here
7558 if (space > (size_t) 0) {
7560 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7563 rx_interface_stat_p rpc_stat, nrpc_stat;
7567 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7569 * Copy the data based upon the caller version
7571 rx_MarshallProcessRPCStats(callerVersion,
7572 rpc_stat->stats[0].func_total,
7573 rpc_stat->stats, &ptr);
7579 MUTEX_EXIT(&rx_rpc_stats);
7584 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7588 * IN callerVersion - the rpc stat version of the caller
7590 * OUT myVersion - the rpc stat version of this function
7592 * OUT clock_sec - local time seconds
7594 * OUT clock_usec - local time microseconds
7596 * OUT allocSize - the number of bytes allocated to contain stats
7598 * OUT statCount - the number of stats retrieved from the individual
7601 * OUT stats - the actual stats retrieved from the individual peer structures.
7605 * Returns void. If successful, stats will != NULL.
7609 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7610 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7611 size_t * allocSize, afs_uint32 * statCount,
7612 afs_uint32 ** stats)
7622 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7625 * Check to see if stats are enabled
7628 MUTEX_ENTER(&rx_rpc_stats);
7629 if (!rxi_monitor_peerStats) {
7630 MUTEX_EXIT(&rx_rpc_stats);
7634 clock_GetTime(&now);
7635 *clock_sec = now.sec;
7636 *clock_usec = now.usec;
7639 * Allocate the space based upon the caller version
7641 * If the client is at an older version than we are,
7642 * we return the statistic data in the older data format, but
7643 * we still return our version number so the client knows we
7644 * are maintaining more data than it can retrieve.
7647 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7648 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7649 *statCount = rxi_rpc_peer_stat_cnt;
7652 * This can't happen yet, but in the future version changes
7653 * can be handled by adding additional code here
7657 if (space > (size_t) 0) {
7659 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7662 rx_interface_stat_p rpc_stat, nrpc_stat;
7666 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7668 * We have to fix the offset of rpc_stat since we are
7669 * keeping this structure on two rx_queues. The rx_queue
7670 * package assumes that the rx_queue member is the first
7671 * member of the structure. That is, rx_queue assumes that
7672 * any one item is only on one queue at a time. We are
7673 * breaking that assumption and so we have to do a little
7674 * math to fix our pointers.
7677 fix_offset = (char *)rpc_stat;
7678 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7679 rpc_stat = (rx_interface_stat_p) fix_offset;
7682 * Copy the data based upon the caller version
7684 rx_MarshallProcessRPCStats(callerVersion,
7685 rpc_stat->stats[0].func_total,
7686 rpc_stat->stats, &ptr);
7692 MUTEX_EXIT(&rx_rpc_stats);
7697 * rx_FreeRPCStats - free memory allocated by
7698 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7702 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7703 * rx_RetrievePeerRPCStats
7705 * IN allocSize - the number of bytes in stats.
7713 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7715 rxi_Free(stats, allocSize);
7719 * rx_queryProcessRPCStats - see if process rpc stat collection is
7720 * currently enabled.
7726 * Returns 0 if stats are not enabled != 0 otherwise
7730 rx_queryProcessRPCStats(void)
7733 MUTEX_ENTER(&rx_rpc_stats);
7734 rc = rxi_monitor_processStats;
7735 MUTEX_EXIT(&rx_rpc_stats);
7740 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7746 * Returns 0 if stats are not enabled != 0 otherwise
7750 rx_queryPeerRPCStats(void)
7753 MUTEX_ENTER(&rx_rpc_stats);
7754 rc = rxi_monitor_peerStats;
7755 MUTEX_EXIT(&rx_rpc_stats);
7760 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7770 rx_enableProcessRPCStats(void)
7772 MUTEX_ENTER(&rx_rpc_stats);
7773 rx_enable_stats = 1;
7774 rxi_monitor_processStats = 1;
7775 MUTEX_EXIT(&rx_rpc_stats);
7779 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7789 rx_enablePeerRPCStats(void)
7791 MUTEX_ENTER(&rx_rpc_stats);
7792 rx_enable_stats = 1;
7793 rxi_monitor_peerStats = 1;
7794 MUTEX_EXIT(&rx_rpc_stats);
7798 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7808 rx_disableProcessRPCStats(void)
7810 rx_interface_stat_p rpc_stat, nrpc_stat;
7813 MUTEX_ENTER(&rx_rpc_stats);
7816 * Turn off process statistics and if peer stats is also off, turn
7820 rxi_monitor_processStats = 0;
7821 if (rxi_monitor_peerStats == 0) {
7822 rx_enable_stats = 0;
7825 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7826 unsigned int num_funcs = 0;
7829 queue_Remove(rpc_stat);
7830 num_funcs = rpc_stat->stats[0].func_total;
7832 sizeof(rx_interface_stat_t) +
7833 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7835 rxi_Free(rpc_stat, space);
7836 rxi_rpc_process_stat_cnt -= num_funcs;
7838 MUTEX_EXIT(&rx_rpc_stats);
7842 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7852 rx_disablePeerRPCStats(void)
7854 struct rx_peer **peer_ptr, **peer_end;
7857 MUTEX_ENTER(&rx_rpc_stats);
7860 * Turn off peer statistics and if process stats is also off, turn
7864 rxi_monitor_peerStats = 0;
7865 if (rxi_monitor_processStats == 0) {
7866 rx_enable_stats = 0;
7869 MUTEX_ENTER(&rx_peerHashTable_lock);
7870 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7871 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7873 struct rx_peer *peer, *next, *prev;
7874 for (prev = peer = *peer_ptr; peer; peer = next) {
7876 code = MUTEX_TRYENTER(&peer->peer_lock);
7878 rx_interface_stat_p rpc_stat, nrpc_stat;
7881 (&peer->rpcStats, rpc_stat, nrpc_stat,
7882 rx_interface_stat)) {
7883 unsigned int num_funcs = 0;
7886 queue_Remove(&rpc_stat->queue_header);
7887 queue_Remove(&rpc_stat->all_peers);
7888 num_funcs = rpc_stat->stats[0].func_total;
7890 sizeof(rx_interface_stat_t) +
7891 rpc_stat->stats[0].func_total *
7892 sizeof(rx_function_entry_v1_t);
7894 rxi_Free(rpc_stat, space);
7895 rxi_rpc_peer_stat_cnt -= num_funcs;
7897 MUTEX_EXIT(&peer->peer_lock);
7898 if (prev == *peer_ptr) {
7908 MUTEX_EXIT(&rx_peerHashTable_lock);
7909 MUTEX_EXIT(&rx_rpc_stats);
7913 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7918 * IN clearFlag - flag indicating which stats to clear
7926 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7928 rx_interface_stat_p rpc_stat, nrpc_stat;
7930 MUTEX_ENTER(&rx_rpc_stats);
7932 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7933 unsigned int num_funcs = 0, i;
7934 num_funcs = rpc_stat->stats[0].func_total;
7935 for (i = 0; i < num_funcs; i++) {
7936 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7937 hzero(rpc_stat->stats[i].invocations);
7939 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7940 hzero(rpc_stat->stats[i].bytes_sent);
7942 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7943 hzero(rpc_stat->stats[i].bytes_rcvd);
7945 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7946 rpc_stat->stats[i].queue_time_sum.sec = 0;
7947 rpc_stat->stats[i].queue_time_sum.usec = 0;
7949 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7950 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7951 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7953 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7954 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7955 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7957 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7958 rpc_stat->stats[i].queue_time_max.sec = 0;
7959 rpc_stat->stats[i].queue_time_max.usec = 0;
7961 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7962 rpc_stat->stats[i].execution_time_sum.sec = 0;
7963 rpc_stat->stats[i].execution_time_sum.usec = 0;
7965 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7966 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7967 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7969 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7970 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7971 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7973 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7974 rpc_stat->stats[i].execution_time_max.sec = 0;
7975 rpc_stat->stats[i].execution_time_max.usec = 0;
7980 MUTEX_EXIT(&rx_rpc_stats);
7984 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
7989 * IN clearFlag - flag indicating which stats to clear
7997 rx_clearPeerRPCStats(afs_uint32 clearFlag)
7999 rx_interface_stat_p rpc_stat, nrpc_stat;
8001 MUTEX_ENTER(&rx_rpc_stats);
8003 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8004 unsigned int num_funcs = 0, i;
8007 * We have to fix the offset of rpc_stat since we are
8008 * keeping this structure on two rx_queues. The rx_queue
8009 * package assumes that the rx_queue member is the first
8010 * member of the structure. That is, rx_queue assumes that
8011 * any one item is only on one queue at a time. We are
8012 * breaking that assumption and so we have to do a little
8013 * math to fix our pointers.
8016 fix_offset = (char *)rpc_stat;
8017 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8018 rpc_stat = (rx_interface_stat_p) fix_offset;
8020 num_funcs = rpc_stat->stats[0].func_total;
8021 for (i = 0; i < num_funcs; i++) {
8022 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8023 hzero(rpc_stat->stats[i].invocations);
8025 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8026 hzero(rpc_stat->stats[i].bytes_sent);
8028 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8029 hzero(rpc_stat->stats[i].bytes_rcvd);
8031 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8032 rpc_stat->stats[i].queue_time_sum.sec = 0;
8033 rpc_stat->stats[i].queue_time_sum.usec = 0;
8035 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8036 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8037 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8039 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8040 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8041 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8043 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8044 rpc_stat->stats[i].queue_time_max.sec = 0;
8045 rpc_stat->stats[i].queue_time_max.usec = 0;
8047 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8048 rpc_stat->stats[i].execution_time_sum.sec = 0;
8049 rpc_stat->stats[i].execution_time_sum.usec = 0;
8051 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8052 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8053 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8055 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8056 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8057 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8059 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8060 rpc_stat->stats[i].execution_time_max.sec = 0;
8061 rpc_stat->stats[i].execution_time_max.usec = 0;
8066 MUTEX_EXIT(&rx_rpc_stats);
8070 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8071 * is authorized to enable/disable/clear RX statistics.
8073 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8076 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8078 rxi_rxstat_userok = proc;
8082 rx_RxStatUserOk(struct rx_call *call)
8084 if (!rxi_rxstat_userok)
8086 return rxi_rxstat_userok(call);
8091 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8092 * function in the MSVC runtime DLL (msvcrt.dll).
8094 * Note: the system serializes calls to this function.
8097 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8098 DWORD reason, /* reason function is being called */
8099 LPVOID reserved) /* reserved for future use */
8102 case DLL_PROCESS_ATTACH:
8103 /* library is being attached to a process */
8107 case DLL_PROCESS_DETACH:
8116 int rx_DumpCalls(FILE *outputFile, char *cookie)
8118 #ifdef RXDEBUG_PACKET
8120 #ifdef KDUMP_RX_LOCK
8121 struct rx_call_rx_lock *c;
8127 sprintf(output, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8128 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8130 for (c = rx_allCallsp; c; c = c->allNextp) {
8131 u_short rqc, tqc, iovqc;
8132 struct rx_packet *p, *np;
8134 MUTEX_ENTER(&c->lock);
8135 queue_Count(&c->rq, p, np, rx_packet, rqc);
8136 queue_Count(&c->tq, p, np, rx_packet, tqc);
8137 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8139 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, "
8140 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8141 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8142 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8143 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8144 #ifdef RX_ENABLE_LOCKS
8147 #ifdef RX_REFCOUNT_CHECK
8148 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8149 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8152 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,
8153 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8154 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8155 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8156 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8157 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8158 #ifdef RX_ENABLE_LOCKS
8159 , (afs_uint32)c->refCount
8161 #ifdef RX_REFCOUNT_CHECK
8162 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8165 MUTEX_EXIT(&c->lock);
8167 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8169 sprintf(output, "%s - End dumping all Rx Calls\r\n", cookie);
8170 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8171 #endif /* RXDEBUG_PACKET */
8174 #endif /* AFS_NT40_ENV */