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>
21 #include "afs/sysincludes.h"
22 #include "afsincludes.h"
28 #include <net/net_globals.h>
29 #endif /* AFS_OSF_ENV */
30 #ifdef AFS_LINUX20_ENV
33 #include "netinet/in.h"
35 #include "inet/common.h"
37 #include "inet/ip_ire.h"
39 #include "afs/afs_args.h"
40 #include "afs/afs_osi.h"
41 #ifdef RX_KERNEL_TRACE
42 #include "rx_kcommon.h"
44 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
48 #undef RXDEBUG /* turn off debugging */
50 #if defined(AFS_SGI_ENV)
51 #include "sys/debug.h"
60 #endif /* AFS_OSF_ENV */
62 #include "afs/sysincludes.h"
63 #include "afsincludes.h"
66 #include "rx_kmutex.h"
67 #include "rx_kernel.h"
71 #include "rx_globals.h"
73 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
74 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
75 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
77 extern afs_int32 afs_termState;
79 #include "sys/lockl.h"
80 #include "sys/lock_def.h"
81 #endif /* AFS_AIX41_ENV */
82 # include "rxgen_consts.h"
84 # include <sys/types.h>
91 # include <afs/afsutil.h>
92 # include <WINNT\afsreg.h>
94 # include <sys/socket.h>
95 # include <sys/file.h>
97 # include <sys/stat.h>
98 # include <netinet/in.h>
99 # include <sys/time.h>
102 # include "rx_user.h"
103 # include "rx_clock.h"
104 # include "rx_queue.h"
105 # include "rx_globals.h"
106 # include "rx_trace.h"
107 # include <afs/rxgen_consts.h>
111 #ifdef AFS_PTHREAD_ENV
113 int (*registerProgram) (pid_t, char *) = 0;
114 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
117 int (*registerProgram) (PROCESS, char *) = 0;
118 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
122 /* Local static routines */
123 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
124 #ifdef RX_ENABLE_LOCKS
125 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
128 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
130 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
131 afs_int32 rxi_start_in_error;
133 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
136 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
137 * currently allocated within rx. This number is used to allocate the
138 * memory required to return the statistics when queried.
141 static unsigned int rxi_rpc_peer_stat_cnt;
144 * rxi_rpc_process_stat_cnt counts the total number of local process stat
145 * structures currently allocated within rx. The number is used to allocate
146 * the memory required to return the statistics when queried.
149 static unsigned int rxi_rpc_process_stat_cnt;
151 #if !defined(offsetof)
152 #include <stddef.h> /* for definition of offsetof() */
155 #ifdef AFS_PTHREAD_ENV
159 * Use procedural initialization of mutexes/condition variables
163 extern afs_kmutex_t rx_stats_mutex;
164 extern afs_kmutex_t rx_waiting_mutex;
165 extern afs_kmutex_t rx_quota_mutex;
166 extern afs_kmutex_t rx_pthread_mutex;
167 extern afs_kmutex_t rx_packets_mutex;
168 extern afs_kmutex_t des_init_mutex;
169 extern afs_kmutex_t des_random_mutex;
170 extern afs_kmutex_t rx_clock_mutex;
171 extern afs_kmutex_t rxi_connCacheMutex;
172 extern afs_kmutex_t rx_event_mutex;
173 extern afs_kmutex_t osi_malloc_mutex;
174 extern afs_kmutex_t event_handler_mutex;
175 extern afs_kmutex_t listener_mutex;
176 extern afs_kmutex_t rx_if_init_mutex;
177 extern afs_kmutex_t rx_if_mutex;
178 extern afs_kmutex_t rxkad_client_uid_mutex;
179 extern afs_kmutex_t rxkad_random_mutex;
181 extern afs_kcondvar_t rx_event_handler_cond;
182 extern afs_kcondvar_t rx_listener_cond;
184 static afs_kmutex_t epoch_mutex;
185 static afs_kmutex_t rx_init_mutex;
186 static afs_kmutex_t rx_debug_mutex;
187 static afs_kmutex_t rx_rpc_stats;
190 rxi_InitPthread(void)
192 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
193 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
194 MUTEX_INIT(&rx_waiting_mutex, "waiting", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
213 assert(pthread_cond_init
214 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
215 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
217 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
218 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
220 rxkad_global_stats_init();
222 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
224 #ifdef RX_ENABLE_LOCKS
227 #endif /* RX_LOCKS_DB */
228 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
229 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
231 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
233 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
235 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
237 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
238 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
239 #endif /* RX_ENABLE_LOCKS */
242 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
243 #define INIT_PTHREAD_LOCKS \
244 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
246 * The rx_stats_mutex mutex protects the following global variables:
247 * rxi_lowConnRefCount
248 * rxi_lowPeerRefCount
257 * The rx_quota_mutex mutex protects the following global variables:
265 * The rx_freePktQ_lock protects the following global variables:
270 * The rx_packets_mutex mutex protects the following global variables:
278 * The rx_pthread_mutex mutex protects the following global variables:
282 #define INIT_PTHREAD_LOCKS
286 /* Variables for handling the minProcs implementation. availProcs gives the
287 * number of threads available in the pool at this moment (not counting dudes
288 * executing right now). totalMin gives the total number of procs required
289 * for handling all minProcs requests. minDeficit is a dynamic variable
290 * tracking the # of procs required to satisfy all of the remaining minProcs
292 * For fine grain locking to work, the quota check and the reservation of
293 * a server thread has to come while rxi_availProcs and rxi_minDeficit
294 * are locked. To this end, the code has been modified under #ifdef
295 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
296 * same time. A new function, ReturnToServerPool() returns the allocation.
298 * A call can be on several queue's (but only one at a time). When
299 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
300 * that no one else is touching the queue. To this end, we store the address
301 * of the queue lock in the call structure (under the call lock) when we
302 * put the call on a queue, and we clear the call_queue_lock when the
303 * call is removed from a queue (once the call lock has been obtained).
304 * This allows rxi_ResetCall to safely synchronize with others wishing
305 * to manipulate the queue.
308 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
309 static afs_kmutex_t rx_rpc_stats;
310 void rxi_StartUnlocked(struct rxevent *event, void *call,
311 void *arg1, int istack);
314 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
315 ** pretty good that the next packet coming in is from the same connection
316 ** as the last packet, since we're send multiple packets in a transmit window.
318 struct rx_connection *rxLastConn = 0;
320 #ifdef RX_ENABLE_LOCKS
321 /* The locking hierarchy for rx fine grain locking is composed of these
324 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
325 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
326 * call->lock - locks call data fields.
327 * These are independent of each other:
328 * rx_freeCallQueue_lock
333 * serverQueueEntry->lock
335 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
336 * peer->lock - locks peer data fields.
337 * conn_data_lock - that more than one thread is not updating a conn data
338 * field at the same time.
346 * Do we need a lock to protect the peer field in the conn structure?
347 * conn->peer was previously a constant for all intents and so has no
348 * lock protecting this field. The multihomed client delta introduced
349 * a RX code change : change the peer field in the connection structure
350 * to that remote inetrface from which the last packet for this
351 * connection was sent out. This may become an issue if further changes
354 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
355 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
357 /* rxdb_fileID is used to identify the lock location, along with line#. */
358 static int rxdb_fileID = RXDB_FILE_RX;
359 #endif /* RX_LOCKS_DB */
360 #else /* RX_ENABLE_LOCKS */
361 #define SET_CALL_QUEUE_LOCK(C, L)
362 #define CLEAR_CALL_QUEUE_LOCK(C)
363 #endif /* RX_ENABLE_LOCKS */
364 struct rx_serverQueueEntry *rx_waitForPacket = 0;
365 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
367 /* ------------Exported Interfaces------------- */
369 /* This function allows rxkad to set the epoch to a suitably random number
370 * which rx_NewConnection will use in the future. The principle purpose is to
371 * get rxnull connections to use the same epoch as the rxkad connections do, at
372 * least once the first rxkad connection is established. This is important now
373 * that the host/port addresses aren't used in FindConnection: the uniqueness
374 * of epoch/cid matters and the start time won't do. */
376 #ifdef AFS_PTHREAD_ENV
378 * This mutex protects the following global variables:
382 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
383 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
387 #endif /* AFS_PTHREAD_ENV */
390 rx_SetEpoch(afs_uint32 epoch)
397 /* Initialize rx. A port number may be mentioned, in which case this
398 * becomes the default port number for any service installed later.
399 * If 0 is provided for the port number, a random port will be chosen
400 * by the kernel. Whether this will ever overlap anything in
401 * /etc/services is anybody's guess... Returns 0 on success, -1 on
406 int rxinit_status = 1;
407 #ifdef AFS_PTHREAD_ENV
409 * This mutex protects the following global variables:
413 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
414 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
417 #define UNLOCK_RX_INIT
421 rx_InitHost(u_int host, u_int port)
428 char *htable, *ptable;
435 if (rxinit_status == 0) {
436 tmp_status = rxinit_status;
438 return tmp_status; /* Already started; return previous error code. */
444 if (afs_winsockInit() < 0)
450 * Initialize anything necessary to provide a non-premptive threading
453 rxi_InitializeThreadSupport();
456 /* Allocate and initialize a socket for client and perhaps server
459 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
460 if (rx_socket == OSI_NULLSOCKET) {
464 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
467 #endif /* RX_LOCKS_DB */
468 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
469 MUTEX_INIT(&rx_waiting_mutex, "rx_waiting_mutex", MUTEX_DEFAULT, 0);
470 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
471 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
472 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
478 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
480 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
482 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
484 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
485 #if defined(AFS_HPUX110_ENV)
487 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
488 #endif /* AFS_HPUX110_ENV */
489 #endif /* RX_ENABLE_LOCKS && KERNEL */
492 rx_connDeadTime = 12;
493 rx_tranquil = 0; /* reset flag */
494 memset(&rx_stats, 0, sizeof(struct rx_statistics));
496 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
497 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
498 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
499 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
500 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
501 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
503 /* Malloc up a bunch of packets & buffers */
505 queue_Init(&rx_freePacketQueue);
506 rxi_NeedMorePackets = FALSE;
507 #ifdef RX_ENABLE_TSFPQ
508 rx_nPackets = 0; /* in TSFPQ version, rx_nPackets is managed by rxi_MorePackets* */
509 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
510 #else /* RX_ENABLE_TSFPQ */
511 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
512 rxi_MorePackets(rx_nPackets);
513 #endif /* RX_ENABLE_TSFPQ */
520 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
521 tv.tv_sec = clock_now.sec;
522 tv.tv_usec = clock_now.usec;
523 srand((unsigned int)tv.tv_usec);
530 #if defined(KERNEL) && !defined(UKERNEL)
531 /* Really, this should never happen in a real kernel */
534 struct sockaddr_in addr;
536 int addrlen = sizeof(addr);
538 socklen_t addrlen = sizeof(addr);
540 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
544 rx_port = addr.sin_port;
547 rx_stats.minRtt.sec = 9999999;
549 rx_SetEpoch(tv.tv_sec | 0x80000000);
551 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
552 * will provide a randomer value. */
554 MUTEX_ENTER(&rx_quota_mutex);
555 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
556 MUTEX_EXIT(&rx_quota_mutex);
557 /* *Slightly* random start time for the cid. This is just to help
558 * out with the hashing function at the peer */
559 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
560 rx_connHashTable = (struct rx_connection **)htable;
561 rx_peerHashTable = (struct rx_peer **)ptable;
563 rx_lastAckDelay.sec = 0;
564 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
565 rx_hardAckDelay.sec = 0;
566 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
567 rx_softAckDelay.sec = 0;
568 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
570 rxevent_Init(20, rxi_ReScheduleEvents);
572 /* Initialize various global queues */
573 queue_Init(&rx_idleServerQueue);
574 queue_Init(&rx_incomingCallQueue);
575 queue_Init(&rx_freeCallQueue);
577 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
578 /* Initialize our list of usable IP addresses. */
582 /* Start listener process (exact function is dependent on the
583 * implementation environment--kernel or user space) */
587 tmp_status = rxinit_status = 0;
595 return rx_InitHost(htonl(INADDR_ANY), port);
598 /* called with unincremented nRequestsRunning to see if it is OK to start
599 * a new thread in this service. Could be "no" for two reasons: over the
600 * max quota, or would prevent others from reaching their min quota.
602 #ifdef RX_ENABLE_LOCKS
603 /* This verion of QuotaOK reserves quota if it's ok while the
604 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
607 QuotaOK(struct rx_service *aservice)
609 /* check if over max quota */
610 if (aservice->nRequestsRunning >= aservice->maxProcs) {
614 /* under min quota, we're OK */
615 /* otherwise, can use only if there are enough to allow everyone
616 * to go to their min quota after this guy starts.
619 MUTEX_ENTER(&rx_quota_mutex);
620 if ((aservice->nRequestsRunning < aservice->minProcs)
621 || (rxi_availProcs > rxi_minDeficit)) {
622 aservice->nRequestsRunning++;
623 /* just started call in minProcs pool, need fewer to maintain
625 if (aservice->nRequestsRunning <= aservice->minProcs)
628 MUTEX_EXIT(&rx_quota_mutex);
631 MUTEX_EXIT(&rx_quota_mutex);
637 ReturnToServerPool(struct rx_service *aservice)
639 aservice->nRequestsRunning--;
640 MUTEX_ENTER(&rx_quota_mutex);
641 if (aservice->nRequestsRunning < aservice->minProcs)
644 MUTEX_EXIT(&rx_quota_mutex);
647 #else /* RX_ENABLE_LOCKS */
649 QuotaOK(struct rx_service *aservice)
652 /* under min quota, we're OK */
653 if (aservice->nRequestsRunning < aservice->minProcs)
656 /* check if over max quota */
657 if (aservice->nRequestsRunning >= aservice->maxProcs)
660 /* otherwise, can use only if there are enough to allow everyone
661 * to go to their min quota after this guy starts.
663 if (rxi_availProcs > rxi_minDeficit)
667 #endif /* RX_ENABLE_LOCKS */
670 /* Called by rx_StartServer to start up lwp's to service calls.
671 NExistingProcs gives the number of procs already existing, and which
672 therefore needn't be created. */
674 rxi_StartServerProcs(int nExistingProcs)
676 struct rx_service *service;
681 /* For each service, reserve N processes, where N is the "minimum"
682 * number of processes that MUST be able to execute a request in parallel,
683 * at any time, for that process. Also compute the maximum difference
684 * between any service's maximum number of processes that can run
685 * (i.e. the maximum number that ever will be run, and a guarantee
686 * that this number will run if other services aren't running), and its
687 * minimum number. The result is the extra number of processes that
688 * we need in order to provide the latter guarantee */
689 for (i = 0; i < RX_MAX_SERVICES; i++) {
691 service = rx_services[i];
692 if (service == (struct rx_service *)0)
694 nProcs += service->minProcs;
695 diff = service->maxProcs - service->minProcs;
699 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
700 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
701 for (i = 0; i < nProcs; i++) {
702 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
708 /* This routine is only required on Windows */
710 rx_StartClientThread(void)
712 #ifdef AFS_PTHREAD_ENV
714 pid = pthread_self();
715 #endif /* AFS_PTHREAD_ENV */
717 #endif /* AFS_NT40_ENV */
719 /* This routine must be called if any services are exported. If the
720 * donateMe flag is set, the calling process is donated to the server
723 rx_StartServer(int donateMe)
725 struct rx_service *service;
731 /* Start server processes, if necessary (exact function is dependent
732 * on the implementation environment--kernel or user space). DonateMe
733 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
734 * case, one less new proc will be created rx_StartServerProcs.
736 rxi_StartServerProcs(donateMe);
738 /* count up the # of threads in minProcs, and add set the min deficit to
739 * be that value, too.
741 for (i = 0; i < RX_MAX_SERVICES; i++) {
742 service = rx_services[i];
743 if (service == (struct rx_service *)0)
745 MUTEX_ENTER(&rx_quota_mutex);
746 rxi_totalMin += service->minProcs;
747 /* below works even if a thread is running, since minDeficit would
748 * still have been decremented and later re-incremented.
750 rxi_minDeficit += service->minProcs;
751 MUTEX_EXIT(&rx_quota_mutex);
754 /* Turn on reaping of idle server connections */
755 rxi_ReapConnections(NULL, NULL, NULL);
764 #ifdef AFS_PTHREAD_ENV
766 pid = afs_pointer_to_int(pthread_self());
767 #else /* AFS_PTHREAD_ENV */
769 LWP_CurrentProcess(&pid);
770 #endif /* AFS_PTHREAD_ENV */
772 sprintf(name, "srv_%d", ++nProcs);
774 (*registerProgram) (pid, name);
776 #endif /* AFS_NT40_ENV */
777 rx_ServerProc(NULL); /* Never returns */
779 #ifdef RX_ENABLE_TSFPQ
780 /* no use leaving packets around in this thread's local queue if
781 * it isn't getting donated to the server thread pool.
783 rxi_FlushLocalPacketsTSFPQ();
784 #endif /* RX_ENABLE_TSFPQ */
788 /* Create a new client connection to the specified service, using the
789 * specified security object to implement the security model for this
791 struct rx_connection *
792 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
793 struct rx_securityClass *securityObject,
794 int serviceSecurityIndex)
798 struct rx_connection *conn;
803 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n",
804 ntohl(shost), ntohs(sport), sservice, securityObject, serviceSecurityIndex));
806 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
807 * the case of kmem_alloc? */
808 conn = rxi_AllocConnection();
809 #ifdef RX_ENABLE_LOCKS
810 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
811 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
812 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
815 MUTEX_ENTER(&rx_connHashTable_lock);
816 cid = (rx_nextCid += RX_MAXCALLS);
817 conn->type = RX_CLIENT_CONNECTION;
819 conn->epoch = rx_epoch;
820 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
821 conn->serviceId = sservice;
822 conn->securityObject = securityObject;
823 conn->securityData = (void *) 0;
824 conn->securityIndex = serviceSecurityIndex;
825 rx_SetConnDeadTime(conn, rx_connDeadTime);
826 conn->ackRate = RX_FAST_ACK_RATE;
828 conn->specific = NULL;
829 conn->challengeEvent = NULL;
830 conn->delayedAbortEvent = NULL;
831 conn->abortCount = 0;
833 for (i = 0; i < RX_MAXCALLS; i++) {
834 conn->twind[i] = rx_initSendWindow;
835 conn->rwind[i] = rx_initReceiveWindow;
838 RXS_NewConnection(securityObject, conn);
840 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
842 conn->refCount++; /* no lock required since only this thread knows... */
843 conn->next = rx_connHashTable[hashindex];
844 rx_connHashTable[hashindex] = conn;
846 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
847 MUTEX_EXIT(&rx_connHashTable_lock);
853 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
855 /* The idea is to set the dead time to a value that allows several
856 * keepalives to be dropped without timing out the connection. */
857 conn->secondsUntilDead = MAX(seconds, 6);
858 conn->secondsUntilPing = conn->secondsUntilDead / 6;
861 int rxi_lowPeerRefCount = 0;
862 int rxi_lowConnRefCount = 0;
865 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
866 * NOTE: must not be called with rx_connHashTable_lock held.
869 rxi_CleanupConnection(struct rx_connection *conn)
871 /* Notify the service exporter, if requested, that this connection
872 * is being destroyed */
873 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
874 (*conn->service->destroyConnProc) (conn);
876 /* Notify the security module that this connection is being destroyed */
877 RXS_DestroyConnection(conn->securityObject, conn);
879 /* If this is the last connection using the rx_peer struct, set its
880 * idle time to now. rxi_ReapConnections will reap it if it's still
881 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
883 MUTEX_ENTER(&rx_peerHashTable_lock);
884 if (conn->peer->refCount < 2) {
885 conn->peer->idleWhen = clock_Sec();
886 if (conn->peer->refCount < 1) {
887 conn->peer->refCount = 1;
888 if (rx_stats_active) {
889 MUTEX_ENTER(&rx_stats_mutex);
890 rxi_lowPeerRefCount++;
891 MUTEX_EXIT(&rx_stats_mutex);
895 conn->peer->refCount--;
896 MUTEX_EXIT(&rx_peerHashTable_lock);
900 if (conn->type == RX_SERVER_CONNECTION)
901 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
903 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
906 if (conn->specific) {
908 for (i = 0; i < conn->nSpecific; i++) {
909 if (conn->specific[i] && rxi_keyCreate_destructor[i])
910 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
911 conn->specific[i] = NULL;
913 free(conn->specific);
915 conn->specific = NULL;
919 MUTEX_DESTROY(&conn->conn_call_lock);
920 MUTEX_DESTROY(&conn->conn_data_lock);
921 CV_DESTROY(&conn->conn_call_cv);
923 rxi_FreeConnection(conn);
926 /* Destroy the specified connection */
928 rxi_DestroyConnection(struct rx_connection *conn)
930 MUTEX_ENTER(&rx_connHashTable_lock);
931 rxi_DestroyConnectionNoLock(conn);
932 /* conn should be at the head of the cleanup list */
933 if (conn == rx_connCleanup_list) {
934 rx_connCleanup_list = rx_connCleanup_list->next;
935 MUTEX_EXIT(&rx_connHashTable_lock);
936 rxi_CleanupConnection(conn);
938 #ifdef RX_ENABLE_LOCKS
940 MUTEX_EXIT(&rx_connHashTable_lock);
942 #endif /* RX_ENABLE_LOCKS */
946 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
948 struct rx_connection **conn_ptr;
950 struct rx_packet *packet;
957 MUTEX_ENTER(&conn->conn_data_lock);
958 if (conn->refCount > 0)
961 if (rx_stats_active) {
962 MUTEX_ENTER(&rx_stats_mutex);
963 rxi_lowConnRefCount++;
964 MUTEX_EXIT(&rx_stats_mutex);
968 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
969 /* Busy; wait till the last guy before proceeding */
970 MUTEX_EXIT(&conn->conn_data_lock);
975 /* If the client previously called rx_NewCall, but it is still
976 * waiting, treat this as a running call, and wait to destroy the
977 * connection later when the call completes. */
978 if ((conn->type == RX_CLIENT_CONNECTION)
979 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
980 conn->flags |= RX_CONN_DESTROY_ME;
981 MUTEX_EXIT(&conn->conn_data_lock);
985 MUTEX_EXIT(&conn->conn_data_lock);
987 /* Check for extant references to this connection */
988 for (i = 0; i < RX_MAXCALLS; i++) {
989 struct rx_call *call = conn->call[i];
992 if (conn->type == RX_CLIENT_CONNECTION) {
993 MUTEX_ENTER(&call->lock);
994 if (call->delayedAckEvent) {
995 /* Push the final acknowledgment out now--there
996 * won't be a subsequent call to acknowledge the
997 * last reply packets */
998 rxevent_Cancel(call->delayedAckEvent, call,
999 RX_CALL_REFCOUNT_DELAY);
1000 if (call->state == RX_STATE_PRECALL
1001 || call->state == RX_STATE_ACTIVE) {
1002 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1004 rxi_AckAll(NULL, call, 0);
1007 MUTEX_EXIT(&call->lock);
1011 #ifdef RX_ENABLE_LOCKS
1013 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1014 MUTEX_EXIT(&conn->conn_data_lock);
1016 /* Someone is accessing a packet right now. */
1020 #endif /* RX_ENABLE_LOCKS */
1023 /* Don't destroy the connection if there are any call
1024 * structures still in use */
1025 MUTEX_ENTER(&conn->conn_data_lock);
1026 conn->flags |= RX_CONN_DESTROY_ME;
1027 MUTEX_EXIT(&conn->conn_data_lock);
1032 if (conn->delayedAbortEvent) {
1033 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1034 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1036 MUTEX_ENTER(&conn->conn_data_lock);
1037 rxi_SendConnectionAbort(conn, packet, 0, 1);
1038 MUTEX_EXIT(&conn->conn_data_lock);
1039 rxi_FreePacket(packet);
1043 /* Remove from connection hash table before proceeding */
1045 &rx_connHashTable[CONN_HASH
1046 (peer->host, peer->port, conn->cid, conn->epoch,
1048 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1049 if (*conn_ptr == conn) {
1050 *conn_ptr = conn->next;
1054 /* if the conn that we are destroying was the last connection, then we
1055 * clear rxLastConn as well */
1056 if (rxLastConn == conn)
1059 /* Make sure the connection is completely reset before deleting it. */
1060 /* get rid of pending events that could zap us later */
1061 if (conn->challengeEvent)
1062 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1063 if (conn->checkReachEvent)
1064 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1066 /* Add the connection to the list of destroyed connections that
1067 * need to be cleaned up. This is necessary to avoid deadlocks
1068 * in the routines we call to inform others that this connection is
1069 * being destroyed. */
1070 conn->next = rx_connCleanup_list;
1071 rx_connCleanup_list = conn;
1074 /* Externally available version */
1076 rx_DestroyConnection(struct rx_connection *conn)
1081 rxi_DestroyConnection(conn);
1086 rx_GetConnection(struct rx_connection *conn)
1091 MUTEX_ENTER(&conn->conn_data_lock);
1093 MUTEX_EXIT(&conn->conn_data_lock);
1097 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1098 /* Wait for the transmit queue to no longer be busy.
1099 * requires the call->lock to be held */
1100 static void rxi_WaitforTQBusy(struct rx_call *call) {
1101 while (call->flags & RX_CALL_TQ_BUSY) {
1102 call->flags |= RX_CALL_TQ_WAIT;
1104 #ifdef RX_ENABLE_LOCKS
1105 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1106 CV_WAIT(&call->cv_tq, &call->lock);
1107 #else /* RX_ENABLE_LOCKS */
1108 osi_rxSleep(&call->tq);
1109 #endif /* RX_ENABLE_LOCKS */
1111 if (call->tqWaiters == 0) {
1112 call->flags &= ~RX_CALL_TQ_WAIT;
1118 /* Start a new rx remote procedure call, on the specified connection.
1119 * If wait is set to 1, wait for a free call channel; otherwise return
1120 * 0. Maxtime gives the maximum number of seconds this call may take,
1121 * after rx_NewCall returns. After this time interval, a call to any
1122 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1123 * For fine grain locking, we hold the conn_call_lock in order to
1124 * to ensure that we don't get signalle after we found a call in an active
1125 * state and before we go to sleep.
1128 rx_NewCall(struct rx_connection *conn)
1131 struct rx_call *call;
1132 struct clock queueTime;
1136 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1139 clock_GetTime(&queueTime);
1140 MUTEX_ENTER(&conn->conn_call_lock);
1143 * Check if there are others waiting for a new call.
1144 * If so, let them go first to avoid starving them.
1145 * This is a fairly simple scheme, and might not be
1146 * a complete solution for large numbers of waiters.
1148 * makeCallWaiters keeps track of the number of
1149 * threads waiting to make calls and the
1150 * RX_CONN_MAKECALL_WAITING flag bit is used to
1151 * indicate that there are indeed calls waiting.
1152 * The flag is set when the waiter is incremented.
1153 * It is only cleared in rx_EndCall when
1154 * makeCallWaiters is 0. This prevents us from
1155 * accidently destroying the connection while it
1156 * is potentially about to be used.
1158 MUTEX_ENTER(&conn->conn_data_lock);
1159 if (conn->makeCallWaiters) {
1160 conn->flags |= RX_CONN_MAKECALL_WAITING;
1161 conn->makeCallWaiters++;
1162 MUTEX_EXIT(&conn->conn_data_lock);
1164 #ifdef RX_ENABLE_LOCKS
1165 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1169 MUTEX_ENTER(&conn->conn_data_lock);
1170 conn->makeCallWaiters--;
1172 MUTEX_EXIT(&conn->conn_data_lock);
1175 for (i = 0; i < RX_MAXCALLS; i++) {
1176 call = conn->call[i];
1178 MUTEX_ENTER(&call->lock);
1179 if (call->state == RX_STATE_DALLY) {
1180 rxi_ResetCall(call, 0);
1181 (*call->callNumber)++;
1184 MUTEX_EXIT(&call->lock);
1186 call = rxi_NewCall(conn, i);
1190 if (i < RX_MAXCALLS) {
1193 MUTEX_ENTER(&conn->conn_data_lock);
1194 conn->flags |= RX_CONN_MAKECALL_WAITING;
1195 conn->makeCallWaiters++;
1196 MUTEX_EXIT(&conn->conn_data_lock);
1198 #ifdef RX_ENABLE_LOCKS
1199 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1203 MUTEX_ENTER(&conn->conn_data_lock);
1204 conn->makeCallWaiters--;
1205 MUTEX_EXIT(&conn->conn_data_lock);
1208 * Wake up anyone else who might be giving us a chance to
1209 * run (see code above that avoids resource starvation).
1211 #ifdef RX_ENABLE_LOCKS
1212 CV_BROADCAST(&conn->conn_call_cv);
1217 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1219 /* Client is initially in send mode */
1220 call->state = RX_STATE_ACTIVE;
1221 call->error = conn->error;
1223 call->mode = RX_MODE_ERROR;
1225 call->mode = RX_MODE_SENDING;
1227 /* remember start time for call in case we have hard dead time limit */
1228 call->queueTime = queueTime;
1229 clock_GetTime(&call->startTime);
1230 hzero(call->bytesSent);
1231 hzero(call->bytesRcvd);
1233 /* Turn on busy protocol. */
1234 rxi_KeepAliveOn(call);
1236 MUTEX_EXIT(&call->lock);
1237 MUTEX_EXIT(&conn->conn_call_lock);
1240 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1241 /* Now, if TQ wasn't cleared earlier, do it now. */
1242 MUTEX_ENTER(&call->lock);
1243 rxi_WaitforTQBusy(call);
1244 if (call->flags & RX_CALL_TQ_CLEARME) {
1245 rxi_ClearTransmitQueue(call, 1);
1246 /*queue_Init(&call->tq);*/
1248 MUTEX_EXIT(&call->lock);
1249 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1251 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1256 rxi_HasActiveCalls(struct rx_connection *aconn)
1259 struct rx_call *tcall;
1263 for (i = 0; i < RX_MAXCALLS; i++) {
1264 if ((tcall = aconn->call[i])) {
1265 if ((tcall->state == RX_STATE_ACTIVE)
1266 || (tcall->state == RX_STATE_PRECALL)) {
1277 rxi_GetCallNumberVector(struct rx_connection *aconn,
1278 afs_int32 * aint32s)
1281 struct rx_call *tcall;
1285 for (i = 0; i < RX_MAXCALLS; i++) {
1286 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1287 aint32s[i] = aconn->callNumber[i] + 1;
1289 aint32s[i] = aconn->callNumber[i];
1296 rxi_SetCallNumberVector(struct rx_connection *aconn,
1297 afs_int32 * aint32s)
1300 struct rx_call *tcall;
1304 for (i = 0; i < RX_MAXCALLS; i++) {
1305 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1306 aconn->callNumber[i] = aint32s[i] - 1;
1308 aconn->callNumber[i] = aint32s[i];
1314 /* Advertise a new service. A service is named locally by a UDP port
1315 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1318 char *serviceName; Name for identification purposes (e.g. the
1319 service name might be used for probing for
1322 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1323 char *serviceName, struct rx_securityClass **securityObjects,
1324 int nSecurityObjects,
1325 afs_int32(*serviceProc) (struct rx_call * acall))
1327 osi_socket socket = OSI_NULLSOCKET;
1328 struct rx_service *tservice;
1334 if (serviceId == 0) {
1336 "rx_NewService: service id for service %s is not non-zero.\n",
1343 "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",
1351 tservice = rxi_AllocService();
1353 for (i = 0; i < RX_MAX_SERVICES; i++) {
1354 struct rx_service *service = rx_services[i];
1356 if (port == service->servicePort && host == service->serviceHost) {
1357 if (service->serviceId == serviceId) {
1358 /* The identical service has already been
1359 * installed; if the caller was intending to
1360 * change the security classes used by this
1361 * service, he/she loses. */
1363 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1364 serviceName, serviceId, service->serviceName);
1366 rxi_FreeService(tservice);
1369 /* Different service, same port: re-use the socket
1370 * which is bound to the same port */
1371 socket = service->socket;
1374 if (socket == OSI_NULLSOCKET) {
1375 /* If we don't already have a socket (from another
1376 * service on same port) get a new one */
1377 socket = rxi_GetHostUDPSocket(host, port);
1378 if (socket == OSI_NULLSOCKET) {
1380 rxi_FreeService(tservice);
1385 service->socket = socket;
1386 service->serviceHost = host;
1387 service->servicePort = port;
1388 service->serviceId = serviceId;
1389 service->serviceName = serviceName;
1390 service->nSecurityObjects = nSecurityObjects;
1391 service->securityObjects = securityObjects;
1392 service->minProcs = 0;
1393 service->maxProcs = 1;
1394 service->idleDeadTime = 60;
1395 service->idleDeadErr = 0;
1396 service->connDeadTime = rx_connDeadTime;
1397 service->executeRequestProc = serviceProc;
1398 service->checkReach = 0;
1399 rx_services[i] = service; /* not visible until now */
1405 rxi_FreeService(tservice);
1406 (osi_Msg "rx_NewService: cannot support > %d services\n",
1411 /* Set configuration options for all of a service's security objects */
1414 rx_SetSecurityConfiguration(struct rx_service *service,
1415 rx_securityConfigVariables type,
1419 for (i = 0; i<service->nSecurityObjects; i++) {
1420 if (service->securityObjects[i]) {
1421 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1429 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1430 struct rx_securityClass **securityObjects, int nSecurityObjects,
1431 afs_int32(*serviceProc) (struct rx_call * acall))
1433 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1436 /* Generic request processing loop. This routine should be called
1437 * by the implementation dependent rx_ServerProc. If socketp is
1438 * non-null, it will be set to the file descriptor that this thread
1439 * is now listening on. If socketp is null, this routine will never
1442 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1444 struct rx_call *call;
1446 struct rx_service *tservice = NULL;
1453 call = rx_GetCall(threadID, tservice, socketp);
1454 if (socketp && *socketp != OSI_NULLSOCKET) {
1455 /* We are now a listener thread */
1460 /* if server is restarting( typically smooth shutdown) then do not
1461 * allow any new calls.
1464 if (rx_tranquil && (call != NULL)) {
1468 MUTEX_ENTER(&call->lock);
1470 rxi_CallError(call, RX_RESTARTING);
1471 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1473 MUTEX_EXIT(&call->lock);
1477 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1478 #ifdef RX_ENABLE_LOCKS
1480 #endif /* RX_ENABLE_LOCKS */
1481 afs_termState = AFSOP_STOP_AFS;
1482 afs_osi_Wakeup(&afs_termState);
1483 #ifdef RX_ENABLE_LOCKS
1485 #endif /* RX_ENABLE_LOCKS */
1490 tservice = call->conn->service;
1492 if (tservice->beforeProc)
1493 (*tservice->beforeProc) (call);
1495 code = call->conn->service->executeRequestProc(call);
1497 if (tservice->afterProc)
1498 (*tservice->afterProc) (call, code);
1500 rx_EndCall(call, code);
1501 if (rx_stats_active) {
1502 MUTEX_ENTER(&rx_stats_mutex);
1504 MUTEX_EXIT(&rx_stats_mutex);
1511 rx_WakeupServerProcs(void)
1513 struct rx_serverQueueEntry *np, *tqp;
1517 MUTEX_ENTER(&rx_serverPool_lock);
1519 #ifdef RX_ENABLE_LOCKS
1520 if (rx_waitForPacket)
1521 CV_BROADCAST(&rx_waitForPacket->cv);
1522 #else /* RX_ENABLE_LOCKS */
1523 if (rx_waitForPacket)
1524 osi_rxWakeup(rx_waitForPacket);
1525 #endif /* RX_ENABLE_LOCKS */
1526 MUTEX_ENTER(&freeSQEList_lock);
1527 for (np = rx_FreeSQEList; np; np = tqp) {
1528 tqp = *(struct rx_serverQueueEntry **)np;
1529 #ifdef RX_ENABLE_LOCKS
1530 CV_BROADCAST(&np->cv);
1531 #else /* RX_ENABLE_LOCKS */
1533 #endif /* RX_ENABLE_LOCKS */
1535 MUTEX_EXIT(&freeSQEList_lock);
1536 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1537 #ifdef RX_ENABLE_LOCKS
1538 CV_BROADCAST(&np->cv);
1539 #else /* RX_ENABLE_LOCKS */
1541 #endif /* RX_ENABLE_LOCKS */
1543 MUTEX_EXIT(&rx_serverPool_lock);
1548 * One thing that seems to happen is that all the server threads get
1549 * tied up on some empty or slow call, and then a whole bunch of calls
1550 * arrive at once, using up the packet pool, so now there are more
1551 * empty calls. The most critical resources here are server threads
1552 * and the free packet pool. The "doreclaim" code seems to help in
1553 * general. I think that eventually we arrive in this state: there
1554 * are lots of pending calls which do have all their packets present,
1555 * so they won't be reclaimed, are multi-packet calls, so they won't
1556 * be scheduled until later, and thus are tying up most of the free
1557 * packet pool for a very long time.
1559 * 1. schedule multi-packet calls if all the packets are present.
1560 * Probably CPU-bound operation, useful to return packets to pool.
1561 * Do what if there is a full window, but the last packet isn't here?
1562 * 3. preserve one thread which *only* runs "best" calls, otherwise
1563 * it sleeps and waits for that type of call.
1564 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1565 * the current dataquota business is badly broken. The quota isn't adjusted
1566 * to reflect how many packets are presently queued for a running call.
1567 * So, when we schedule a queued call with a full window of packets queued
1568 * up for it, that *should* free up a window full of packets for other 2d-class
1569 * calls to be able to use from the packet pool. But it doesn't.
1571 * NB. Most of the time, this code doesn't run -- since idle server threads
1572 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1573 * as a new call arrives.
1575 /* Sleep until a call arrives. Returns a pointer to the call, ready
1576 * for an rx_Read. */
1577 #ifdef RX_ENABLE_LOCKS
1579 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1581 struct rx_serverQueueEntry *sq;
1582 struct rx_call *call = (struct rx_call *)0;
1583 struct rx_service *service = NULL;
1586 MUTEX_ENTER(&freeSQEList_lock);
1588 if ((sq = rx_FreeSQEList)) {
1589 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1590 MUTEX_EXIT(&freeSQEList_lock);
1591 } else { /* otherwise allocate a new one and return that */
1592 MUTEX_EXIT(&freeSQEList_lock);
1593 sq = (struct rx_serverQueueEntry *)
1594 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1595 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1596 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1599 MUTEX_ENTER(&rx_serverPool_lock);
1600 if (cur_service != NULL) {
1601 ReturnToServerPool(cur_service);
1604 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1605 struct rx_call *tcall, *ncall, *choice2 = NULL;
1607 /* Scan for eligible incoming calls. A call is not eligible
1608 * if the maximum number of calls for its service type are
1609 * already executing */
1610 /* One thread will process calls FCFS (to prevent starvation),
1611 * while the other threads may run ahead looking for calls which
1612 * have all their input data available immediately. This helps
1613 * keep threads from blocking, waiting for data from the client. */
1614 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1615 service = tcall->conn->service;
1616 if (!QuotaOK(service)) {
1619 MUTEX_ENTER(&rx_pthread_mutex);
1620 if (tno == rxi_fcfs_thread_num
1621 || !tcall->queue_item_header.next) {
1622 MUTEX_EXIT(&rx_pthread_mutex);
1623 /* If we're the fcfs thread , then we'll just use
1624 * this call. If we haven't been able to find an optimal
1625 * choice, and we're at the end of the list, then use a
1626 * 2d choice if one has been identified. Otherwise... */
1627 call = (choice2 ? choice2 : tcall);
1628 service = call->conn->service;
1630 MUTEX_EXIT(&rx_pthread_mutex);
1631 if (!queue_IsEmpty(&tcall->rq)) {
1632 struct rx_packet *rp;
1633 rp = queue_First(&tcall->rq, rx_packet);
1634 if (rp->header.seq == 1) {
1636 || (rp->header.flags & RX_LAST_PACKET)) {
1638 } else if (rxi_2dchoice && !choice2
1639 && !(tcall->flags & RX_CALL_CLEARED)
1640 && (tcall->rprev > rxi_HardAckRate)) {
1650 ReturnToServerPool(service);
1657 MUTEX_EXIT(&rx_serverPool_lock);
1658 MUTEX_ENTER(&call->lock);
1660 if (call->flags & RX_CALL_WAIT_PROC) {
1661 call->flags &= ~RX_CALL_WAIT_PROC;
1662 MUTEX_ENTER(&rx_waiting_mutex);
1664 MUTEX_EXIT(&rx_waiting_mutex);
1667 if (call->state != RX_STATE_PRECALL || call->error) {
1668 MUTEX_EXIT(&call->lock);
1669 MUTEX_ENTER(&rx_serverPool_lock);
1670 ReturnToServerPool(service);
1675 if (queue_IsEmpty(&call->rq)
1676 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1677 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1679 CLEAR_CALL_QUEUE_LOCK(call);
1682 /* If there are no eligible incoming calls, add this process
1683 * to the idle server queue, to wait for one */
1687 *socketp = OSI_NULLSOCKET;
1689 sq->socketp = socketp;
1690 queue_Append(&rx_idleServerQueue, sq);
1691 #ifndef AFS_AIX41_ENV
1692 rx_waitForPacket = sq;
1694 rx_waitingForPacket = sq;
1695 #endif /* AFS_AIX41_ENV */
1697 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1699 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1700 MUTEX_EXIT(&rx_serverPool_lock);
1701 return (struct rx_call *)0;
1704 } while (!(call = sq->newcall)
1705 && !(socketp && *socketp != OSI_NULLSOCKET));
1706 MUTEX_EXIT(&rx_serverPool_lock);
1708 MUTEX_ENTER(&call->lock);
1714 MUTEX_ENTER(&freeSQEList_lock);
1715 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1716 rx_FreeSQEList = sq;
1717 MUTEX_EXIT(&freeSQEList_lock);
1720 clock_GetTime(&call->startTime);
1721 call->state = RX_STATE_ACTIVE;
1722 call->mode = RX_MODE_RECEIVING;
1723 #ifdef RX_KERNEL_TRACE
1724 if (ICL_SETACTIVE(afs_iclSetp)) {
1725 int glockOwner = ISAFS_GLOCK();
1728 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1729 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1736 rxi_calltrace(RX_CALL_START, call);
1737 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1738 call->conn->service->servicePort, call->conn->service->serviceId,
1741 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1742 MUTEX_EXIT(&call->lock);
1744 dpf(("rx_GetCall(socketp=0x%"AFS_PTR_FMT", *socketp=0x%"AFS_PTR_FMT")\n", socketp, *socketp));
1749 #else /* RX_ENABLE_LOCKS */
1751 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1753 struct rx_serverQueueEntry *sq;
1754 struct rx_call *call = (struct rx_call *)0, *choice2;
1755 struct rx_service *service = NULL;
1759 MUTEX_ENTER(&freeSQEList_lock);
1761 if ((sq = rx_FreeSQEList)) {
1762 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1763 MUTEX_EXIT(&freeSQEList_lock);
1764 } else { /* otherwise allocate a new one and return that */
1765 MUTEX_EXIT(&freeSQEList_lock);
1766 sq = (struct rx_serverQueueEntry *)
1767 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1768 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1769 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1771 MUTEX_ENTER(&sq->lock);
1773 if (cur_service != NULL) {
1774 cur_service->nRequestsRunning--;
1775 if (cur_service->nRequestsRunning < cur_service->minProcs)
1779 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1780 struct rx_call *tcall, *ncall;
1781 /* Scan for eligible incoming calls. A call is not eligible
1782 * if the maximum number of calls for its service type are
1783 * already executing */
1784 /* One thread will process calls FCFS (to prevent starvation),
1785 * while the other threads may run ahead looking for calls which
1786 * have all their input data available immediately. This helps
1787 * keep threads from blocking, waiting for data from the client. */
1788 choice2 = (struct rx_call *)0;
1789 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1790 service = tcall->conn->service;
1791 if (QuotaOK(service)) {
1792 MUTEX_ENTER(&rx_pthread_mutex);
1793 if (tno == rxi_fcfs_thread_num
1794 || !tcall->queue_item_header.next) {
1795 MUTEX_EXIT(&rx_pthread_mutex);
1796 /* If we're the fcfs thread, then we'll just use
1797 * this call. If we haven't been able to find an optimal
1798 * choice, and we're at the end of the list, then use a
1799 * 2d choice if one has been identified. Otherwise... */
1800 call = (choice2 ? choice2 : tcall);
1801 service = call->conn->service;
1803 MUTEX_EXIT(&rx_pthread_mutex);
1804 if (!queue_IsEmpty(&tcall->rq)) {
1805 struct rx_packet *rp;
1806 rp = queue_First(&tcall->rq, rx_packet);
1807 if (rp->header.seq == 1
1809 || (rp->header.flags & RX_LAST_PACKET))) {
1811 } else if (rxi_2dchoice && !choice2
1812 && !(tcall->flags & RX_CALL_CLEARED)
1813 && (tcall->rprev > rxi_HardAckRate)) {
1827 /* we can't schedule a call if there's no data!!! */
1828 /* send an ack if there's no data, if we're missing the
1829 * first packet, or we're missing something between first
1830 * and last -- there's a "hole" in the incoming data. */
1831 if (queue_IsEmpty(&call->rq)
1832 || queue_First(&call->rq, rx_packet)->header.seq != 1
1833 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1834 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1836 call->flags &= (~RX_CALL_WAIT_PROC);
1837 service->nRequestsRunning++;
1838 /* just started call in minProcs pool, need fewer to maintain
1840 if (service->nRequestsRunning <= service->minProcs)
1844 /* MUTEX_EXIT(&call->lock); */
1846 /* If there are no eligible incoming calls, add this process
1847 * to the idle server queue, to wait for one */
1850 *socketp = OSI_NULLSOCKET;
1852 sq->socketp = socketp;
1853 queue_Append(&rx_idleServerQueue, sq);
1857 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1859 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1860 return (struct rx_call *)0;
1863 } while (!(call = sq->newcall)
1864 && !(socketp && *socketp != OSI_NULLSOCKET));
1866 MUTEX_EXIT(&sq->lock);
1868 MUTEX_ENTER(&freeSQEList_lock);
1869 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1870 rx_FreeSQEList = sq;
1871 MUTEX_EXIT(&freeSQEList_lock);
1874 clock_GetTime(&call->startTime);
1875 call->state = RX_STATE_ACTIVE;
1876 call->mode = RX_MODE_RECEIVING;
1877 #ifdef RX_KERNEL_TRACE
1878 if (ICL_SETACTIVE(afs_iclSetp)) {
1879 int glockOwner = ISAFS_GLOCK();
1882 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1883 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1890 rxi_calltrace(RX_CALL_START, call);
1891 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1892 call->conn->service->servicePort, call->conn->service->serviceId,
1895 dpf(("rx_GetCall(socketp=0x%"AFS_PTR_FMT", *socketp=0x%"AFS_PTR_FMT")\n", socketp, *socketp));
1902 #endif /* RX_ENABLE_LOCKS */
1906 /* Establish a procedure to be called when a packet arrives for a
1907 * call. This routine will be called at most once after each call,
1908 * and will also be called if there is an error condition on the or
1909 * the call is complete. Used by multi rx to build a selection
1910 * function which determines which of several calls is likely to be a
1911 * good one to read from.
1912 * NOTE: the way this is currently implemented it is probably only a
1913 * good idea to (1) use it immediately after a newcall (clients only)
1914 * and (2) only use it once. Other uses currently void your warranty
1917 rx_SetArrivalProc(struct rx_call *call,
1918 void (*proc) (struct rx_call * call,
1921 void * handle, int arg)
1923 call->arrivalProc = proc;
1924 call->arrivalProcHandle = handle;
1925 call->arrivalProcArg = arg;
1928 /* Call is finished (possibly prematurely). Return rc to the peer, if
1929 * appropriate, and return the final error code from the conversation
1933 rx_EndCall(struct rx_call *call, afs_int32 rc)
1935 struct rx_connection *conn = call->conn;
1936 struct rx_service *service;
1942 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
1943 call, rc, call->error, call->abortCode));
1946 MUTEX_ENTER(&call->lock);
1948 if (rc == 0 && call->error == 0) {
1949 call->abortCode = 0;
1950 call->abortCount = 0;
1953 call->arrivalProc = (void (*)())0;
1954 if (rc && call->error == 0) {
1955 rxi_CallError(call, rc);
1956 /* Send an abort message to the peer if this error code has
1957 * only just been set. If it was set previously, assume the
1958 * peer has already been sent the error code or will request it
1960 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1962 if (conn->type == RX_SERVER_CONNECTION) {
1963 /* Make sure reply or at least dummy reply is sent */
1964 if (call->mode == RX_MODE_RECEIVING) {
1965 rxi_WriteProc(call, 0, 0);
1967 if (call->mode == RX_MODE_SENDING) {
1968 rxi_FlushWrite(call);
1970 service = conn->service;
1971 rxi_calltrace(RX_CALL_END, call);
1972 /* Call goes to hold state until reply packets are acknowledged */
1973 if (call->tfirst + call->nSoftAcked < call->tnext) {
1974 call->state = RX_STATE_HOLD;
1976 call->state = RX_STATE_DALLY;
1977 rxi_ClearTransmitQueue(call, 0);
1978 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
1979 rxevent_Cancel(call->keepAliveEvent, call,
1980 RX_CALL_REFCOUNT_ALIVE);
1982 } else { /* Client connection */
1984 /* Make sure server receives input packets, in the case where
1985 * no reply arguments are expected */
1986 if ((call->mode == RX_MODE_SENDING)
1987 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
1988 (void)rxi_ReadProc(call, &dummy, 1);
1991 /* If we had an outstanding delayed ack, be nice to the server
1992 * and force-send it now.
1994 if (call->delayedAckEvent) {
1995 rxevent_Cancel(call->delayedAckEvent, call,
1996 RX_CALL_REFCOUNT_DELAY);
1997 call->delayedAckEvent = NULL;
1998 rxi_SendDelayedAck(NULL, call, NULL);
2001 /* We need to release the call lock since it's lower than the
2002 * conn_call_lock and we don't want to hold the conn_call_lock
2003 * over the rx_ReadProc call. The conn_call_lock needs to be held
2004 * here for the case where rx_NewCall is perusing the calls on
2005 * the connection structure. We don't want to signal until
2006 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2007 * have checked this call, found it active and by the time it
2008 * goes to sleep, will have missed the signal.
2010 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2011 * there are threads waiting to use the conn object.
2013 MUTEX_EXIT(&call->lock);
2014 MUTEX_ENTER(&conn->conn_call_lock);
2015 MUTEX_ENTER(&call->lock);
2016 MUTEX_ENTER(&conn->conn_data_lock);
2017 conn->flags |= RX_CONN_BUSY;
2018 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2019 if (conn->makeCallWaiters == 0)
2020 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2021 MUTEX_EXIT(&conn->conn_data_lock);
2022 #ifdef RX_ENABLE_LOCKS
2023 CV_BROADCAST(&conn->conn_call_cv);
2028 #ifdef RX_ENABLE_LOCKS
2030 MUTEX_EXIT(&conn->conn_data_lock);
2032 #endif /* RX_ENABLE_LOCKS */
2033 call->state = RX_STATE_DALLY;
2035 error = call->error;
2037 /* currentPacket, nLeft, and NFree must be zeroed here, because
2038 * ResetCall cannot: ResetCall may be called at splnet(), in the
2039 * kernel version, and may interrupt the macros rx_Read or
2040 * rx_Write, which run at normal priority for efficiency. */
2041 if (call->currentPacket) {
2042 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2043 rxi_FreePacket(call->currentPacket);
2044 call->currentPacket = (struct rx_packet *)0;
2047 call->nLeft = call->nFree = call->curlen = 0;
2049 /* Free any packets from the last call to ReadvProc/WritevProc */
2050 #ifdef RXDEBUG_PACKET
2052 #endif /* RXDEBUG_PACKET */
2053 rxi_FreePackets(0, &call->iovq);
2055 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2056 MUTEX_EXIT(&call->lock);
2057 if (conn->type == RX_CLIENT_CONNECTION) {
2058 MUTEX_EXIT(&conn->conn_call_lock);
2059 conn->flags &= ~RX_CONN_BUSY;
2063 * Map errors to the local host's errno.h format.
2065 error = ntoh_syserr_conv(error);
2069 #if !defined(KERNEL)
2071 /* Call this routine when shutting down a server or client (especially
2072 * clients). This will allow Rx to gracefully garbage collect server
2073 * connections, and reduce the number of retries that a server might
2074 * make to a dead client.
2075 * This is not quite right, since some calls may still be ongoing and
2076 * we can't lock them to destroy them. */
2080 struct rx_connection **conn_ptr, **conn_end;
2084 if (rxinit_status == 1) {
2086 return; /* Already shutdown. */
2088 rxi_DeleteCachedConnections();
2089 if (rx_connHashTable) {
2090 MUTEX_ENTER(&rx_connHashTable_lock);
2091 for (conn_ptr = &rx_connHashTable[0], conn_end =
2092 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2094 struct rx_connection *conn, *next;
2095 for (conn = *conn_ptr; conn; conn = next) {
2097 if (conn->type == RX_CLIENT_CONNECTION) {
2098 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2100 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2101 #ifdef RX_ENABLE_LOCKS
2102 rxi_DestroyConnectionNoLock(conn);
2103 #else /* RX_ENABLE_LOCKS */
2104 rxi_DestroyConnection(conn);
2105 #endif /* RX_ENABLE_LOCKS */
2109 #ifdef RX_ENABLE_LOCKS
2110 while (rx_connCleanup_list) {
2111 struct rx_connection *conn;
2112 conn = rx_connCleanup_list;
2113 rx_connCleanup_list = rx_connCleanup_list->next;
2114 MUTEX_EXIT(&rx_connHashTable_lock);
2115 rxi_CleanupConnection(conn);
2116 MUTEX_ENTER(&rx_connHashTable_lock);
2118 MUTEX_EXIT(&rx_connHashTable_lock);
2119 #endif /* RX_ENABLE_LOCKS */
2124 afs_winsockCleanup();
2132 /* if we wakeup packet waiter too often, can get in loop with two
2133 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2135 rxi_PacketsUnWait(void)
2137 if (!rx_waitingForPackets) {
2141 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2142 return; /* still over quota */
2145 rx_waitingForPackets = 0;
2146 #ifdef RX_ENABLE_LOCKS
2147 CV_BROADCAST(&rx_waitingForPackets_cv);
2149 osi_rxWakeup(&rx_waitingForPackets);
2155 /* ------------------Internal interfaces------------------------- */
2157 /* Return this process's service structure for the
2158 * specified socket and service */
2160 rxi_FindService(osi_socket socket, u_short serviceId)
2162 struct rx_service **sp;
2163 for (sp = &rx_services[0]; *sp; sp++) {
2164 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2170 #ifdef RXDEBUG_PACKET
2171 #ifdef KDUMP_RX_LOCK
2172 static struct rx_call_rx_lock *rx_allCallsp = 0;
2174 static struct rx_call *rx_allCallsp = 0;
2176 #endif /* RXDEBUG_PACKET */
2178 /* Allocate a call structure, for the indicated channel of the
2179 * supplied connection. The mode and state of the call must be set by
2180 * the caller. Returns the call with mutex locked. */
2182 rxi_NewCall(struct rx_connection *conn, int channel)
2184 struct rx_call *call;
2185 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2186 struct rx_call *cp; /* Call pointer temp */
2187 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2188 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2190 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2192 /* Grab an existing call structure, or allocate a new one.
2193 * Existing call structures are assumed to have been left reset by
2195 MUTEX_ENTER(&rx_freeCallQueue_lock);
2197 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2199 * EXCEPT that the TQ might not yet be cleared out.
2200 * Skip over those with in-use TQs.
2203 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2204 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2210 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2211 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2212 call = queue_First(&rx_freeCallQueue, rx_call);
2213 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2215 if (rx_stats_active)
2216 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2217 MUTEX_EXIT(&rx_freeCallQueue_lock);
2218 MUTEX_ENTER(&call->lock);
2219 CLEAR_CALL_QUEUE_LOCK(call);
2220 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2221 /* Now, if TQ wasn't cleared earlier, do it now. */
2222 if (call->flags & RX_CALL_TQ_CLEARME) {
2223 rxi_ClearTransmitQueue(call, 1);
2224 /*queue_Init(&call->tq);*/
2226 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2227 /* Bind the call to its connection structure */
2229 rxi_ResetCall(call, 1);
2232 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2233 #ifdef RXDEBUG_PACKET
2234 call->allNextp = rx_allCallsp;
2235 rx_allCallsp = call;
2237 #endif /* RXDEBUG_PACKET */
2238 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2240 MUTEX_EXIT(&rx_freeCallQueue_lock);
2241 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2242 MUTEX_ENTER(&call->lock);
2243 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2244 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2245 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2247 /* Initialize once-only items */
2248 queue_Init(&call->tq);
2249 queue_Init(&call->rq);
2250 queue_Init(&call->iovq);
2251 #ifdef RXDEBUG_PACKET
2252 call->rqc = call->tqc = call->iovqc = 0;
2253 #endif /* RXDEBUG_PACKET */
2254 /* Bind the call to its connection structure (prereq for reset) */
2256 rxi_ResetCall(call, 1);
2258 call->channel = channel;
2259 call->callNumber = &conn->callNumber[channel];
2260 call->rwind = conn->rwind[channel];
2261 call->twind = conn->twind[channel];
2262 /* Note that the next expected call number is retained (in
2263 * conn->callNumber[i]), even if we reallocate the call structure
2265 conn->call[channel] = call;
2266 /* if the channel's never been used (== 0), we should start at 1, otherwise
2267 * the call number is valid from the last time this channel was used */
2268 if (*call->callNumber == 0)
2269 *call->callNumber = 1;
2274 /* A call has been inactive long enough that so we can throw away
2275 * state, including the call structure, which is placed on the call
2277 * Call is locked upon entry.
2278 * haveCTLock set if called from rxi_ReapConnections
2280 #ifdef RX_ENABLE_LOCKS
2282 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2283 #else /* RX_ENABLE_LOCKS */
2285 rxi_FreeCall(struct rx_call *call)
2286 #endif /* RX_ENABLE_LOCKS */
2288 int channel = call->channel;
2289 struct rx_connection *conn = call->conn;
2292 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2293 (*call->callNumber)++;
2294 rxi_ResetCall(call, 0);
2295 call->conn->call[channel] = (struct rx_call *)0;
2297 MUTEX_ENTER(&rx_freeCallQueue_lock);
2298 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2299 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2300 /* A call may be free even though its transmit queue is still in use.
2301 * Since we search the call list from head to tail, put busy calls at
2302 * the head of the list, and idle calls at the tail.
2304 if (call->flags & RX_CALL_TQ_BUSY)
2305 queue_Prepend(&rx_freeCallQueue, call);
2307 queue_Append(&rx_freeCallQueue, call);
2308 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2309 queue_Append(&rx_freeCallQueue, call);
2310 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2311 if (rx_stats_active)
2312 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2313 MUTEX_EXIT(&rx_freeCallQueue_lock);
2315 /* Destroy the connection if it was previously slated for
2316 * destruction, i.e. the Rx client code previously called
2317 * rx_DestroyConnection (client connections), or
2318 * rxi_ReapConnections called the same routine (server
2319 * connections). Only do this, however, if there are no
2320 * outstanding calls. Note that for fine grain locking, there appears
2321 * to be a deadlock in that rxi_FreeCall has a call locked and
2322 * DestroyConnectionNoLock locks each call in the conn. But note a
2323 * few lines up where we have removed this call from the conn.
2324 * If someone else destroys a connection, they either have no
2325 * call lock held or are going through this section of code.
2327 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2328 MUTEX_ENTER(&conn->conn_data_lock);
2330 MUTEX_EXIT(&conn->conn_data_lock);
2331 #ifdef RX_ENABLE_LOCKS
2333 rxi_DestroyConnectionNoLock(conn);
2335 rxi_DestroyConnection(conn);
2336 #else /* RX_ENABLE_LOCKS */
2337 rxi_DestroyConnection(conn);
2338 #endif /* RX_ENABLE_LOCKS */
2342 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2344 rxi_Alloc(size_t size)
2348 if (rx_stats_active)
2349 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2352 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2353 afs_osi_Alloc_NoSleep(size);
2358 osi_Panic("rxi_Alloc error");
2364 rxi_Free(void *addr, size_t size)
2366 if (rx_stats_active)
2367 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2368 osi_Free(addr, size);
2372 rxi_SetPeerMtu(afs_uint32 host, afs_uint32 port, int mtu)
2374 struct rx_peer **peer_ptr, **peer_end;
2377 MUTEX_ENTER(&rx_peerHashTable_lock);
2379 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2380 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2382 struct rx_peer *peer, *next;
2383 for (peer = *peer_ptr; peer; peer = next) {
2385 if (host == peer->host) {
2386 MUTEX_ENTER(&peer->peer_lock);
2387 peer->ifMTU=MIN(mtu, peer->ifMTU);
2388 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2389 MUTEX_EXIT(&peer->peer_lock);
2394 struct rx_peer *peer;
2395 hashIndex = PEER_HASH(host, port);
2396 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2397 if ((peer->host == host) && (peer->port == port)) {
2398 MUTEX_ENTER(&peer->peer_lock);
2399 peer->ifMTU=MIN(mtu, peer->ifMTU);
2400 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2401 MUTEX_EXIT(&peer->peer_lock);
2405 MUTEX_EXIT(&rx_peerHashTable_lock);
2408 /* Find the peer process represented by the supplied (host,port)
2409 * combination. If there is no appropriate active peer structure, a
2410 * new one will be allocated and initialized
2411 * The origPeer, if set, is a pointer to a peer structure on which the
2412 * refcount will be be decremented. This is used to replace the peer
2413 * structure hanging off a connection structure */
2415 rxi_FindPeer(afs_uint32 host, u_short port,
2416 struct rx_peer *origPeer, int create)
2420 hashIndex = PEER_HASH(host, port);
2421 MUTEX_ENTER(&rx_peerHashTable_lock);
2422 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2423 if ((pp->host == host) && (pp->port == port))
2428 pp = rxi_AllocPeer(); /* This bzero's *pp */
2429 pp->host = host; /* set here or in InitPeerParams is zero */
2431 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2432 queue_Init(&pp->congestionQueue);
2433 queue_Init(&pp->rpcStats);
2434 pp->next = rx_peerHashTable[hashIndex];
2435 rx_peerHashTable[hashIndex] = pp;
2436 rxi_InitPeerParams(pp);
2437 if (rx_stats_active)
2438 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2445 origPeer->refCount--;
2446 MUTEX_EXIT(&rx_peerHashTable_lock);
2451 /* Find the connection at (host, port) started at epoch, and with the
2452 * given connection id. Creates the server connection if necessary.
2453 * The type specifies whether a client connection or a server
2454 * connection is desired. In both cases, (host, port) specify the
2455 * peer's (host, pair) pair. Client connections are not made
2456 * automatically by this routine. The parameter socket gives the
2457 * socket descriptor on which the packet was received. This is used,
2458 * in the case of server connections, to check that *new* connections
2459 * come via a valid (port, serviceId). Finally, the securityIndex
2460 * parameter must match the existing index for the connection. If a
2461 * server connection is created, it will be created using the supplied
2462 * index, if the index is valid for this service */
2463 struct rx_connection *
2464 rxi_FindConnection(osi_socket socket, afs_int32 host,
2465 u_short port, u_short serviceId, afs_uint32 cid,
2466 afs_uint32 epoch, int type, u_int securityIndex)
2468 int hashindex, flag, i;
2469 struct rx_connection *conn;
2470 hashindex = CONN_HASH(host, port, cid, epoch, type);
2471 MUTEX_ENTER(&rx_connHashTable_lock);
2472 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2473 rx_connHashTable[hashindex],
2476 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2477 && (epoch == conn->epoch)) {
2478 struct rx_peer *pp = conn->peer;
2479 if (securityIndex != conn->securityIndex) {
2480 /* this isn't supposed to happen, but someone could forge a packet
2481 * like this, and there seems to be some CM bug that makes this
2482 * happen from time to time -- in which case, the fileserver
2484 MUTEX_EXIT(&rx_connHashTable_lock);
2485 return (struct rx_connection *)0;
2487 if (pp->host == host && pp->port == port)
2489 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2491 /* So what happens when it's a callback connection? */
2492 if ( /*type == RX_CLIENT_CONNECTION && */
2493 (conn->epoch & 0x80000000))
2497 /* the connection rxLastConn that was used the last time is not the
2498 ** one we are looking for now. Hence, start searching in the hash */
2500 conn = rx_connHashTable[hashindex];
2505 struct rx_service *service;
2506 if (type == RX_CLIENT_CONNECTION) {
2507 MUTEX_EXIT(&rx_connHashTable_lock);
2508 return (struct rx_connection *)0;
2510 service = rxi_FindService(socket, serviceId);
2511 if (!service || (securityIndex >= service->nSecurityObjects)
2512 || (service->securityObjects[securityIndex] == 0)) {
2513 MUTEX_EXIT(&rx_connHashTable_lock);
2514 return (struct rx_connection *)0;
2516 conn = rxi_AllocConnection(); /* This bzero's the connection */
2517 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2518 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2519 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2520 conn->next = rx_connHashTable[hashindex];
2521 rx_connHashTable[hashindex] = conn;
2522 conn->peer = rxi_FindPeer(host, port, 0, 1);
2523 conn->type = RX_SERVER_CONNECTION;
2524 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2525 conn->epoch = epoch;
2526 conn->cid = cid & RX_CIDMASK;
2527 /* conn->serial = conn->lastSerial = 0; */
2528 /* conn->timeout = 0; */
2529 conn->ackRate = RX_FAST_ACK_RATE;
2530 conn->service = service;
2531 conn->serviceId = serviceId;
2532 conn->securityIndex = securityIndex;
2533 conn->securityObject = service->securityObjects[securityIndex];
2534 conn->nSpecific = 0;
2535 conn->specific = NULL;
2536 rx_SetConnDeadTime(conn, service->connDeadTime);
2537 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2538 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2539 for (i = 0; i < RX_MAXCALLS; i++) {
2540 conn->twind[i] = rx_initSendWindow;
2541 conn->rwind[i] = rx_initReceiveWindow;
2543 /* Notify security object of the new connection */
2544 RXS_NewConnection(conn->securityObject, conn);
2545 /* XXXX Connection timeout? */
2546 if (service->newConnProc)
2547 (*service->newConnProc) (conn);
2548 if (rx_stats_active)
2549 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2552 MUTEX_ENTER(&conn->conn_data_lock);
2554 MUTEX_EXIT(&conn->conn_data_lock);
2556 rxLastConn = conn; /* store this connection as the last conn used */
2557 MUTEX_EXIT(&rx_connHashTable_lock);
2561 /* There are two packet tracing routines available for testing and monitoring
2562 * Rx. One is called just after every packet is received and the other is
2563 * called just before every packet is sent. Received packets, have had their
2564 * headers decoded, and packets to be sent have not yet had their headers
2565 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2566 * containing the network address. Both can be modified. The return value, if
2567 * non-zero, indicates that the packet should be dropped. */
2569 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2570 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2572 /* A packet has been received off the interface. Np is the packet, socket is
2573 * the socket number it was received from (useful in determining which service
2574 * this packet corresponds to), and (host, port) reflect the host,port of the
2575 * sender. This call returns the packet to the caller if it is finished with
2576 * it, rather than de-allocating it, just as a small performance hack */
2579 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2580 afs_uint32 host, u_short port, int *tnop,
2581 struct rx_call **newcallp)
2583 struct rx_call *call;
2584 struct rx_connection *conn;
2586 afs_uint32 currentCallNumber;
2592 struct rx_packet *tnp;
2595 /* We don't print out the packet until now because (1) the time may not be
2596 * accurate enough until now in the lwp implementation (rx_Listener only gets
2597 * the time after the packet is read) and (2) from a protocol point of view,
2598 * this is the first time the packet has been seen */
2599 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2600 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2601 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2602 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2603 np->header.epoch, np->header.cid, np->header.callNumber,
2604 np->header.seq, np->header.flags, np));
2607 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2608 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2611 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2612 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2615 /* If an input tracer function is defined, call it with the packet and
2616 * network address. Note this function may modify its arguments. */
2617 if (rx_justReceived) {
2618 struct sockaddr_in addr;
2620 addr.sin_family = AF_INET;
2621 addr.sin_port = port;
2622 addr.sin_addr.s_addr = host;
2623 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2624 addr.sin_len = sizeof(addr);
2625 #endif /* AFS_OSF_ENV */
2626 drop = (*rx_justReceived) (np, &addr);
2627 /* drop packet if return value is non-zero */
2630 port = addr.sin_port; /* in case fcn changed addr */
2631 host = addr.sin_addr.s_addr;
2635 /* If packet was not sent by the client, then *we* must be the client */
2636 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2637 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2639 /* Find the connection (or fabricate one, if we're the server & if
2640 * necessary) associated with this packet */
2642 rxi_FindConnection(socket, host, port, np->header.serviceId,
2643 np->header.cid, np->header.epoch, type,
2644 np->header.securityIndex);
2647 /* If no connection found or fabricated, just ignore the packet.
2648 * (An argument could be made for sending an abort packet for
2653 MUTEX_ENTER(&conn->conn_data_lock);
2654 if (conn->maxSerial < np->header.serial)
2655 conn->maxSerial = np->header.serial;
2656 MUTEX_EXIT(&conn->conn_data_lock);
2658 /* If the connection is in an error state, send an abort packet and ignore
2659 * the incoming packet */
2661 /* Don't respond to an abort packet--we don't want loops! */
2662 MUTEX_ENTER(&conn->conn_data_lock);
2663 if (np->header.type != RX_PACKET_TYPE_ABORT)
2664 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2666 MUTEX_EXIT(&conn->conn_data_lock);
2670 /* Check for connection-only requests (i.e. not call specific). */
2671 if (np->header.callNumber == 0) {
2672 switch (np->header.type) {
2673 case RX_PACKET_TYPE_ABORT: {
2674 /* What if the supplied error is zero? */
2675 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2676 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2677 rxi_ConnectionError(conn, errcode);
2678 MUTEX_ENTER(&conn->conn_data_lock);
2680 MUTEX_EXIT(&conn->conn_data_lock);
2683 case RX_PACKET_TYPE_CHALLENGE:
2684 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2685 MUTEX_ENTER(&conn->conn_data_lock);
2687 MUTEX_EXIT(&conn->conn_data_lock);
2689 case RX_PACKET_TYPE_RESPONSE:
2690 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2691 MUTEX_ENTER(&conn->conn_data_lock);
2693 MUTEX_EXIT(&conn->conn_data_lock);
2695 case RX_PACKET_TYPE_PARAMS:
2696 case RX_PACKET_TYPE_PARAMS + 1:
2697 case RX_PACKET_TYPE_PARAMS + 2:
2698 /* ignore these packet types for now */
2699 MUTEX_ENTER(&conn->conn_data_lock);
2701 MUTEX_EXIT(&conn->conn_data_lock);
2706 /* Should not reach here, unless the peer is broken: send an
2708 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2709 MUTEX_ENTER(&conn->conn_data_lock);
2710 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2712 MUTEX_EXIT(&conn->conn_data_lock);
2717 channel = np->header.cid & RX_CHANNELMASK;
2718 call = conn->call[channel];
2719 #ifdef RX_ENABLE_LOCKS
2721 MUTEX_ENTER(&call->lock);
2722 /* Test to see if call struct is still attached to conn. */
2723 if (call != conn->call[channel]) {
2725 MUTEX_EXIT(&call->lock);
2726 if (type == RX_SERVER_CONNECTION) {
2727 call = conn->call[channel];
2728 /* If we started with no call attached and there is one now,
2729 * another thread is also running this routine and has gotten
2730 * the connection channel. We should drop this packet in the tests
2731 * below. If there was a call on this connection and it's now
2732 * gone, then we'll be making a new call below.
2733 * If there was previously a call and it's now different then
2734 * the old call was freed and another thread running this routine
2735 * has created a call on this channel. One of these two threads
2736 * has a packet for the old call and the code below handles those
2740 MUTEX_ENTER(&call->lock);
2742 /* This packet can't be for this call. If the new call address is
2743 * 0 then no call is running on this channel. If there is a call
2744 * then, since this is a client connection we're getting data for
2745 * it must be for the previous call.
2747 if (rx_stats_active)
2748 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2749 MUTEX_ENTER(&conn->conn_data_lock);
2751 MUTEX_EXIT(&conn->conn_data_lock);
2756 currentCallNumber = conn->callNumber[channel];
2758 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2759 if (np->header.callNumber < currentCallNumber) {
2760 if (rx_stats_active)
2761 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2762 #ifdef RX_ENABLE_LOCKS
2764 MUTEX_EXIT(&call->lock);
2766 MUTEX_ENTER(&conn->conn_data_lock);
2768 MUTEX_EXIT(&conn->conn_data_lock);
2772 MUTEX_ENTER(&conn->conn_call_lock);
2773 call = rxi_NewCall(conn, channel);
2774 MUTEX_EXIT(&conn->conn_call_lock);
2775 *call->callNumber = np->header.callNumber;
2777 if (np->header.callNumber == 0)
2778 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%0.06d len %d",
2779 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2780 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2781 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2783 call->state = RX_STATE_PRECALL;
2784 clock_GetTime(&call->queueTime);
2785 hzero(call->bytesSent);
2786 hzero(call->bytesRcvd);
2788 * If the number of queued calls exceeds the overload
2789 * threshold then abort this call.
2791 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2792 struct rx_packet *tp;
2794 rxi_CallError(call, rx_BusyError);
2795 tp = rxi_SendCallAbort(call, np, 1, 0);
2796 MUTEX_EXIT(&call->lock);
2797 MUTEX_ENTER(&conn->conn_data_lock);
2799 MUTEX_EXIT(&conn->conn_data_lock);
2800 if (rx_stats_active)
2801 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2804 rxi_KeepAliveOn(call);
2805 } else if (np->header.callNumber != currentCallNumber) {
2806 /* Wait until the transmit queue is idle before deciding
2807 * whether to reset the current call. Chances are that the
2808 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2811 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2812 while ((call->state == RX_STATE_ACTIVE)
2813 && (call->flags & RX_CALL_TQ_BUSY)) {
2814 call->flags |= RX_CALL_TQ_WAIT;
2816 #ifdef RX_ENABLE_LOCKS
2817 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2818 CV_WAIT(&call->cv_tq, &call->lock);
2819 #else /* RX_ENABLE_LOCKS */
2820 osi_rxSleep(&call->tq);
2821 #endif /* RX_ENABLE_LOCKS */
2823 if (call->tqWaiters == 0)
2824 call->flags &= ~RX_CALL_TQ_WAIT;
2826 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2827 /* If the new call cannot be taken right now send a busy and set
2828 * the error condition in this call, so that it terminates as
2829 * quickly as possible */
2830 if (call->state == RX_STATE_ACTIVE) {
2831 struct rx_packet *tp;
2833 rxi_CallError(call, RX_CALL_DEAD);
2834 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2836 MUTEX_EXIT(&call->lock);
2837 MUTEX_ENTER(&conn->conn_data_lock);
2839 MUTEX_EXIT(&conn->conn_data_lock);
2842 rxi_ResetCall(call, 0);
2843 *call->callNumber = np->header.callNumber;
2845 if (np->header.callNumber == 0)
2846 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
2847 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2848 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2849 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
2851 call->state = RX_STATE_PRECALL;
2852 clock_GetTime(&call->queueTime);
2853 hzero(call->bytesSent);
2854 hzero(call->bytesRcvd);
2856 * If the number of queued calls exceeds the overload
2857 * threshold then abort this call.
2859 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2860 struct rx_packet *tp;
2862 rxi_CallError(call, rx_BusyError);
2863 tp = rxi_SendCallAbort(call, np, 1, 0);
2864 MUTEX_EXIT(&call->lock);
2865 MUTEX_ENTER(&conn->conn_data_lock);
2867 MUTEX_EXIT(&conn->conn_data_lock);
2868 if (rx_stats_active)
2869 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2872 rxi_KeepAliveOn(call);
2874 /* Continuing call; do nothing here. */
2876 } else { /* we're the client */
2877 /* Ignore all incoming acknowledgements for calls in DALLY state */
2878 if (call && (call->state == RX_STATE_DALLY)
2879 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2880 if (rx_stats_active)
2881 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2882 #ifdef RX_ENABLE_LOCKS
2884 MUTEX_EXIT(&call->lock);
2887 MUTEX_ENTER(&conn->conn_data_lock);
2889 MUTEX_EXIT(&conn->conn_data_lock);
2893 /* Ignore anything that's not relevant to the current call. If there
2894 * isn't a current call, then no packet is relevant. */
2895 if (!call || (np->header.callNumber != currentCallNumber)) {
2896 if (rx_stats_active)
2897 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2898 #ifdef RX_ENABLE_LOCKS
2900 MUTEX_EXIT(&call->lock);
2903 MUTEX_ENTER(&conn->conn_data_lock);
2905 MUTEX_EXIT(&conn->conn_data_lock);
2908 /* If the service security object index stamped in the packet does not
2909 * match the connection's security index, ignore the packet */
2910 if (np->header.securityIndex != conn->securityIndex) {
2911 #ifdef RX_ENABLE_LOCKS
2912 MUTEX_EXIT(&call->lock);
2914 MUTEX_ENTER(&conn->conn_data_lock);
2916 MUTEX_EXIT(&conn->conn_data_lock);
2920 /* If we're receiving the response, then all transmit packets are
2921 * implicitly acknowledged. Get rid of them. */
2922 if (np->header.type == RX_PACKET_TYPE_DATA) {
2923 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2924 /* XXX Hack. Because we must release the global rx lock when
2925 * sending packets (osi_NetSend) we drop all acks while we're
2926 * traversing the tq in rxi_Start sending packets out because
2927 * packets may move to the freePacketQueue as result of being here!
2928 * So we drop these packets until we're safely out of the
2929 * traversing. Really ugly!
2930 * For fine grain RX locking, we set the acked field in the
2931 * packets and let rxi_Start remove them from the transmit queue.
2933 if (call->flags & RX_CALL_TQ_BUSY) {
2934 #ifdef RX_ENABLE_LOCKS
2935 rxi_SetAcksInTransmitQueue(call);
2938 return np; /* xmitting; drop packet */
2941 rxi_ClearTransmitQueue(call, 0);
2943 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2944 rxi_ClearTransmitQueue(call, 0);
2945 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2947 if (np->header.type == RX_PACKET_TYPE_ACK) {
2948 /* now check to see if this is an ack packet acknowledging that the
2949 * server actually *lost* some hard-acked data. If this happens we
2950 * ignore this packet, as it may indicate that the server restarted in
2951 * the middle of a call. It is also possible that this is an old ack
2952 * packet. We don't abort the connection in this case, because this
2953 * *might* just be an old ack packet. The right way to detect a server
2954 * restart in the midst of a call is to notice that the server epoch
2956 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2957 * XXX unacknowledged. I think that this is off-by-one, but
2958 * XXX I don't dare change it just yet, since it will
2959 * XXX interact badly with the server-restart detection
2960 * XXX code in receiveackpacket. */
2961 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2962 if (rx_stats_active)
2963 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2964 MUTEX_EXIT(&call->lock);
2965 MUTEX_ENTER(&conn->conn_data_lock);
2967 MUTEX_EXIT(&conn->conn_data_lock);
2971 } /* else not a data packet */
2974 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2975 /* Set remote user defined status from packet */
2976 call->remoteStatus = np->header.userStatus;
2978 /* Note the gap between the expected next packet and the actual
2979 * packet that arrived, when the new packet has a smaller serial number
2980 * than expected. Rioses frequently reorder packets all by themselves,
2981 * so this will be quite important with very large window sizes.
2982 * Skew is checked against 0 here to avoid any dependence on the type of
2983 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2985 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2986 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2987 * I think using a beta of 1/8 is probably appropriate. 93.04.21
2989 MUTEX_ENTER(&conn->conn_data_lock);
2990 skew = conn->lastSerial - np->header.serial;
2991 conn->lastSerial = np->header.serial;
2992 MUTEX_EXIT(&conn->conn_data_lock);
2994 struct rx_peer *peer;
2996 if (skew > peer->inPacketSkew) {
2997 dpf(("*** In skew changed from %d to %d\n",
2998 peer->inPacketSkew, skew));
2999 peer->inPacketSkew = skew;
3003 /* Now do packet type-specific processing */
3004 switch (np->header.type) {
3005 case RX_PACKET_TYPE_DATA:
3006 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3009 case RX_PACKET_TYPE_ACK:
3010 /* Respond immediately to ack packets requesting acknowledgement
3012 if (np->header.flags & RX_REQUEST_ACK) {
3014 (void)rxi_SendCallAbort(call, 0, 1, 0);
3016 (void)rxi_SendAck(call, 0, np->header.serial,
3017 RX_ACK_PING_RESPONSE, 1);
3019 np = rxi_ReceiveAckPacket(call, np, 1);
3021 case RX_PACKET_TYPE_ABORT: {
3022 /* An abort packet: reset the call, passing the error up to the user. */
3023 /* What if error is zero? */
3024 /* What if the error is -1? the application will treat it as a timeout. */
3025 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3026 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3027 rxi_CallError(call, errdata);
3028 MUTEX_EXIT(&call->lock);
3029 MUTEX_ENTER(&conn->conn_data_lock);
3031 MUTEX_EXIT(&conn->conn_data_lock);
3032 return np; /* xmitting; drop packet */
3034 case RX_PACKET_TYPE_BUSY:
3037 case RX_PACKET_TYPE_ACKALL:
3038 /* All packets acknowledged, so we can drop all packets previously
3039 * readied for sending */
3040 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3041 /* XXX Hack. We because we can't release the global rx lock when
3042 * sending packets (osi_NetSend) we drop all ack pkts while we're
3043 * traversing the tq in rxi_Start sending packets out because
3044 * packets may move to the freePacketQueue as result of being
3045 * here! So we drop these packets until we're safely out of the
3046 * traversing. Really ugly!
3047 * For fine grain RX locking, we set the acked field in the packets
3048 * and let rxi_Start remove the packets from the transmit queue.
3050 if (call->flags & RX_CALL_TQ_BUSY) {
3051 #ifdef RX_ENABLE_LOCKS
3052 rxi_SetAcksInTransmitQueue(call);
3054 #else /* RX_ENABLE_LOCKS */
3055 MUTEX_EXIT(&call->lock);
3056 MUTEX_ENTER(&conn->conn_data_lock);
3058 MUTEX_EXIT(&conn->conn_data_lock);
3059 return np; /* xmitting; drop packet */
3060 #endif /* RX_ENABLE_LOCKS */
3062 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3063 rxi_ClearTransmitQueue(call, 0);
3064 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3067 /* Should not reach here, unless the peer is broken: send an abort
3069 rxi_CallError(call, RX_PROTOCOL_ERROR);
3070 np = rxi_SendCallAbort(call, np, 1, 0);
3073 /* Note when this last legitimate packet was received, for keep-alive
3074 * processing. Note, we delay getting the time until now in the hope that
3075 * the packet will be delivered to the user before any get time is required
3076 * (if not, then the time won't actually be re-evaluated here). */
3077 call->lastReceiveTime = clock_Sec();
3078 MUTEX_EXIT(&call->lock);
3079 MUTEX_ENTER(&conn->conn_data_lock);
3081 MUTEX_EXIT(&conn->conn_data_lock);
3085 /* return true if this is an "interesting" connection from the point of view
3086 of someone trying to debug the system */
3088 rxi_IsConnInteresting(struct rx_connection *aconn)
3091 struct rx_call *tcall;
3093 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3095 for (i = 0; i < RX_MAXCALLS; i++) {
3096 tcall = aconn->call[i];
3098 if ((tcall->state == RX_STATE_PRECALL)
3099 || (tcall->state == RX_STATE_ACTIVE))
3101 if ((tcall->mode == RX_MODE_SENDING)
3102 || (tcall->mode == RX_MODE_RECEIVING))
3110 /* if this is one of the last few packets AND it wouldn't be used by the
3111 receiving call to immediately satisfy a read request, then drop it on
3112 the floor, since accepting it might prevent a lock-holding thread from
3113 making progress in its reading. If a call has been cleared while in
3114 the precall state then ignore all subsequent packets until the call
3115 is assigned to a thread. */
3118 TooLow(struct rx_packet *ap, struct rx_call *acall)
3122 MUTEX_ENTER(&rx_quota_mutex);
3123 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3124 && (acall->state == RX_STATE_PRECALL))
3125 || ((rx_nFreePackets < rxi_dataQuota + 2)
3126 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3127 && (acall->flags & RX_CALL_READER_WAIT)))) {
3130 MUTEX_EXIT(&rx_quota_mutex);
3136 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3138 struct rx_connection *conn = arg1;
3139 struct rx_call *acall = arg2;
3140 struct rx_call *call = acall;
3141 struct clock when, now;
3144 MUTEX_ENTER(&conn->conn_data_lock);
3145 conn->checkReachEvent = NULL;
3146 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3149 MUTEX_EXIT(&conn->conn_data_lock);
3153 MUTEX_ENTER(&conn->conn_call_lock);
3154 MUTEX_ENTER(&conn->conn_data_lock);
3155 for (i = 0; i < RX_MAXCALLS; i++) {
3156 struct rx_call *tc = conn->call[i];
3157 if (tc && tc->state == RX_STATE_PRECALL) {
3163 /* Indicate that rxi_CheckReachEvent is no longer running by
3164 * clearing the flag. Must be atomic under conn_data_lock to
3165 * avoid a new call slipping by: rxi_CheckConnReach holds
3166 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3168 conn->flags &= ~RX_CONN_ATTACHWAIT;
3169 MUTEX_EXIT(&conn->conn_data_lock);
3170 MUTEX_EXIT(&conn->conn_call_lock);
3175 MUTEX_ENTER(&call->lock);
3176 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3178 MUTEX_EXIT(&call->lock);
3180 clock_GetTime(&now);
3182 when.sec += RX_CHECKREACH_TIMEOUT;
3183 MUTEX_ENTER(&conn->conn_data_lock);
3184 if (!conn->checkReachEvent) {
3186 conn->checkReachEvent =
3187 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3190 MUTEX_EXIT(&conn->conn_data_lock);
3196 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3198 struct rx_service *service = conn->service;
3199 struct rx_peer *peer = conn->peer;
3200 afs_uint32 now, lastReach;
3202 if (service->checkReach == 0)
3206 MUTEX_ENTER(&peer->peer_lock);
3207 lastReach = peer->lastReachTime;
3208 MUTEX_EXIT(&peer->peer_lock);
3209 if (now - lastReach < RX_CHECKREACH_TTL)
3212 MUTEX_ENTER(&conn->conn_data_lock);
3213 if (conn->flags & RX_CONN_ATTACHWAIT) {
3214 MUTEX_EXIT(&conn->conn_data_lock);
3217 conn->flags |= RX_CONN_ATTACHWAIT;
3218 MUTEX_EXIT(&conn->conn_data_lock);
3219 if (!conn->checkReachEvent)
3220 rxi_CheckReachEvent(NULL, conn, call);
3225 /* try to attach call, if authentication is complete */
3227 TryAttach(struct rx_call *acall, osi_socket socket,
3228 int *tnop, struct rx_call **newcallp,
3231 struct rx_connection *conn = acall->conn;
3233 if (conn->type == RX_SERVER_CONNECTION
3234 && acall->state == RX_STATE_PRECALL) {
3235 /* Don't attach until we have any req'd. authentication. */
3236 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3237 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3238 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3239 /* Note: this does not necessarily succeed; there
3240 * may not any proc available
3243 rxi_ChallengeOn(acall->conn);
3248 /* A data packet has been received off the interface. This packet is
3249 * appropriate to the call (the call is in the right state, etc.). This
3250 * routine can return a packet to the caller, for re-use */
3253 rxi_ReceiveDataPacket(struct rx_call *call,
3254 struct rx_packet *np, int istack,
3255 osi_socket socket, afs_uint32 host, u_short port,
3256 int *tnop, struct rx_call **newcallp)
3258 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3263 afs_uint32 serial=0, flags=0;
3265 struct rx_packet *tnp;
3266 struct clock when, now;
3267 if (rx_stats_active)
3268 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3271 /* If there are no packet buffers, drop this new packet, unless we can find
3272 * packet buffers from inactive calls */
3274 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3275 MUTEX_ENTER(&rx_freePktQ_lock);
3276 rxi_NeedMorePackets = TRUE;
3277 MUTEX_EXIT(&rx_freePktQ_lock);
3278 if (rx_stats_active)
3279 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3280 call->rprev = np->header.serial;
3281 rxi_calltrace(RX_TRACE_DROP, call);
3282 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3284 rxi_ClearReceiveQueue(call);
3285 clock_GetTime(&now);
3287 clock_Add(&when, &rx_softAckDelay);
3288 if (!call->delayedAckEvent
3289 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3290 rxevent_Cancel(call->delayedAckEvent, call,
3291 RX_CALL_REFCOUNT_DELAY);
3292 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3293 call->delayedAckEvent =
3294 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3296 /* we've damaged this call already, might as well do it in. */
3302 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3303 * packet is one of several packets transmitted as a single
3304 * datagram. Do not send any soft or hard acks until all packets
3305 * in a jumbogram have been processed. Send negative acks right away.
3307 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3308 /* tnp is non-null when there are more packets in the
3309 * current jumbo gram */
3316 seq = np->header.seq;
3317 serial = np->header.serial;
3318 flags = np->header.flags;
3320 /* If the call is in an error state, send an abort message */
3322 return rxi_SendCallAbort(call, np, istack, 0);
3324 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3325 * AFS 3.5 jumbogram. */
3326 if (flags & RX_JUMBO_PACKET) {
3327 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3332 if (np->header.spare != 0) {
3333 MUTEX_ENTER(&call->conn->conn_data_lock);
3334 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3335 MUTEX_EXIT(&call->conn->conn_data_lock);
3338 /* The usual case is that this is the expected next packet */
3339 if (seq == call->rnext) {
3341 /* Check to make sure it is not a duplicate of one already queued */
3342 if (queue_IsNotEmpty(&call->rq)
3343 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3344 if (rx_stats_active)
3345 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3346 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3347 rxevent_Cancel(call->delayedAckEvent, call,
3348 RX_CALL_REFCOUNT_DELAY);
3349 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3355 /* It's the next packet. Stick it on the receive queue
3356 * for this call. Set newPackets to make sure we wake
3357 * the reader once all packets have been processed */
3358 np->flags |= RX_PKTFLAG_RQ;
3359 queue_Prepend(&call->rq, np);
3360 #ifdef RXDEBUG_PACKET
3362 #endif /* RXDEBUG_PACKET */
3364 np = NULL; /* We can't use this anymore */
3367 /* If an ack is requested then set a flag to make sure we
3368 * send an acknowledgement for this packet */
3369 if (flags & RX_REQUEST_ACK) {
3370 ackNeeded = RX_ACK_REQUESTED;
3373 /* Keep track of whether we have received the last packet */
3374 if (flags & RX_LAST_PACKET) {
3375 call->flags |= RX_CALL_HAVE_LAST;
3379 /* Check whether we have all of the packets for this call */
3380 if (call->flags & RX_CALL_HAVE_LAST) {
3381 afs_uint32 tseq; /* temporary sequence number */
3382 struct rx_packet *tp; /* Temporary packet pointer */
3383 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3385 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3386 if (tseq != tp->header.seq)
3388 if (tp->header.flags & RX_LAST_PACKET) {
3389 call->flags |= RX_CALL_RECEIVE_DONE;
3396 /* Provide asynchronous notification for those who want it
3397 * (e.g. multi rx) */
3398 if (call->arrivalProc) {
3399 (*call->arrivalProc) (call, call->arrivalProcHandle,
3400 call->arrivalProcArg);
3401 call->arrivalProc = (void (*)())0;
3404 /* Update last packet received */
3407 /* If there is no server process serving this call, grab
3408 * one, if available. We only need to do this once. If a
3409 * server thread is available, this thread becomes a server
3410 * thread and the server thread becomes a listener thread. */
3412 TryAttach(call, socket, tnop, newcallp, 0);
3415 /* This is not the expected next packet. */
3417 /* Determine whether this is a new or old packet, and if it's
3418 * a new one, whether it fits into the current receive window.
3419 * Also figure out whether the packet was delivered in sequence.
3420 * We use the prev variable to determine whether the new packet
3421 * is the successor of its immediate predecessor in the
3422 * receive queue, and the missing flag to determine whether
3423 * any of this packets predecessors are missing. */
3425 afs_uint32 prev; /* "Previous packet" sequence number */
3426 struct rx_packet *tp; /* Temporary packet pointer */
3427 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3428 int missing; /* Are any predecessors missing? */
3430 /* If the new packet's sequence number has been sent to the
3431 * application already, then this is a duplicate */
3432 if (seq < call->rnext) {
3433 if (rx_stats_active)
3434 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3435 rxevent_Cancel(call->delayedAckEvent, call,
3436 RX_CALL_REFCOUNT_DELAY);
3437 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3443 /* If the sequence number is greater than what can be
3444 * accomodated by the current window, then send a negative
3445 * acknowledge and drop the packet */
3446 if ((call->rnext + call->rwind) <= seq) {
3447 rxevent_Cancel(call->delayedAckEvent, call,
3448 RX_CALL_REFCOUNT_DELAY);
3449 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3456 /* Look for the packet in the queue of old received packets */
3457 for (prev = call->rnext - 1, missing =
3458 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3459 /*Check for duplicate packet */
3460 if (seq == tp->header.seq) {
3461 if (rx_stats_active)
3462 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3463 rxevent_Cancel(call->delayedAckEvent, call,
3464 RX_CALL_REFCOUNT_DELAY);
3465 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3471 /* If we find a higher sequence packet, break out and
3472 * insert the new packet here. */
3473 if (seq < tp->header.seq)
3475 /* Check for missing packet */
3476 if (tp->header.seq != prev + 1) {
3480 prev = tp->header.seq;
3483 /* Keep track of whether we have received the last packet. */
3484 if (flags & RX_LAST_PACKET) {
3485 call->flags |= RX_CALL_HAVE_LAST;
3488 /* It's within the window: add it to the the receive queue.
3489 * tp is left by the previous loop either pointing at the
3490 * packet before which to insert the new packet, or at the
3491 * queue head if the queue is empty or the packet should be
3493 np->flags |= RX_PKTFLAG_RQ;
3494 #ifdef RXDEBUG_PACKET
3496 #endif /* RXDEBUG_PACKET */
3497 queue_InsertBefore(tp, np);
3501 /* Check whether we have all of the packets for this call */
3502 if ((call->flags & RX_CALL_HAVE_LAST)
3503 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3504 afs_uint32 tseq; /* temporary sequence number */
3507 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3508 if (tseq != tp->header.seq)
3510 if (tp->header.flags & RX_LAST_PACKET) {
3511 call->flags |= RX_CALL_RECEIVE_DONE;
3518 /* We need to send an ack of the packet is out of sequence,
3519 * or if an ack was requested by the peer. */
3520 if (seq != prev + 1 || missing) {
3521 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3522 } else if (flags & RX_REQUEST_ACK) {
3523 ackNeeded = RX_ACK_REQUESTED;
3526 /* Acknowledge the last packet for each call */
3527 if (flags & RX_LAST_PACKET) {
3538 * If the receiver is waiting for an iovec, fill the iovec
3539 * using the data from the receive queue */
3540 if (call->flags & RX_CALL_IOVEC_WAIT) {
3541 didHardAck = rxi_FillReadVec(call, serial);
3542 /* the call may have been aborted */
3551 /* Wakeup the reader if any */
3552 if ((call->flags & RX_CALL_READER_WAIT)
3553 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3554 || (call->iovNext >= call->iovMax)
3555 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3556 call->flags &= ~RX_CALL_READER_WAIT;
3557 #ifdef RX_ENABLE_LOCKS
3558 CV_BROADCAST(&call->cv_rq);
3560 osi_rxWakeup(&call->rq);
3566 * Send an ack when requested by the peer, or once every
3567 * rxi_SoftAckRate packets until the last packet has been
3568 * received. Always send a soft ack for the last packet in
3569 * the server's reply. */
3571 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3572 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3573 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3574 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3575 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3576 } else if (call->nSoftAcks) {
3577 clock_GetTime(&now);
3579 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3580 clock_Add(&when, &rx_lastAckDelay);
3582 clock_Add(&when, &rx_softAckDelay);
3584 if (!call->delayedAckEvent
3585 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3586 rxevent_Cancel(call->delayedAckEvent, call,
3587 RX_CALL_REFCOUNT_DELAY);
3588 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3589 call->delayedAckEvent =
3590 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3592 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3593 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3600 static void rxi_ComputeRate();
3604 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3606 struct rx_peer *peer = conn->peer;
3608 MUTEX_ENTER(&peer->peer_lock);
3609 peer->lastReachTime = clock_Sec();
3610 MUTEX_EXIT(&peer->peer_lock);
3612 MUTEX_ENTER(&conn->conn_data_lock);
3613 if (conn->flags & RX_CONN_ATTACHWAIT) {
3616 conn->flags &= ~RX_CONN_ATTACHWAIT;
3617 MUTEX_EXIT(&conn->conn_data_lock);
3619 for (i = 0; i < RX_MAXCALLS; i++) {
3620 struct rx_call *call = conn->call[i];
3623 MUTEX_ENTER(&call->lock);
3624 /* tnop can be null if newcallp is null */
3625 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3627 MUTEX_EXIT(&call->lock);
3631 MUTEX_EXIT(&conn->conn_data_lock);
3634 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3636 rx_ack_reason(int reason)
3639 case RX_ACK_REQUESTED:
3641 case RX_ACK_DUPLICATE:
3643 case RX_ACK_OUT_OF_SEQUENCE:
3645 case RX_ACK_EXCEEDS_WINDOW:
3647 case RX_ACK_NOSPACE:
3651 case RX_ACK_PING_RESPONSE:
3664 /* rxi_ComputePeerNetStats
3666 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3667 * estimates (like RTT and throughput) based on ack packets. Caller
3668 * must ensure that the packet in question is the right one (i.e.
3669 * serial number matches).
3672 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3673 struct rx_ackPacket *ap, struct rx_packet *np)
3675 struct rx_peer *peer = call->conn->peer;
3677 /* Use RTT if not delayed by client and
3678 * ignore packets that were retransmitted. */
3679 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3680 ap->reason != RX_ACK_DELAY &&
3681 clock_Eq(&p->timeSent, &p->firstSent))
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(struct rx_call *call, struct rx_packet *np,
3693 struct rx_ackPacket *ap;
3695 struct rx_packet *tp;
3696 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3697 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;
3708 int newAckCount = 0;
3709 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3710 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3712 if (rx_stats_active)
3713 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3714 ap = (struct rx_ackPacket *)rx_DataOf(np);
3715 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3717 return np; /* truncated ack packet */
3719 /* depends on ack packet struct */
3720 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3721 first = ntohl(ap->firstPacket);
3722 serial = ntohl(ap->serial);
3723 /* temporarily disabled -- needs to degrade over time
3724 * skew = ntohs(ap->maxSkew); */
3726 /* Ignore ack packets received out of order */
3727 if (first < call->tfirst) {
3731 if (np->header.flags & RX_SLOW_START_OK) {
3732 call->flags |= RX_CALL_SLOW_START_OK;
3735 if (ap->reason == RX_ACK_PING_RESPONSE)
3736 rxi_UpdatePeerReach(conn, call);
3740 if (rxdebug_active) {
3744 len = _snprintf(msg, sizeof(msg),
3745 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3746 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3747 ntohl(ap->serial), ntohl(ap->previousPacket),
3748 (unsigned int)np->header.seq, (unsigned int)skew,
3749 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3753 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3754 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3758 OutputDebugString(msg);
3760 #else /* AFS_NT40_ENV */
3763 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3764 ap->reason, ntohl(ap->previousPacket),
3765 (unsigned int)np->header.seq, (unsigned int)serial,
3766 (unsigned int)skew, ntohl(ap->firstPacket));
3769 for (offset = 0; offset < nAcks; offset++)
3770 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3775 #endif /* AFS_NT40_ENV */
3778 /* Update the outgoing packet skew value to the latest value of
3779 * the peer's incoming packet skew value. The ack packet, of
3780 * course, could arrive out of order, but that won't affect things
3782 MUTEX_ENTER(&peer->peer_lock);
3783 peer->outPacketSkew = skew;
3785 /* Check for packets that no longer need to be transmitted, and
3786 * discard them. This only applies to packets positively
3787 * acknowledged as having been sent to the peer's upper level.
3788 * All other packets must be retained. So only packets with
3789 * sequence numbers < ap->firstPacket are candidates. */
3790 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3791 if (tp->header.seq >= first)
3793 call->tfirst = tp->header.seq + 1;
3794 rxi_ComputePeerNetStats(call, tp, ap, np);
3795 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3798 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3799 /* XXX Hack. Because we have to release the global rx lock when sending
3800 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3801 * in rxi_Start sending packets out because packets may move to the
3802 * freePacketQueue as result of being here! So we drop these packets until
3803 * we're safely out of the traversing. Really ugly!
3804 * To make it even uglier, if we're using fine grain locking, we can
3805 * set the ack bits in the packets and have rxi_Start remove the packets
3806 * when it's done transmitting.
3808 if (call->flags & RX_CALL_TQ_BUSY) {
3809 #ifdef RX_ENABLE_LOCKS
3810 tp->flags |= RX_PKTFLAG_ACKED;
3811 call->flags |= RX_CALL_TQ_SOME_ACKED;
3812 #else /* RX_ENABLE_LOCKS */
3814 #endif /* RX_ENABLE_LOCKS */
3816 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3819 tp->flags &= ~RX_PKTFLAG_TQ;
3820 #ifdef RXDEBUG_PACKET
3822 #endif /* RXDEBUG_PACKET */
3823 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3828 /* Give rate detector a chance to respond to ping requests */
3829 if (ap->reason == RX_ACK_PING_RESPONSE) {
3830 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3834 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3836 /* Now go through explicit acks/nacks and record the results in
3837 * the waiting packets. These are packets that can't be released
3838 * yet, even with a positive acknowledge. This positive
3839 * acknowledge only means the packet has been received by the
3840 * peer, not that it will be retained long enough to be sent to
3841 * the peer's upper level. In addition, reset the transmit timers
3842 * of any missing packets (those packets that must be missing
3843 * because this packet was out of sequence) */
3845 call->nSoftAcked = 0;
3846 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3847 /* Update round trip time if the ack was stimulated on receipt
3849 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3850 #ifdef RX_ENABLE_LOCKS
3851 if (tp->header.seq >= first)
3852 #endif /* RX_ENABLE_LOCKS */
3853 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3854 rxi_ComputePeerNetStats(call, tp, ap, np);
3856 /* Set the acknowledge flag per packet based on the
3857 * information in the ack packet. An acknowlegded packet can
3858 * be downgraded when the server has discarded a packet it
3859 * soacked previously, or when an ack packet is received
3860 * out of sequence. */
3861 if (tp->header.seq < first) {
3862 /* Implicit ack information */
3863 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3866 tp->flags |= RX_PKTFLAG_ACKED;
3867 } else if (tp->header.seq < first + nAcks) {
3868 /* Explicit ack information: set it in the packet appropriately */
3869 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3870 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3872 tp->flags |= RX_PKTFLAG_ACKED;
3879 } else /* RX_ACK_TYPE_NACK */ {
3880 tp->flags &= ~RX_PKTFLAG_ACKED;
3884 tp->flags &= ~RX_PKTFLAG_ACKED;
3889 * Following the suggestion of Phil Kern, we back off the peer's
3890 * timeout value for future packets until a successful response
3891 * is received for an initial transmission.
3893 if (missing && !backedOff) {
3894 struct clock c = peer->timeout;
3895 struct clock max_to = {3, 0};
3897 clock_Add(&peer->timeout, &c);
3898 if (clock_Gt(&peer->timeout, &max_to))
3899 peer->timeout = max_to;
3903 /* If packet isn't yet acked, and it has been transmitted at least
3904 * once, reset retransmit time using latest timeout
3905 * ie, this should readjust the retransmit timer for all outstanding
3906 * packets... So we don't just retransmit when we should know better*/
3908 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3909 tp->retryTime = tp->timeSent;
3910 clock_Add(&tp->retryTime, &peer->timeout);
3911 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3912 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3916 /* If the window has been extended by this acknowledge packet,
3917 * then wakeup a sender waiting in alloc for window space, or try
3918 * sending packets now, if he's been sitting on packets due to
3919 * lack of window space */
3920 if (call->tnext < (call->tfirst + call->twind)) {
3921 #ifdef RX_ENABLE_LOCKS
3922 CV_SIGNAL(&call->cv_twind);
3924 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3925 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3926 osi_rxWakeup(&call->twind);
3929 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3930 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3934 /* if the ack packet has a receivelen field hanging off it,
3935 * update our state */
3936 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3939 /* If the ack packet has a "recommended" size that is less than
3940 * what I am using now, reduce my size to match */
3941 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
3942 (int)sizeof(afs_int32), &tSize);
3943 tSize = (afs_uint32) ntohl(tSize);
3944 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3946 /* Get the maximum packet size to send to this peer */
3947 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3949 tSize = (afs_uint32) ntohl(tSize);
3950 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3951 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3953 /* sanity check - peer might have restarted with different params.
3954 * If peer says "send less", dammit, send less... Peer should never
3955 * be unable to accept packets of the size that prior AFS versions would
3956 * send without asking. */
3957 if (peer->maxMTU != tSize) {
3958 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3960 peer->maxMTU = tSize;
3961 peer->MTU = MIN(tSize, peer->MTU);
3962 call->MTU = MIN(call->MTU, tSize);
3965 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3968 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
3969 (int)sizeof(afs_int32), &tSize);
3970 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3971 if (tSize < call->twind) { /* smaller than our send */
3972 call->twind = tSize; /* window, we must send less... */
3973 call->ssthresh = MIN(call->twind, call->ssthresh);
3974 call->conn->twind[call->channel] = call->twind;
3977 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3978 * network MTU confused with the loopback MTU. Calculate the
3979 * maximum MTU here for use in the slow start code below.
3981 maxMTU = peer->maxMTU;
3982 /* Did peer restart with older RX version? */
3983 if (peer->maxDgramPackets > 1) {
3984 peer->maxDgramPackets = 1;
3986 } else if (np->length >=
3987 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3990 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
3991 sizeof(afs_int32), &tSize);
3992 tSize = (afs_uint32) ntohl(tSize);
3994 * As of AFS 3.5 we set the send window to match the receive window.
3996 if (tSize < call->twind) {
3997 call->twind = tSize;
3998 call->conn->twind[call->channel] = call->twind;
3999 call->ssthresh = MIN(call->twind, call->ssthresh);
4000 } else if (tSize > call->twind) {
4001 call->twind = tSize;
4002 call->conn->twind[call->channel] = call->twind;
4006 * As of AFS 3.5, a jumbogram is more than one fixed size
4007 * packet transmitted in a single UDP datagram. If the remote
4008 * MTU is smaller than our local MTU then never send a datagram
4009 * larger than the natural MTU.
4012 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4013 (int)sizeof(afs_int32), &tSize);
4014 maxDgramPackets = (afs_uint32) ntohl(tSize);
4015 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4017 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4018 maxDgramPackets = MIN(maxDgramPackets, tSize);
4019 if (maxDgramPackets > 1) {
4020 peer->maxDgramPackets = maxDgramPackets;
4021 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4023 peer->maxDgramPackets = 1;
4024 call->MTU = peer->natMTU;
4026 } else if (peer->maxDgramPackets > 1) {
4027 /* Restarted with lower version of RX */
4028 peer->maxDgramPackets = 1;
4030 } else if (peer->maxDgramPackets > 1
4031 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4032 /* Restarted with lower version of RX */
4033 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4034 peer->natMTU = OLD_MAX_PACKET_SIZE;
4035 peer->MTU = OLD_MAX_PACKET_SIZE;
4036 peer->maxDgramPackets = 1;
4037 peer->nDgramPackets = 1;
4039 call->MTU = OLD_MAX_PACKET_SIZE;
4044 * Calculate how many datagrams were successfully received after
4045 * the first missing packet and adjust the negative ack counter
4050 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4051 if (call->nNacks < nNacked) {
4052 call->nNacks = nNacked;
4055 call->nAcks += newAckCount;
4059 if (call->flags & RX_CALL_FAST_RECOVER) {
4061 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4063 call->flags &= ~RX_CALL_FAST_RECOVER;
4064 call->cwind = call->nextCwind;
4065 call->nextCwind = 0;
4068 call->nCwindAcks = 0;
4069 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4070 /* Three negative acks in a row trigger congestion recovery */
4071 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4072 MUTEX_EXIT(&peer->peer_lock);
4073 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4074 /* someone else is waiting to start recovery */
4077 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4078 rxi_WaitforTQBusy(call);
4079 MUTEX_ENTER(&peer->peer_lock);
4080 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4081 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4082 call->flags |= RX_CALL_FAST_RECOVER;
4083 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4085 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4086 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4087 call->nextCwind = call->ssthresh;
4090 peer->MTU = call->MTU;
4091 peer->cwind = call->nextCwind;
4092 peer->nDgramPackets = call->nDgramPackets;
4094 call->congestSeq = peer->congestSeq;
4095 /* Reset the resend times on the packets that were nacked
4096 * so we will retransmit as soon as the window permits*/
4097 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4099 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4100 clock_Zero(&tp->retryTime);
4102 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4107 /* If cwind is smaller than ssthresh, then increase
4108 * the window one packet for each ack we receive (exponential
4110 * If cwind is greater than or equal to ssthresh then increase
4111 * the congestion window by one packet for each cwind acks we
4112 * receive (linear growth). */
4113 if (call->cwind < call->ssthresh) {
4115 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4116 call->nCwindAcks = 0;
4118 call->nCwindAcks += newAckCount;
4119 if (call->nCwindAcks >= call->cwind) {
4120 call->nCwindAcks = 0;
4121 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4125 * If we have received several acknowledgements in a row then
4126 * it is time to increase the size of our datagrams
4128 if ((int)call->nAcks > rx_nDgramThreshold) {
4129 if (peer->maxDgramPackets > 1) {
4130 if (call->nDgramPackets < peer->maxDgramPackets) {
4131 call->nDgramPackets++;
4133 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4134 } else if (call->MTU < peer->maxMTU) {
4135 call->MTU += peer->natMTU;
4136 call->MTU = MIN(call->MTU, peer->maxMTU);
4142 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4144 /* Servers need to hold the call until all response packets have
4145 * been acknowledged. Soft acks are good enough since clients
4146 * are not allowed to clear their receive queues. */
4147 if (call->state == RX_STATE_HOLD
4148 && call->tfirst + call->nSoftAcked >= call->tnext) {
4149 call->state = RX_STATE_DALLY;
4150 rxi_ClearTransmitQueue(call, 0);
4151 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4152 } else if (!queue_IsEmpty(&call->tq)) {
4153 rxi_Start(0, call, 0, istack);
4158 /* Received a response to a challenge packet */
4160 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4161 struct rx_packet *np, int istack)
4165 /* Ignore the packet if we're the client */
4166 if (conn->type == RX_CLIENT_CONNECTION)
4169 /* If already authenticated, ignore the packet (it's probably a retry) */
4170 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4173 /* Otherwise, have the security object evaluate the response packet */
4174 error = RXS_CheckResponse(conn->securityObject, conn, np);
4176 /* If the response is invalid, reset the connection, sending
4177 * an abort to the peer */
4181 rxi_ConnectionError(conn, error);
4182 MUTEX_ENTER(&conn->conn_data_lock);
4183 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4184 MUTEX_EXIT(&conn->conn_data_lock);
4187 /* If the response is valid, any calls waiting to attach
4188 * servers can now do so */
4191 for (i = 0; i < RX_MAXCALLS; i++) {
4192 struct rx_call *call = conn->call[i];
4194 MUTEX_ENTER(&call->lock);
4195 if (call->state == RX_STATE_PRECALL)
4196 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4197 /* tnop can be null if newcallp is null */
4198 MUTEX_EXIT(&call->lock);
4202 /* Update the peer reachability information, just in case
4203 * some calls went into attach-wait while we were waiting
4204 * for authentication..
4206 rxi_UpdatePeerReach(conn, NULL);
4211 /* A client has received an authentication challenge: the security
4212 * object is asked to cough up a respectable response packet to send
4213 * back to the server. The server is responsible for retrying the
4214 * challenge if it fails to get a response. */
4217 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4218 struct rx_packet *np, int istack)
4222 /* Ignore the challenge if we're the server */
4223 if (conn->type == RX_SERVER_CONNECTION)
4226 /* Ignore the challenge if the connection is otherwise idle; someone's
4227 * trying to use us as an oracle. */
4228 if (!rxi_HasActiveCalls(conn))
4231 /* Send the security object the challenge packet. It is expected to fill
4232 * in the response. */
4233 error = RXS_GetResponse(conn->securityObject, conn, np);
4235 /* If the security object is unable to return a valid response, reset the
4236 * connection and send an abort to the peer. Otherwise send the response
4237 * packet to the peer connection. */
4239 rxi_ConnectionError(conn, error);
4240 MUTEX_ENTER(&conn->conn_data_lock);
4241 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4242 MUTEX_EXIT(&conn->conn_data_lock);
4244 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4245 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4251 /* Find an available server process to service the current request in
4252 * the given call structure. If one isn't available, queue up this
4253 * call so it eventually gets one */
4255 rxi_AttachServerProc(struct rx_call *call,
4256 osi_socket socket, int *tnop,
4257 struct rx_call **newcallp)
4259 struct rx_serverQueueEntry *sq;
4260 struct rx_service *service = call->conn->service;
4263 /* May already be attached */
4264 if (call->state == RX_STATE_ACTIVE)
4267 MUTEX_ENTER(&rx_serverPool_lock);
4269 haveQuota = QuotaOK(service);
4270 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4271 /* If there are no processes available to service this call,
4272 * put the call on the incoming call queue (unless it's
4273 * already on the queue).
4275 #ifdef RX_ENABLE_LOCKS
4277 ReturnToServerPool(service);
4278 #endif /* RX_ENABLE_LOCKS */
4280 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4281 call->flags |= RX_CALL_WAIT_PROC;
4282 MUTEX_ENTER(&rx_waiting_mutex);
4285 MUTEX_EXIT(&rx_waiting_mutex);
4286 rxi_calltrace(RX_CALL_ARRIVAL, call);
4287 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4288 queue_Append(&rx_incomingCallQueue, call);
4291 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4293 /* If hot threads are enabled, and both newcallp and sq->socketp
4294 * are non-null, then this thread will process the call, and the
4295 * idle server thread will start listening on this threads socket.
4298 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4301 *sq->socketp = socket;
4302 clock_GetTime(&call->startTime);
4303 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4307 if (call->flags & RX_CALL_WAIT_PROC) {
4308 /* Conservative: I don't think this should happen */
4309 call->flags &= ~RX_CALL_WAIT_PROC;
4310 if (queue_IsOnQueue(call)) {
4313 MUTEX_ENTER(&rx_waiting_mutex);
4315 MUTEX_EXIT(&rx_waiting_mutex);
4318 call->state = RX_STATE_ACTIVE;
4319 call->mode = RX_MODE_RECEIVING;
4320 #ifdef RX_KERNEL_TRACE
4322 int glockOwner = ISAFS_GLOCK();
4325 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4326 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4332 if (call->flags & RX_CALL_CLEARED) {
4333 /* send an ack now to start the packet flow up again */
4334 call->flags &= ~RX_CALL_CLEARED;
4335 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4337 #ifdef RX_ENABLE_LOCKS
4340 service->nRequestsRunning++;
4341 if (service->nRequestsRunning <= service->minProcs)
4347 MUTEX_EXIT(&rx_serverPool_lock);
4350 /* Delay the sending of an acknowledge event for a short while, while
4351 * a new call is being prepared (in the case of a client) or a reply
4352 * is being prepared (in the case of a server). Rather than sending
4353 * an ack packet, an ACKALL packet is sent. */
4355 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4357 #ifdef RX_ENABLE_LOCKS
4359 MUTEX_ENTER(&call->lock);
4360 call->delayedAckEvent = NULL;
4361 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4363 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4364 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4366 MUTEX_EXIT(&call->lock);
4367 #else /* RX_ENABLE_LOCKS */
4369 call->delayedAckEvent = NULL;
4370 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4371 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4372 #endif /* RX_ENABLE_LOCKS */
4376 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4378 struct rx_call *call = arg1;
4379 #ifdef RX_ENABLE_LOCKS
4381 MUTEX_ENTER(&call->lock);
4382 if (event == call->delayedAckEvent)
4383 call->delayedAckEvent = NULL;
4384 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4386 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4388 MUTEX_EXIT(&call->lock);
4389 #else /* RX_ENABLE_LOCKS */
4391 call->delayedAckEvent = NULL;
4392 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4393 #endif /* RX_ENABLE_LOCKS */
4397 #ifdef RX_ENABLE_LOCKS
4398 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4399 * clearing them out.
4402 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4404 struct rx_packet *p, *tp;
4407 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4408 p->flags |= RX_PKTFLAG_ACKED;
4412 call->flags |= RX_CALL_TQ_CLEARME;
4413 call->flags |= RX_CALL_TQ_SOME_ACKED;
4416 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4417 call->tfirst = call->tnext;
4418 call->nSoftAcked = 0;
4420 if (call->flags & RX_CALL_FAST_RECOVER) {
4421 call->flags &= ~RX_CALL_FAST_RECOVER;
4422 call->cwind = call->nextCwind;
4423 call->nextCwind = 0;
4426 CV_SIGNAL(&call->cv_twind);
4428 #endif /* RX_ENABLE_LOCKS */
4430 /* Clear out the transmit queue for the current call (all packets have
4431 * been received by peer) */
4433 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4435 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4436 struct rx_packet *p, *tp;
4438 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4440 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4441 p->flags |= RX_PKTFLAG_ACKED;
4445 call->flags |= RX_CALL_TQ_CLEARME;
4446 call->flags |= RX_CALL_TQ_SOME_ACKED;
4449 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4450 #ifdef RXDEBUG_PACKET
4452 #endif /* RXDEBUG_PACKET */
4453 rxi_FreePackets(0, &call->tq);
4454 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4455 call->flags &= ~RX_CALL_TQ_CLEARME;
4457 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4459 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4460 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4461 call->nSoftAcked = 0;
4463 if (call->flags & RX_CALL_FAST_RECOVER) {
4464 call->flags &= ~RX_CALL_FAST_RECOVER;
4465 call->cwind = call->nextCwind;
4467 #ifdef RX_ENABLE_LOCKS
4468 CV_SIGNAL(&call->cv_twind);
4470 osi_rxWakeup(&call->twind);
4475 rxi_ClearReceiveQueue(struct rx_call *call)
4477 if (queue_IsNotEmpty(&call->rq)) {
4480 count = rxi_FreePackets(0, &call->rq);
4481 rx_packetReclaims += count;
4482 #ifdef RXDEBUG_PACKET
4484 if ( call->rqc != 0 )
4485 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0", call, call->rqc));
4487 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4489 if (call->state == RX_STATE_PRECALL) {
4490 call->flags |= RX_CALL_CLEARED;
4494 /* Send an abort packet for the specified call */
4496 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4497 int istack, int force)
4500 struct clock when, now;
4505 /* Clients should never delay abort messages */
4506 if (rx_IsClientConn(call->conn))
4509 if (call->abortCode != call->error) {
4510 call->abortCode = call->error;
4511 call->abortCount = 0;
4514 if (force || rxi_callAbortThreshhold == 0
4515 || call->abortCount < rxi_callAbortThreshhold) {
4516 if (call->delayedAbortEvent) {
4517 rxevent_Cancel(call->delayedAbortEvent, call,
4518 RX_CALL_REFCOUNT_ABORT);
4520 error = htonl(call->error);
4523 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4524 (char *)&error, sizeof(error), istack);
4525 } else if (!call->delayedAbortEvent) {
4526 clock_GetTime(&now);
4528 clock_Addmsec(&when, rxi_callAbortDelay);
4529 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4530 call->delayedAbortEvent =
4531 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4536 /* Send an abort packet for the specified connection. Packet is an
4537 * optional pointer to a packet that can be used to send the abort.
4538 * Once the number of abort messages reaches the threshhold, an
4539 * event is scheduled to send the abort. Setting the force flag
4540 * overrides sending delayed abort messages.
4542 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4543 * to send the abort packet.
4546 rxi_SendConnectionAbort(struct rx_connection *conn,
4547 struct rx_packet *packet, int istack, int force)
4550 struct clock when, now;
4555 /* Clients should never delay abort messages */
4556 if (rx_IsClientConn(conn))
4559 if (force || rxi_connAbortThreshhold == 0
4560 || conn->abortCount < rxi_connAbortThreshhold) {
4561 if (conn->delayedAbortEvent) {
4562 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4564 error = htonl(conn->error);
4566 MUTEX_EXIT(&conn->conn_data_lock);
4568 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4569 RX_PACKET_TYPE_ABORT, (char *)&error,
4570 sizeof(error), istack);
4571 MUTEX_ENTER(&conn->conn_data_lock);
4572 } else if (!conn->delayedAbortEvent) {
4573 clock_GetTime(&now);
4575 clock_Addmsec(&when, rxi_connAbortDelay);
4576 conn->delayedAbortEvent =
4577 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4582 /* Associate an error all of the calls owned by a connection. Called
4583 * with error non-zero. This is only for really fatal things, like
4584 * bad authentication responses. The connection itself is set in
4585 * error at this point, so that future packets received will be
4588 rxi_ConnectionError(struct rx_connection *conn,
4594 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d", conn, error));
4596 MUTEX_ENTER(&conn->conn_data_lock);
4597 if (conn->challengeEvent)
4598 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4599 if (conn->checkReachEvent) {
4600 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4601 conn->checkReachEvent = 0;
4602 conn->flags &= ~RX_CONN_ATTACHWAIT;
4605 MUTEX_EXIT(&conn->conn_data_lock);
4606 for (i = 0; i < RX_MAXCALLS; i++) {
4607 struct rx_call *call = conn->call[i];
4609 MUTEX_ENTER(&call->lock);
4610 rxi_CallError(call, error);
4611 MUTEX_EXIT(&call->lock);
4614 conn->error = error;
4615 if (rx_stats_active)
4616 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4621 rxi_CallError(struct rx_call *call, afs_int32 error)
4624 osirx_AssertMine(&call->lock, "rxi_CallError");
4626 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d", call, error, call->error));
4628 error = call->error;
4630 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4631 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4632 rxi_ResetCall(call, 0);
4635 rxi_ResetCall(call, 0);
4637 call->error = error;
4638 call->mode = RX_MODE_ERROR;
4641 /* Reset various fields in a call structure, and wakeup waiting
4642 * processes. Some fields aren't changed: state & mode are not
4643 * touched (these must be set by the caller), and bufptr, nLeft, and
4644 * nFree are not reset, since these fields are manipulated by
4645 * unprotected macros, and may only be reset by non-interrupting code.
4648 /* this code requires that call->conn be set properly as a pre-condition. */
4649 #endif /* ADAPT_WINDOW */
4652 rxi_ResetCall(struct rx_call *call, int newcall)
4655 struct rx_peer *peer;
4656 struct rx_packet *packet;
4658 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4660 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
4662 /* Notify anyone who is waiting for asynchronous packet arrival */
4663 if (call->arrivalProc) {
4664 (*call->arrivalProc) (call, call->arrivalProcHandle,
4665 call->arrivalProcArg);
4666 call->arrivalProc = (void (*)())0;
4669 if (call->delayedAbortEvent) {
4670 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4671 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4673 rxi_SendCallAbort(call, packet, 0, 1);
4674 rxi_FreePacket(packet);
4679 * Update the peer with the congestion information in this call
4680 * so other calls on this connection can pick up where this call
4681 * left off. If the congestion sequence numbers don't match then
4682 * another call experienced a retransmission.
4684 peer = call->conn->peer;
4685 MUTEX_ENTER(&peer->peer_lock);
4687 if (call->congestSeq == peer->congestSeq) {
4688 peer->cwind = MAX(peer->cwind, call->cwind);
4689 peer->MTU = MAX(peer->MTU, call->MTU);
4690 peer->nDgramPackets =
4691 MAX(peer->nDgramPackets, call->nDgramPackets);
4694 call->abortCode = 0;
4695 call->abortCount = 0;
4697 if (peer->maxDgramPackets > 1) {
4698 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4700 call->MTU = peer->MTU;
4702 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4703 call->ssthresh = rx_maxSendWindow;
4704 call->nDgramPackets = peer->nDgramPackets;
4705 call->congestSeq = peer->congestSeq;
4706 MUTEX_EXIT(&peer->peer_lock);
4708 flags = call->flags;
4709 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4710 if (flags & RX_CALL_TQ_BUSY) {
4711 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4712 call->flags |= (flags & RX_CALL_TQ_WAIT);
4714 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4716 rxi_ClearTransmitQueue(call, 1);
4717 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4718 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4719 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4722 while (call->tqWaiters) {
4723 #ifdef RX_ENABLE_LOCKS
4724 CV_BROADCAST(&call->cv_tq);
4725 #else /* RX_ENABLE_LOCKS */
4726 osi_rxWakeup(&call->tq);
4727 #endif /* RX_ENABLE_LOCKS */
4732 rxi_ClearReceiveQueue(call);
4733 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4735 if (call->currentPacket) {
4736 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4737 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4738 queue_Prepend(&call->iovq, call->currentPacket);
4739 #ifdef RXDEBUG_PACKET
4741 #endif /* RXDEBUG_PACKET */
4742 call->currentPacket = (struct rx_packet *)0;
4744 call->curlen = call->nLeft = call->nFree = 0;
4746 #ifdef RXDEBUG_PACKET
4749 rxi_FreePackets(0, &call->iovq);
4752 call->twind = call->conn->twind[call->channel];
4753 call->rwind = call->conn->rwind[call->channel];
4754 call->nSoftAcked = 0;
4755 call->nextCwind = 0;
4758 call->nCwindAcks = 0;
4759 call->nSoftAcks = 0;
4760 call->nHardAcks = 0;
4762 call->tfirst = call->rnext = call->tnext = 1;
4764 call->lastAcked = 0;
4765 call->localStatus = call->remoteStatus = 0;
4767 if (flags & RX_CALL_READER_WAIT) {
4768 #ifdef RX_ENABLE_LOCKS
4769 CV_BROADCAST(&call->cv_rq);
4771 osi_rxWakeup(&call->rq);
4774 if (flags & RX_CALL_WAIT_PACKETS) {
4775 MUTEX_ENTER(&rx_freePktQ_lock);
4776 rxi_PacketsUnWait(); /* XXX */
4777 MUTEX_EXIT(&rx_freePktQ_lock);
4779 #ifdef RX_ENABLE_LOCKS
4780 CV_SIGNAL(&call->cv_twind);
4782 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4783 osi_rxWakeup(&call->twind);
4786 #ifdef RX_ENABLE_LOCKS
4787 /* The following ensures that we don't mess with any queue while some
4788 * other thread might also be doing so. The call_queue_lock field is
4789 * is only modified under the call lock. If the call is in the process
4790 * of being removed from a queue, the call is not locked until the
4791 * the queue lock is dropped and only then is the call_queue_lock field
4792 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4793 * Note that any other routine which removes a call from a queue has to
4794 * obtain the queue lock before examing the queue and removing the call.
4796 if (call->call_queue_lock) {
4797 MUTEX_ENTER(call->call_queue_lock);
4798 if (queue_IsOnQueue(call)) {
4800 if (flags & RX_CALL_WAIT_PROC) {
4802 MUTEX_ENTER(&rx_waiting_mutex);
4804 MUTEX_EXIT(&rx_waiting_mutex);
4807 MUTEX_EXIT(call->call_queue_lock);
4808 CLEAR_CALL_QUEUE_LOCK(call);
4810 #else /* RX_ENABLE_LOCKS */
4811 if (queue_IsOnQueue(call)) {
4813 if (flags & RX_CALL_WAIT_PROC)
4816 #endif /* RX_ENABLE_LOCKS */
4818 rxi_KeepAliveOff(call);
4819 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4822 /* Send an acknowledge for the indicated packet (seq,serial) of the
4823 * indicated call, for the indicated reason (reason). This
4824 * acknowledge will specifically acknowledge receiving the packet, and
4825 * will also specify which other packets for this call have been
4826 * received. This routine returns the packet that was used to the
4827 * caller. The caller is responsible for freeing it or re-using it.
4828 * This acknowledgement also returns the highest sequence number
4829 * actually read out by the higher level to the sender; the sender
4830 * promises to keep around packets that have not been read by the
4831 * higher level yet (unless, of course, the sender decides to abort
4832 * the call altogether). Any of p, seq, serial, pflags, or reason may
4833 * be set to zero without ill effect. That is, if they are zero, they
4834 * will not convey any information.
4835 * NOW there is a trailer field, after the ack where it will safely be
4836 * ignored by mundanes, which indicates the maximum size packet this
4837 * host can swallow. */
4839 struct rx_packet *optionalPacket; use to send ack (or null)
4840 int seq; Sequence number of the packet we are acking
4841 int serial; Serial number of the packet
4842 int pflags; Flags field from packet header
4843 int reason; Reason an acknowledge was prompted
4847 rxi_SendAck(struct rx_call *call,
4848 struct rx_packet *optionalPacket, int serial, int reason,
4851 struct rx_ackPacket *ap;
4852 struct rx_packet *rqp;
4853 struct rx_packet *nxp; /* For queue_Scan */
4854 struct rx_packet *p;
4857 #ifdef RX_ENABLE_TSFPQ
4858 struct rx_ts_info_t * rx_ts_info;
4862 * Open the receive window once a thread starts reading packets
4864 if (call->rnext > 1) {
4865 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4868 call->nHardAcks = 0;
4869 call->nSoftAcks = 0;
4870 if (call->rnext > call->lastAcked)
4871 call->lastAcked = call->rnext;
4875 rx_computelen(p, p->length); /* reset length, you never know */
4876 } /* where that's been... */
4877 #ifdef RX_ENABLE_TSFPQ
4879 RX_TS_INFO_GET(rx_ts_info);
4880 if ((p = rx_ts_info->local_special_packet)) {
4881 rx_computelen(p, p->length);
4882 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4883 rx_ts_info->local_special_packet = p;
4884 } else { /* We won't send the ack, but don't panic. */
4885 return optionalPacket;
4889 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4890 /* We won't send the ack, but don't panic. */
4891 return optionalPacket;
4896 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4899 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4900 #ifndef RX_ENABLE_TSFPQ
4901 if (!optionalPacket)
4904 return optionalPacket;
4906 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4907 if (rx_Contiguous(p) < templ) {
4908 #ifndef RX_ENABLE_TSFPQ
4909 if (!optionalPacket)
4912 return optionalPacket;
4917 /* MTUXXX failing to send an ack is very serious. We should */
4918 /* try as hard as possible to send even a partial ack; it's */
4919 /* better than nothing. */
4920 ap = (struct rx_ackPacket *)rx_DataOf(p);
4921 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4922 ap->reason = reason;
4924 /* The skew computation used to be bogus, I think it's better now. */
4925 /* We should start paying attention to skew. XXX */
4926 ap->serial = htonl(serial);
4927 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4929 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4930 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4932 /* No fear of running out of ack packet here because there can only be at most
4933 * one window full of unacknowledged packets. The window size must be constrained
4934 * to be less than the maximum ack size, of course. Also, an ack should always
4935 * fit into a single packet -- it should not ever be fragmented. */
4936 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4937 if (!rqp || !call->rq.next
4938 || (rqp->header.seq > (call->rnext + call->rwind))) {
4939 #ifndef RX_ENABLE_TSFPQ
4940 if (!optionalPacket)
4943 rxi_CallError(call, RX_CALL_DEAD);
4944 return optionalPacket;
4947 while (rqp->header.seq > call->rnext + offset)
4948 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4949 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4951 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4952 #ifndef RX_ENABLE_TSFPQ
4953 if (!optionalPacket)
4956 rxi_CallError(call, RX_CALL_DEAD);
4957 return optionalPacket;
4962 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4964 /* these are new for AFS 3.3 */
4965 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4966 templ = htonl(templ);
4967 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4968 templ = htonl(call->conn->peer->ifMTU);
4969 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4970 sizeof(afs_int32), &templ);
4972 /* new for AFS 3.4 */
4973 templ = htonl(call->rwind);
4974 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4975 sizeof(afs_int32), &templ);
4977 /* new for AFS 3.5 */
4978 templ = htonl(call->conn->peer->ifDgramPackets);
4979 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4980 sizeof(afs_int32), &templ);
4982 p->header.serviceId = call->conn->serviceId;
4983 p->header.cid = (call->conn->cid | call->channel);
4984 p->header.callNumber = *call->callNumber;
4986 p->header.securityIndex = call->conn->securityIndex;
4987 p->header.epoch = call->conn->epoch;
4988 p->header.type = RX_PACKET_TYPE_ACK;
4989 p->header.flags = RX_SLOW_START_OK;
4990 if (reason == RX_ACK_PING) {
4991 p->header.flags |= RX_REQUEST_ACK;
4993 clock_GetTime(&call->pingRequestTime);
4996 if (call->conn->type == RX_CLIENT_CONNECTION)
4997 p->header.flags |= RX_CLIENT_INITIATED;
5001 if (rxdebug_active) {
5005 len = _snprintf(msg, sizeof(msg),
5006 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5007 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5008 ntohl(ap->serial), ntohl(ap->previousPacket),
5009 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5010 ap->nAcks, ntohs(ap->bufferSpace) );
5014 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5015 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5019 OutputDebugString(msg);
5021 #else /* AFS_NT40_ENV */
5023 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5024 ap->reason, ntohl(ap->previousPacket),
5025 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5027 for (offset = 0; offset < ap->nAcks; offset++)
5028 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5033 #endif /* AFS_NT40_ENV */
5036 int i, nbytes = p->length;
5038 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5039 if (nbytes <= p->wirevec[i].iov_len) {
5042 savelen = p->wirevec[i].iov_len;
5044 p->wirevec[i].iov_len = nbytes;
5046 rxi_Send(call, p, istack);
5047 p->wirevec[i].iov_len = savelen;
5051 nbytes -= p->wirevec[i].iov_len;
5054 if (rx_stats_active)
5055 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5056 #ifndef RX_ENABLE_TSFPQ
5057 if (!optionalPacket)
5060 return optionalPacket; /* Return packet for re-use by caller */
5063 /* Send all of the packets in the list in single datagram */
5065 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5066 int istack, int moreFlag, struct clock *now,
5067 struct clock *retryTime, int resending)
5072 struct rx_connection *conn = call->conn;
5073 struct rx_peer *peer = conn->peer;
5075 MUTEX_ENTER(&peer->peer_lock);
5078 peer->reSends += len;
5079 if (rx_stats_active)
5080 rx_MutexAdd(rx_stats.dataPacketsSent, len, rx_stats_mutex);
5081 MUTEX_EXIT(&peer->peer_lock);
5083 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5087 /* Set the packet flags and schedule the resend events */
5088 /* Only request an ack for the last packet in the list */
5089 for (i = 0; i < len; i++) {
5090 list[i]->retryTime = *retryTime;
5091 if (list[i]->header.serial) {
5092 /* Exponentially backoff retry times */
5093 if (list[i]->backoff < MAXBACKOFF) {
5094 /* so it can't stay == 0 */
5095 list[i]->backoff = (list[i]->backoff << 1) + 1;
5098 clock_Addmsec(&(list[i]->retryTime),
5099 ((afs_uint32) list[i]->backoff) << 8);
5102 /* Wait a little extra for the ack on the last packet */
5103 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5104 clock_Addmsec(&(list[i]->retryTime), 400);
5107 /* Record the time sent */
5108 list[i]->timeSent = *now;
5110 /* Ask for an ack on retransmitted packets, on every other packet
5111 * if the peer doesn't support slow start. Ask for an ack on every
5112 * packet until the congestion window reaches the ack rate. */
5113 if (list[i]->header.serial) {
5115 if (rx_stats_active)
5116 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5118 /* improved RTO calculation- not Karn */
5119 list[i]->firstSent = *now;
5120 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5121 || (!(call->flags & RX_CALL_SLOW_START_OK)
5122 && (list[i]->header.seq & 1)))) {
5127 /* Tag this packet as not being the last in this group,
5128 * for the receiver's benefit */
5129 if (i < len - 1 || moreFlag) {
5130 list[i]->header.flags |= RX_MORE_PACKETS;
5133 /* Install the new retransmit time for the packet, and
5134 * record the time sent */
5135 list[i]->timeSent = *now;
5139 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5142 /* Since we're about to send a data packet to the peer, it's
5143 * safe to nuke any scheduled end-of-packets ack */
5144 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5146 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5147 MUTEX_EXIT(&call->lock);
5149 rxi_SendPacketList(call, conn, list, len, istack);
5151 rxi_SendPacket(call, conn, list[0], istack);
5153 MUTEX_ENTER(&call->lock);
5154 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5156 /* Update last send time for this call (for keep-alive
5157 * processing), and for the connection (so that we can discover
5158 * idle connections) */
5159 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5162 /* When sending packets we need to follow these rules:
5163 * 1. Never send more than maxDgramPackets in a jumbogram.
5164 * 2. Never send a packet with more than two iovecs in a jumbogram.
5165 * 3. Never send a retransmitted packet in a jumbogram.
5166 * 4. Never send more than cwind/4 packets in a jumbogram
5167 * We always keep the last list we should have sent so we
5168 * can set the RX_MORE_PACKETS flags correctly.
5171 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5172 int istack, struct clock *now, struct clock *retryTime,
5175 int i, cnt, lastCnt = 0;
5176 struct rx_packet **listP, **lastP = 0;
5177 struct rx_peer *peer = call->conn->peer;
5178 int morePackets = 0;
5180 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5181 /* Does the current packet force us to flush the current list? */
5183 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5184 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5186 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5188 /* If the call enters an error state stop sending, or if
5189 * we entered congestion recovery mode, stop sending */
5190 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5198 /* Add the current packet to the list if it hasn't been acked.
5199 * Otherwise adjust the list pointer to skip the current packet. */
5200 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5202 /* Do we need to flush the list? */
5203 if (cnt >= (int)peer->maxDgramPackets
5204 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5205 || list[i]->header.serial
5206 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5208 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5209 retryTime, resending);
5210 /* If the call enters an error state stop sending, or if
5211 * we entered congestion recovery mode, stop sending */
5213 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5218 listP = &list[i + 1];
5223 osi_Panic("rxi_SendList error");
5225 listP = &list[i + 1];
5229 /* Send the whole list when the call is in receive mode, when
5230 * the call is in eof mode, when we are in fast recovery mode,
5231 * and when we have the last packet */
5232 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5233 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5234 || (call->flags & RX_CALL_FAST_RECOVER)) {
5235 /* Check for the case where the current list contains
5236 * an acked packet. Since we always send retransmissions
5237 * in a separate packet, we only need to check the first
5238 * packet in the list */
5239 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5243 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5244 retryTime, resending);
5245 /* If the call enters an error state stop sending, or if
5246 * we entered congestion recovery mode, stop sending */
5247 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5251 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5254 } else if (lastCnt > 0) {
5255 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5260 #ifdef RX_ENABLE_LOCKS
5261 /* Call rxi_Start, below, but with the call lock held. */
5263 rxi_StartUnlocked(struct rxevent *event,
5264 void *arg0, void *arg1, int istack)
5266 struct rx_call *call = arg0;
5268 MUTEX_ENTER(&call->lock);
5269 rxi_Start(event, call, arg1, istack);
5270 MUTEX_EXIT(&call->lock);
5272 #endif /* RX_ENABLE_LOCKS */
5274 /* This routine is called when new packets are readied for
5275 * transmission and when retransmission may be necessary, or when the
5276 * transmission window or burst count are favourable. This should be
5277 * better optimized for new packets, the usual case, now that we've
5278 * got rid of queues of send packets. XXXXXXXXXXX */
5280 rxi_Start(struct rxevent *event,
5281 void *arg0, void *arg1, int istack)
5283 struct rx_call *call = arg0;
5285 struct rx_packet *p;
5286 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5287 struct rx_peer *peer = call->conn->peer;
5288 struct clock now, usenow, retryTime;
5292 struct rx_packet **xmitList;
5295 /* If rxi_Start is being called as a result of a resend event,
5296 * then make sure that the event pointer is removed from the call
5297 * structure, since there is no longer a per-call retransmission
5299 if (event && event == call->resendEvent) {
5300 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5301 call->resendEvent = NULL;
5303 if (queue_IsEmpty(&call->tq)) {
5307 /* Timeouts trigger congestion recovery */
5308 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5309 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5310 /* someone else is waiting to start recovery */
5313 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5314 rxi_WaitforTQBusy(call);
5315 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5316 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5317 call->flags |= RX_CALL_FAST_RECOVER;
5318 if (peer->maxDgramPackets > 1) {
5319 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5321 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5323 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5324 call->nDgramPackets = 1;
5326 call->nextCwind = 1;
5329 MUTEX_ENTER(&peer->peer_lock);
5330 peer->MTU = call->MTU;
5331 peer->cwind = call->cwind;
5332 peer->nDgramPackets = 1;
5334 call->congestSeq = peer->congestSeq;
5335 MUTEX_EXIT(&peer->peer_lock);
5336 /* Clear retry times on packets. Otherwise, it's possible for
5337 * some packets in the queue to force resends at rates faster
5338 * than recovery rates.
5340 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5341 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5342 clock_Zero(&p->retryTime);
5347 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5348 if (rx_stats_active)
5349 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5354 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5355 /* Get clock to compute the re-transmit time for any packets
5356 * in this burst. Note, if we back off, it's reasonable to
5357 * back off all of the packets in the same manner, even if
5358 * some of them have been retransmitted more times than more
5360 * Do a dance to avoid blocking after setting now. */
5361 MUTEX_ENTER(&peer->peer_lock);
5362 retryTime = peer->timeout;
5363 MUTEX_EXIT(&peer->peer_lock);
5364 clock_GetTime(&now);
5365 clock_Add(&retryTime, &now);
5367 /* Send (or resend) any packets that need it, subject to
5368 * window restrictions and congestion burst control
5369 * restrictions. Ask for an ack on the last packet sent in
5370 * this burst. For now, we're relying upon the window being
5371 * considerably bigger than the largest number of packets that
5372 * are typically sent at once by one initial call to
5373 * rxi_Start. This is probably bogus (perhaps we should ask
5374 * for an ack when we're half way through the current
5375 * window?). Also, for non file transfer applications, this
5376 * may end up asking for an ack for every packet. Bogus. XXXX
5379 * But check whether we're here recursively, and let the other guy
5382 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5383 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5384 call->flags |= RX_CALL_TQ_BUSY;
5386 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5388 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5389 call->flags &= ~RX_CALL_NEED_START;
5390 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5392 maxXmitPackets = MIN(call->twind, call->cwind);
5393 xmitList = (struct rx_packet **)
5394 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5395 /* XXXX else we must drop any mtx we hold */
5396 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5398 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5400 if (xmitList == NULL)
5401 osi_Panic("rxi_Start, failed to allocate xmit list");
5402 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5403 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5404 /* We shouldn't be sending packets if a thread is waiting
5405 * to initiate congestion recovery */
5406 dpf(("call %d waiting to initiate fast recovery\n",
5407 *(call->callNumber)));
5411 && (call->flags & RX_CALL_FAST_RECOVER)) {
5412 /* Only send one packet during fast recovery */
5413 dpf(("call %d restricted to one packet per send during fast recovery\n",
5414 *(call->callNumber)));
5417 if ((p->flags & RX_PKTFLAG_FREE)
5418 || (!queue_IsEnd(&call->tq, nxp)
5419 && (nxp->flags & RX_PKTFLAG_FREE))
5420 || (p == (struct rx_packet *)&rx_freePacketQueue)
5421 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5422 osi_Panic("rxi_Start: xmit queue clobbered");
5424 if (p->flags & RX_PKTFLAG_ACKED) {
5425 /* Since we may block, don't trust this */
5426 usenow.sec = usenow.usec = 0;
5427 if (rx_stats_active)
5428 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5429 continue; /* Ignore this packet if it has been acknowledged */
5432 /* Turn off all flags except these ones, which are the same
5433 * on each transmission */
5434 p->header.flags &= RX_PRESET_FLAGS;
5436 if (p->header.seq >=
5437 call->tfirst + MIN((int)call->twind,
5438 (int)(call->nSoftAcked +
5440 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5441 /* Note: if we're waiting for more window space, we can
5442 * still send retransmits; hence we don't return here, but
5443 * break out to schedule a retransmit event */
5444 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5445 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
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 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u nextRetry %u.%06u\n",
5461 *(call->callNumber), p,
5463 p->retryTime.sec, p->retryTime.usec,
5464 retryTime.sec, retryTime.usec));
5465 xmitList[nXmitPackets++] = p;
5469 /* xmitList now hold pointers to all of the packets that are
5470 * ready to send. Now we loop to send the packets */
5471 if (nXmitPackets > 0) {
5472 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5473 &now, &retryTime, resending);
5476 maxXmitPackets * sizeof(struct rx_packet *));
5478 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5480 * TQ references no longer protected by this flag; they must remain
5481 * protected by the global lock.
5483 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5484 call->flags &= ~RX_CALL_TQ_BUSY;
5485 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5486 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5487 call, call->tqWaiters, call->flags));
5488 #ifdef RX_ENABLE_LOCKS
5489 osirx_AssertMine(&call->lock, "rxi_Start start");
5490 CV_BROADCAST(&call->cv_tq);
5491 #else /* RX_ENABLE_LOCKS */
5492 osi_rxWakeup(&call->tq);
5493 #endif /* RX_ENABLE_LOCKS */
5498 /* We went into the error state while sending packets. Now is
5499 * the time to reset the call. This will also inform the using
5500 * process that the call is in an error state.
5502 if (rx_stats_active)
5503 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5504 call->flags &= ~RX_CALL_TQ_BUSY;
5505 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5506 dpf(("call error %d while xmit %x has %d waiters and flags %d\n",
5507 call, call->error, call->tqWaiters, call->flags));
5508 #ifdef RX_ENABLE_LOCKS
5509 osirx_AssertMine(&call->lock, "rxi_Start middle");
5510 CV_BROADCAST(&call->cv_tq);
5511 #else /* RX_ENABLE_LOCKS */
5512 osi_rxWakeup(&call->tq);
5513 #endif /* RX_ENABLE_LOCKS */
5515 rxi_CallError(call, call->error);
5518 #ifdef RX_ENABLE_LOCKS
5519 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5521 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5522 /* Some packets have received acks. If they all have, we can clear
5523 * the transmit queue.
5526 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5527 if (p->header.seq < call->tfirst
5528 && (p->flags & RX_PKTFLAG_ACKED)) {
5530 p->flags &= ~RX_PKTFLAG_TQ;
5531 #ifdef RXDEBUG_PACKET
5539 call->flags |= RX_CALL_TQ_CLEARME;
5541 #endif /* RX_ENABLE_LOCKS */
5542 /* Don't bother doing retransmits if the TQ is cleared. */
5543 if (call->flags & RX_CALL_TQ_CLEARME) {
5544 rxi_ClearTransmitQueue(call, 1);
5546 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5549 /* Always post a resend event, if there is anything in the
5550 * queue, and resend is possible. There should be at least
5551 * one unacknowledged packet in the queue ... otherwise none
5552 * of these packets should be on the queue in the first place.
5554 if (call->resendEvent) {
5555 /* Cancel the existing event and post a new one */
5556 rxevent_Cancel(call->resendEvent, call,
5557 RX_CALL_REFCOUNT_RESEND);
5560 /* The retry time is the retry time on the first unacknowledged
5561 * packet inside the current window */
5563 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5564 /* Don't set timers for packets outside the window */
5565 if (p->header.seq >= call->tfirst + call->twind) {
5569 if (!(p->flags & RX_PKTFLAG_ACKED)
5570 && !clock_IsZero(&p->retryTime)) {
5572 retryTime = p->retryTime;
5577 /* Post a new event to re-run rxi_Start when retries may be needed */
5578 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5579 #ifdef RX_ENABLE_LOCKS
5580 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5582 rxevent_PostNow2(&retryTime, &usenow,
5584 (void *)call, 0, istack);
5585 #else /* RX_ENABLE_LOCKS */
5587 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5588 (void *)call, 0, istack);
5589 #endif /* RX_ENABLE_LOCKS */
5592 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5593 } while (call->flags & RX_CALL_NEED_START);
5595 * TQ references no longer protected by this flag; they must remain
5596 * protected by the global lock.
5598 call->flags &= ~RX_CALL_TQ_BUSY;
5599 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5600 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5601 call, call->tqWaiters, call->flags));
5602 #ifdef RX_ENABLE_LOCKS
5603 osirx_AssertMine(&call->lock, "rxi_Start end");
5604 CV_BROADCAST(&call->cv_tq);
5605 #else /* RX_ENABLE_LOCKS */
5606 osi_rxWakeup(&call->tq);
5607 #endif /* RX_ENABLE_LOCKS */
5610 call->flags |= RX_CALL_NEED_START;
5612 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5614 if (call->resendEvent) {
5615 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5620 /* Also adjusts the keep alive parameters for the call, to reflect
5621 * that we have just sent a packet (so keep alives aren't sent
5624 rxi_Send(struct rx_call *call, struct rx_packet *p,
5627 struct rx_connection *conn = call->conn;
5629 /* Stamp each packet with the user supplied status */
5630 p->header.userStatus = call->localStatus;
5632 /* Allow the security object controlling this call's security to
5633 * make any last-minute changes to the packet */
5634 RXS_SendPacket(conn->securityObject, call, p);
5636 /* Since we're about to send SOME sort of packet to the peer, it's
5637 * safe to nuke any scheduled end-of-packets ack */
5638 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5640 /* Actually send the packet, filling in more connection-specific fields */
5641 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5642 MUTEX_EXIT(&call->lock);
5643 rxi_SendPacket(call, conn, p, istack);
5644 MUTEX_ENTER(&call->lock);
5645 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5647 /* Update last send time for this call (for keep-alive
5648 * processing), and for the connection (so that we can discover
5649 * idle connections) */
5650 conn->lastSendTime = call->lastSendTime = clock_Sec();
5651 /* Don't count keepalives here, so idleness can be tracked. */
5652 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5653 call->lastSendData = call->lastSendTime;
5657 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5658 * that things are fine. Also called periodically to guarantee that nothing
5659 * falls through the cracks (e.g. (error + dally) connections have keepalive
5660 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5662 * haveCTLock Set if calling from rxi_ReapConnections
5664 #ifdef RX_ENABLE_LOCKS
5666 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5667 #else /* RX_ENABLE_LOCKS */
5669 rxi_CheckCall(struct rx_call *call)
5670 #endif /* RX_ENABLE_LOCKS */
5672 struct rx_connection *conn = call->conn;
5674 afs_uint32 deadTime;
5676 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5677 if (call->flags & RX_CALL_TQ_BUSY) {
5678 /* Call is active and will be reset by rxi_Start if it's
5679 * in an error state.
5684 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5686 (((afs_uint32) conn->secondsUntilDead << 10) +
5687 ((afs_uint32) conn->peer->rtt >> 3) +
5688 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5690 /* These are computed to the second (+- 1 second). But that's
5691 * good enough for these values, which should be a significant
5692 * number of seconds. */
5693 if (now > (call->lastReceiveTime + deadTime)) {
5694 if (call->state == RX_STATE_ACTIVE) {
5696 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5698 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5699 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5700 ip_stack_t *ipst = ns->netstack_ip;
5702 ire = ire_cache_lookup(call->conn->peer->host
5703 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5705 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5707 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5714 if (ire && ire->ire_max_frag > 0)
5715 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5716 #if defined(GLOBAL_NETSTACKID)
5720 #endif /* ADAPT_PMTU */
5721 rxi_CallError(call, RX_CALL_DEAD);
5724 #ifdef RX_ENABLE_LOCKS
5725 /* Cancel pending events */
5726 rxevent_Cancel(call->delayedAckEvent, call,
5727 RX_CALL_REFCOUNT_DELAY);
5728 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5729 rxevent_Cancel(call->keepAliveEvent, call,
5730 RX_CALL_REFCOUNT_ALIVE);
5731 if (call->refCount == 0) {
5732 rxi_FreeCall(call, haveCTLock);
5736 #else /* RX_ENABLE_LOCKS */
5739 #endif /* RX_ENABLE_LOCKS */
5741 /* Non-active calls are destroyed if they are not responding
5742 * to pings; active calls are simply flagged in error, so the
5743 * attached process can die reasonably gracefully. */
5745 /* see if we have a non-activity timeout */
5746 if (call->startWait && conn->idleDeadTime
5747 && ((call->startWait + conn->idleDeadTime) < now)) {
5748 if (call->state == RX_STATE_ACTIVE) {
5749 rxi_CallError(call, RX_CALL_TIMEOUT);
5753 if (call->lastSendData && conn->idleDeadTime && (conn->idleDeadErr != 0)
5754 && ((call->lastSendData + conn->idleDeadTime) < now)) {
5755 if (call->state == RX_STATE_ACTIVE) {
5756 rxi_CallError(call, conn->idleDeadErr);
5760 /* see if we have a hard timeout */
5761 if (conn->hardDeadTime
5762 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5763 if (call->state == RX_STATE_ACTIVE)
5764 rxi_CallError(call, RX_CALL_TIMEOUT);
5771 /* When a call is in progress, this routine is called occasionally to
5772 * make sure that some traffic has arrived (or been sent to) the peer.
5773 * If nothing has arrived in a reasonable amount of time, the call is
5774 * declared dead; if nothing has been sent for a while, we send a
5775 * keep-alive packet (if we're actually trying to keep the call alive)
5778 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5780 struct rx_call *call = arg1;
5781 struct rx_connection *conn;
5784 MUTEX_ENTER(&call->lock);
5785 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5786 if (event == call->keepAliveEvent)
5787 call->keepAliveEvent = NULL;
5790 #ifdef RX_ENABLE_LOCKS
5791 if (rxi_CheckCall(call, 0)) {
5792 MUTEX_EXIT(&call->lock);
5795 #else /* RX_ENABLE_LOCKS */
5796 if (rxi_CheckCall(call))
5798 #endif /* RX_ENABLE_LOCKS */
5800 /* Don't try to keep alive dallying calls */
5801 if (call->state == RX_STATE_DALLY) {
5802 MUTEX_EXIT(&call->lock);
5807 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
5808 /* Don't try to send keepalives if there is unacknowledged data */
5809 /* the rexmit code should be good enough, this little hack
5810 * doesn't quite work XXX */
5811 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5813 rxi_ScheduleKeepAliveEvent(call);
5814 MUTEX_EXIT(&call->lock);
5819 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
5821 if (!call->keepAliveEvent) {
5822 struct clock when, now;
5823 clock_GetTime(&now);
5825 when.sec += call->conn->secondsUntilPing;
5826 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5827 call->keepAliveEvent =
5828 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5832 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5834 rxi_KeepAliveOn(struct rx_call *call)
5836 /* Pretend last packet received was received now--i.e. if another
5837 * packet isn't received within the keep alive time, then the call
5838 * will die; Initialize last send time to the current time--even
5839 * if a packet hasn't been sent yet. This will guarantee that a
5840 * keep-alive is sent within the ping time */
5841 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5842 rxi_ScheduleKeepAliveEvent(call);
5845 /* This routine is called to send connection abort messages
5846 * that have been delayed to throttle looping clients. */
5848 rxi_SendDelayedConnAbort(struct rxevent *event,
5849 void *arg1, void *unused)
5851 struct rx_connection *conn = arg1;
5854 struct rx_packet *packet;
5856 MUTEX_ENTER(&conn->conn_data_lock);
5857 conn->delayedAbortEvent = NULL;
5858 error = htonl(conn->error);
5860 MUTEX_EXIT(&conn->conn_data_lock);
5861 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5864 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5865 RX_PACKET_TYPE_ABORT, (char *)&error,
5867 rxi_FreePacket(packet);
5871 /* This routine is called to send call abort messages
5872 * that have been delayed to throttle looping clients. */
5874 rxi_SendDelayedCallAbort(struct rxevent *event,
5875 void *arg1, void *dummy)
5877 struct rx_call *call = arg1;
5880 struct rx_packet *packet;
5882 MUTEX_ENTER(&call->lock);
5883 call->delayedAbortEvent = NULL;
5884 error = htonl(call->error);
5886 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5889 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5890 (char *)&error, sizeof(error), 0);
5891 rxi_FreePacket(packet);
5893 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5894 MUTEX_EXIT(&call->lock);
5897 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5898 * seconds) to ask the client to authenticate itself. The routine
5899 * issues a challenge to the client, which is obtained from the
5900 * security object associated with the connection */
5902 rxi_ChallengeEvent(struct rxevent *event,
5903 void *arg0, void *arg1, int tries)
5905 struct rx_connection *conn = arg0;
5907 conn->challengeEvent = NULL;
5908 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5909 struct rx_packet *packet;
5910 struct clock when, now;
5913 /* We've failed to authenticate for too long.
5914 * Reset any calls waiting for authentication;
5915 * they are all in RX_STATE_PRECALL.
5919 MUTEX_ENTER(&conn->conn_call_lock);
5920 for (i = 0; i < RX_MAXCALLS; i++) {
5921 struct rx_call *call = conn->call[i];
5923 MUTEX_ENTER(&call->lock);
5924 if (call->state == RX_STATE_PRECALL) {
5925 rxi_CallError(call, RX_CALL_DEAD);
5926 rxi_SendCallAbort(call, NULL, 0, 0);
5928 MUTEX_EXIT(&call->lock);
5931 MUTEX_EXIT(&conn->conn_call_lock);
5935 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5937 /* If there's no packet available, do this later. */
5938 RXS_GetChallenge(conn->securityObject, conn, packet);
5939 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5940 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5941 rxi_FreePacket(packet);
5943 clock_GetTime(&now);
5945 when.sec += RX_CHALLENGE_TIMEOUT;
5946 conn->challengeEvent =
5947 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5952 /* Call this routine to start requesting the client to authenticate
5953 * itself. This will continue until authentication is established,
5954 * the call times out, or an invalid response is returned. The
5955 * security object associated with the connection is asked to create
5956 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5957 * defined earlier. */
5959 rxi_ChallengeOn(struct rx_connection *conn)
5961 if (!conn->challengeEvent) {
5962 RXS_CreateChallenge(conn->securityObject, conn);
5963 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5968 /* Compute round trip time of the packet provided, in *rttp.
5971 /* rxi_ComputeRoundTripTime is called with peer locked. */
5972 /* sentp and/or peer may be null */
5974 rxi_ComputeRoundTripTime(struct rx_packet *p,
5975 struct clock *sentp,
5976 struct rx_peer *peer)
5978 struct clock thisRtt, *rttp = &thisRtt;
5982 clock_GetTime(rttp);
5984 if (clock_Lt(rttp, sentp)) {
5986 return; /* somebody set the clock back, don't count this time. */
5988 clock_Sub(rttp, sentp);
5989 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
5990 p->header.callNumber, p, rttp->sec, rttp->usec));
5992 if (rttp->sec == 0 && rttp->usec == 0) {
5994 * The actual round trip time is shorter than the
5995 * clock_GetTime resolution. It is most likely 1ms or 100ns.
5996 * Since we can't tell which at the moment we will assume 1ms.
6001 if (rx_stats_active) {
6002 MUTEX_ENTER(&rx_stats_mutex);
6003 if (clock_Lt(rttp, &rx_stats.minRtt))
6004 rx_stats.minRtt = *rttp;
6005 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
6006 if (rttp->sec > 60) {
6007 MUTEX_EXIT(&rx_stats_mutex);
6008 return; /* somebody set the clock ahead */
6010 rx_stats.maxRtt = *rttp;
6012 clock_Add(&rx_stats.totalRtt, rttp);
6013 rx_stats.nRttSamples++;
6014 MUTEX_EXIT(&rx_stats_mutex);
6017 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6019 /* Apply VanJacobson round-trip estimations */
6024 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6025 * srtt is stored as fixed point with 3 bits after the binary
6026 * point (i.e., scaled by 8). The following magic is
6027 * equivalent to the smoothing algorithm in rfc793 with an
6028 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6029 * srtt'*8 = rtt + srtt*7
6030 * srtt'*8 = srtt*8 + rtt - srtt
6031 * srtt' = srtt + rtt/8 - srtt/8
6032 * srtt' = srtt + (rtt - srtt)/8
6035 delta = _8THMSEC(rttp) - peer->rtt;
6036 peer->rtt += (delta >> 3);
6039 * We accumulate a smoothed rtt variance (actually, a smoothed
6040 * mean difference), then set the retransmit timer to smoothed
6041 * rtt + 4 times the smoothed variance (was 2x in van's original
6042 * paper, but 4x works better for me, and apparently for him as
6044 * rttvar is stored as
6045 * fixed point with 2 bits after the binary point (scaled by
6046 * 4). The following is equivalent to rfc793 smoothing with
6047 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6048 * rttvar'*4 = rttvar*3 + |delta|
6049 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6050 * rttvar' = rttvar + |delta|/4 - rttvar/4
6051 * rttvar' = rttvar + (|delta| - rttvar)/4
6052 * This replaces rfc793's wired-in beta.
6053 * dev*4 = dev*4 + (|actual - expected| - dev)
6059 delta -= (peer->rtt_dev << 1);
6060 peer->rtt_dev += (delta >> 3);
6062 /* I don't have a stored RTT so I start with this value. Since I'm
6063 * probably just starting a call, and will be pushing more data down
6064 * this, I expect congestion to increase rapidly. So I fudge a
6065 * little, and I set deviance to half the rtt. In practice,
6066 * deviance tends to approach something a little less than
6067 * half the smoothed rtt. */
6068 peer->rtt = _8THMSEC(rttp) + 8;
6069 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6071 /* the timeout is RTT + 4*MDEV but no less than rx_minPeerTimeout msec.
6072 * This is because one end or the other of these connections is usually
6073 * in a user process, and can be switched and/or swapped out. So on fast,
6074 * reliable networks, the timeout would otherwise be too short. */
6075 rtt_timeout = MAX(((peer->rtt >> 3) + peer->rtt_dev), rx_minPeerTimeout);
6076 clock_Zero(&(peer->timeout));
6077 clock_Addmsec(&(peer->timeout), rtt_timeout);
6079 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6080 p->header.callNumber, p, MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6084 /* Find all server connections that have not been active for a long time, and
6087 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6089 struct clock now, when;
6090 clock_GetTime(&now);
6092 /* Find server connection structures that haven't been used for
6093 * greater than rx_idleConnectionTime */
6095 struct rx_connection **conn_ptr, **conn_end;
6096 int i, havecalls = 0;
6097 MUTEX_ENTER(&rx_connHashTable_lock);
6098 for (conn_ptr = &rx_connHashTable[0], conn_end =
6099 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6101 struct rx_connection *conn, *next;
6102 struct rx_call *call;
6106 for (conn = *conn_ptr; conn; conn = next) {
6107 /* XXX -- Shouldn't the connection be locked? */
6110 for (i = 0; i < RX_MAXCALLS; i++) {
6111 call = conn->call[i];
6115 code = MUTEX_TRYENTER(&call->lock);
6118 #ifdef RX_ENABLE_LOCKS
6119 result = rxi_CheckCall(call, 1);
6120 #else /* RX_ENABLE_LOCKS */
6121 result = rxi_CheckCall(call);
6122 #endif /* RX_ENABLE_LOCKS */
6123 MUTEX_EXIT(&call->lock);
6125 /* If CheckCall freed the call, it might
6126 * have destroyed the connection as well,
6127 * which screws up the linked lists.
6133 if (conn->type == RX_SERVER_CONNECTION) {
6134 /* This only actually destroys the connection if
6135 * there are no outstanding calls */
6136 MUTEX_ENTER(&conn->conn_data_lock);
6137 if (!havecalls && !conn->refCount
6138 && ((conn->lastSendTime + rx_idleConnectionTime) <
6140 conn->refCount++; /* it will be decr in rx_DestroyConn */
6141 MUTEX_EXIT(&conn->conn_data_lock);
6142 #ifdef RX_ENABLE_LOCKS
6143 rxi_DestroyConnectionNoLock(conn);
6144 #else /* RX_ENABLE_LOCKS */
6145 rxi_DestroyConnection(conn);
6146 #endif /* RX_ENABLE_LOCKS */
6148 #ifdef RX_ENABLE_LOCKS
6150 MUTEX_EXIT(&conn->conn_data_lock);
6152 #endif /* RX_ENABLE_LOCKS */
6156 #ifdef RX_ENABLE_LOCKS
6157 while (rx_connCleanup_list) {
6158 struct rx_connection *conn;
6159 conn = rx_connCleanup_list;
6160 rx_connCleanup_list = rx_connCleanup_list->next;
6161 MUTEX_EXIT(&rx_connHashTable_lock);
6162 rxi_CleanupConnection(conn);
6163 MUTEX_ENTER(&rx_connHashTable_lock);
6165 MUTEX_EXIT(&rx_connHashTable_lock);
6166 #endif /* RX_ENABLE_LOCKS */
6169 /* Find any peer structures that haven't been used (haven't had an
6170 * associated connection) for greater than rx_idlePeerTime */
6172 struct rx_peer **peer_ptr, **peer_end;
6174 MUTEX_ENTER(&rx_rpc_stats);
6175 MUTEX_ENTER(&rx_peerHashTable_lock);
6176 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6177 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6179 struct rx_peer *peer, *next, *prev;
6180 for (prev = peer = *peer_ptr; peer; peer = next) {
6182 code = MUTEX_TRYENTER(&peer->peer_lock);
6183 if ((code) && (peer->refCount == 0)
6184 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6185 rx_interface_stat_p rpc_stat, nrpc_stat;
6187 MUTEX_EXIT(&peer->peer_lock);
6188 MUTEX_DESTROY(&peer->peer_lock);
6190 (&peer->rpcStats, rpc_stat, nrpc_stat,
6191 rx_interface_stat)) {
6192 unsigned int num_funcs;
6195 queue_Remove(&rpc_stat->queue_header);
6196 queue_Remove(&rpc_stat->all_peers);
6197 num_funcs = rpc_stat->stats[0].func_total;
6199 sizeof(rx_interface_stat_t) +
6200 rpc_stat->stats[0].func_total *
6201 sizeof(rx_function_entry_v1_t);
6203 rxi_Free(rpc_stat, space);
6204 rxi_rpc_peer_stat_cnt -= num_funcs;
6207 if (rx_stats_active)
6208 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6209 if (peer == *peer_ptr) {
6216 MUTEX_EXIT(&peer->peer_lock);
6222 MUTEX_EXIT(&rx_peerHashTable_lock);
6223 MUTEX_EXIT(&rx_rpc_stats);
6226 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6227 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6228 * GC, just below. Really, we shouldn't have to keep moving packets from
6229 * one place to another, but instead ought to always know if we can
6230 * afford to hold onto a packet in its particular use. */
6231 MUTEX_ENTER(&rx_freePktQ_lock);
6232 if (rx_waitingForPackets) {
6233 rx_waitingForPackets = 0;
6234 #ifdef RX_ENABLE_LOCKS
6235 CV_BROADCAST(&rx_waitingForPackets_cv);
6237 osi_rxWakeup(&rx_waitingForPackets);
6240 MUTEX_EXIT(&rx_freePktQ_lock);
6243 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6244 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6248 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6249 * rx.h is sort of strange this is better. This is called with a security
6250 * object before it is discarded. Each connection using a security object has
6251 * its own refcount to the object so it won't actually be freed until the last
6252 * connection is destroyed.
6254 * This is the only rxs module call. A hold could also be written but no one
6258 rxs_Release(struct rx_securityClass *aobj)
6260 return RXS_Close(aobj);
6264 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6265 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6266 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6267 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6269 /* Adjust our estimate of the transmission rate to this peer, given
6270 * that the packet p was just acked. We can adjust peer->timeout and
6271 * call->twind. Pragmatically, this is called
6272 * only with packets of maximal length.
6273 * Called with peer and call locked.
6277 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6278 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6280 afs_int32 xferSize, xferMs;
6284 /* Count down packets */
6285 if (peer->rateFlag > 0)
6287 /* Do nothing until we're enabled */
6288 if (peer->rateFlag != 0)
6293 /* Count only when the ack seems legitimate */
6294 switch (ackReason) {
6295 case RX_ACK_REQUESTED:
6297 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6301 case RX_ACK_PING_RESPONSE:
6302 if (p) /* want the response to ping-request, not data send */
6304 clock_GetTime(&newTO);
6305 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6306 clock_Sub(&newTO, &call->pingRequestTime);
6307 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6311 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6318 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)",
6319 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
6320 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6322 /* Track only packets that are big enough. */
6323 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6327 /* absorb RTT data (in milliseconds) for these big packets */
6328 if (peer->smRtt == 0) {
6329 peer->smRtt = xferMs;
6331 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6336 if (peer->countDown) {
6340 peer->countDown = 10; /* recalculate only every so often */
6342 /* In practice, we can measure only the RTT for full packets,
6343 * because of the way Rx acks the data that it receives. (If it's
6344 * smaller than a full packet, it often gets implicitly acked
6345 * either by the call response (from a server) or by the next call
6346 * (from a client), and either case confuses transmission times
6347 * with processing times.) Therefore, replace the above
6348 * more-sophisticated processing with a simpler version, where the
6349 * smoothed RTT is kept for full-size packets, and the time to
6350 * transmit a windowful of full-size packets is simply RTT *
6351 * windowSize. Again, we take two steps:
6352 - ensure the timeout is large enough for a single packet's RTT;
6353 - ensure that the window is small enough to fit in the desired timeout.*/
6355 /* First, the timeout check. */
6356 minTime = peer->smRtt;
6357 /* Get a reasonable estimate for a timeout period */
6359 newTO.sec = minTime / 1000;
6360 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6362 /* Increase the timeout period so that we can always do at least
6363 * one packet exchange */
6364 if (clock_Gt(&newTO, &peer->timeout)) {
6366 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u, ps %u)",
6367 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
6368 newTO.sec, newTO.usec, peer->smRtt, peer->packetSize));
6370 peer->timeout = newTO;
6373 /* Now, get an estimate for the transmit window size. */
6374 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6375 /* Now, convert to the number of full packets that could fit in a
6376 * reasonable fraction of that interval */
6377 minTime /= (peer->smRtt << 1);
6378 xferSize = minTime; /* (make a copy) */
6380 /* Now clamp the size to reasonable bounds. */
6383 else if (minTime > rx_Window)
6384 minTime = rx_Window;
6385 /* if (minTime != peer->maxWindow) {
6386 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6387 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6388 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6390 peer->maxWindow = minTime;
6391 elide... call->twind = minTime;
6395 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6396 * Discern this by calculating the timeout necessary for rx_Window
6398 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6399 /* calculate estimate for transmission interval in milliseconds */
6400 minTime = rx_Window * peer->smRtt;
6401 if (minTime < 1000) {
6402 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u, ps %u)",
6403 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6404 peer->timeout.usec, peer->smRtt, peer->packetSize));
6406 newTO.sec = 0; /* cut back on timeout by half a second */
6407 newTO.usec = 500000;
6408 clock_Sub(&peer->timeout, &newTO);
6413 } /* end of rxi_ComputeRate */
6414 #endif /* ADAPT_WINDOW */
6422 #define TRACE_OPTION_RX_DEBUG 16
6430 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6431 0, KEY_QUERY_VALUE, &parmKey);
6432 if (code != ERROR_SUCCESS)
6435 dummyLen = sizeof(TraceOption);
6436 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6437 (BYTE *) &TraceOption, &dummyLen);
6438 if (code == ERROR_SUCCESS) {
6439 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6441 RegCloseKey (parmKey);
6442 #endif /* AFS_NT40_ENV */
6447 rx_DebugOnOff(int on)
6451 rxdebug_active = on;
6457 rx_StatsOnOff(int on)
6460 rx_stats_active = on;
6465 /* Don't call this debugging routine directly; use dpf */
6467 rxi_DebugPrint(char *format, ...)
6476 va_start(ap, format);
6478 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6481 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6483 if (msg[len-1] != '\n') {
6487 OutputDebugString(msg);
6494 va_start(ap, format);
6496 clock_GetTime(&now);
6497 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
6498 (unsigned int)now.usec);
6499 vfprintf(rx_Log, format, ap);
6508 * This function is used to process the rx_stats structure that is local
6509 * to a process as well as an rx_stats structure received from a remote
6510 * process (via rxdebug). Therefore, it needs to do minimal version
6514 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6515 afs_int32 freePackets, char version)
6520 if (size != sizeof(struct rx_statistics)) {
6522 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
6523 size, sizeof(struct rx_statistics));
6526 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6529 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6530 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
6531 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6532 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6533 s->specialPktAllocFailures);
6535 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
6536 s->receivePktAllocFailures, s->sendPktAllocFailures,
6537 s->specialPktAllocFailures);
6541 " greedy %u, " "bogusReads %u (last from host %x), "
6542 "noPackets %u, " "noBuffers %u, " "selects %u, "
6543 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
6544 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6545 s->selects, s->sendSelects);
6547 fprintf(file, " packets read: ");
6548 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6549 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
6551 fprintf(file, "\n");
6554 " other read counters: data %u, " "ack %u, " "dup %u "
6555 "spurious %u " "dally %u\n", s->dataPacketsRead,
6556 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6557 s->ignorePacketDally);
6559 fprintf(file, " packets sent: ");
6560 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6561 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
6563 fprintf(file, "\n");
6566 " other send counters: ack %u, " "data %u (not resends), "
6567 "resends %u, " "pushed %u, " "acked&ignored %u\n",
6568 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6569 s->dataPacketsPushed, s->ignoreAckedPacket);
6572 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
6573 s->netSendFailures, (int)s->fatalErrors);
6575 if (s->nRttSamples) {
6576 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6577 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6579 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6580 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6584 " %d server connections, " "%d client connections, "
6585 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6586 s->nServerConns, s->nClientConns, s->nPeerStructs,
6587 s->nCallStructs, s->nFreeCallStructs);
6589 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6590 fprintf(file, " %d clock updates\n", clock_nUpdates);
6593 fprintf(file, "ERROR: compiled without RXDEBUG\n");
6597 /* for backward compatibility */
6599 rx_PrintStats(FILE * file)
6601 MUTEX_ENTER(&rx_stats_mutex);
6602 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6604 MUTEX_EXIT(&rx_stats_mutex);
6608 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6610 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
6611 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6612 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6615 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6616 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6617 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6620 " Packet size %d, " "max in packet skew %d, "
6621 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6622 (int)peer->outPacketSkew);
6626 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
6628 * This mutex protects the following static variables:
6632 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
6633 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
6635 #define LOCK_RX_DEBUG
6636 #define UNLOCK_RX_DEBUG
6637 #endif /* AFS_PTHREAD_ENV */
6641 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6642 u_char type, void *inputData, size_t inputLength,
6643 void *outputData, size_t outputLength)
6645 static afs_int32 counter = 100;
6646 time_t waitTime, waitCount, startTime;
6647 struct rx_header theader;
6650 struct timeval tv_now, tv_wake, tv_delta;
6651 struct sockaddr_in taddr, faddr;
6660 startTime = time(0);
6666 tp = &tbuffer[sizeof(struct rx_header)];
6667 taddr.sin_family = AF_INET;
6668 taddr.sin_port = remotePort;
6669 taddr.sin_addr.s_addr = remoteAddr;
6670 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6671 taddr.sin_len = sizeof(struct sockaddr_in);
6674 memset(&theader, 0, sizeof(theader));
6675 theader.epoch = htonl(999);
6677 theader.callNumber = htonl(counter);
6680 theader.type = type;
6681 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6682 theader.serviceId = 0;
6684 memcpy(tbuffer, &theader, sizeof(theader));
6685 memcpy(tp, inputData, inputLength);
6687 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6688 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6690 /* see if there's a packet available */
6691 gettimeofday(&tv_wake,0);
6692 tv_wake.tv_sec += waitTime;
6695 FD_SET(socket, &imask);
6696 tv_delta.tv_sec = tv_wake.tv_sec;
6697 tv_delta.tv_usec = tv_wake.tv_usec;
6698 gettimeofday(&tv_now, 0);
6700 if (tv_delta.tv_usec < tv_now.tv_usec) {
6702 tv_delta.tv_usec += 1000000;
6705 tv_delta.tv_usec -= tv_now.tv_usec;
6707 if (tv_delta.tv_sec < tv_now.tv_sec) {
6711 tv_delta.tv_sec -= tv_now.tv_sec;
6714 code = select(0, &imask, 0, 0, &tv_delta);
6715 #else /* AFS_NT40_ENV */
6716 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6717 #endif /* AFS_NT40_ENV */
6718 if (code == 1 && FD_ISSET(socket, &imask)) {
6719 /* now receive a packet */
6720 faddrLen = sizeof(struct sockaddr_in);
6722 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6723 (struct sockaddr *)&faddr, &faddrLen);
6726 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6727 if (counter == ntohl(theader.callNumber))
6735 /* see if we've timed out */
6743 code -= sizeof(struct rx_header);
6744 if (code > outputLength)
6745 code = outputLength;
6746 memcpy(outputData, tp, code);
6749 #endif /* RXDEBUG */
6752 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6753 afs_uint16 remotePort, struct rx_debugStats * stat,
6754 afs_uint32 * supportedValues)
6760 struct rx_debugIn in;
6762 *supportedValues = 0;
6763 in.type = htonl(RX_DEBUGI_GETSTATS);
6766 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6767 &in, sizeof(in), stat, sizeof(*stat));
6770 * If the call was successful, fixup the version and indicate
6771 * what contents of the stat structure are valid.
6772 * Also do net to host conversion of fields here.
6776 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6777 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6779 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6780 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6782 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6783 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6785 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6786 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6788 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6789 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6791 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6792 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6794 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6795 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6797 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6798 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6800 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6801 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6803 stat->nFreePackets = ntohl(stat->nFreePackets);
6804 stat->packetReclaims = ntohl(stat->packetReclaims);
6805 stat->callsExecuted = ntohl(stat->callsExecuted);
6806 stat->nWaiting = ntohl(stat->nWaiting);
6807 stat->idleThreads = ntohl(stat->idleThreads);
6808 stat->nWaited = ntohl(stat->nWaited);
6809 stat->nPackets = ntohl(stat->nPackets);
6816 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6817 afs_uint16 remotePort, struct rx_statistics * stat,
6818 afs_uint32 * supportedValues)
6824 struct rx_debugIn in;
6825 afs_int32 *lp = (afs_int32 *) stat;
6829 * supportedValues is currently unused, but added to allow future
6830 * versioning of this function.
6833 *supportedValues = 0;
6834 in.type = htonl(RX_DEBUGI_RXSTATS);
6836 memset(stat, 0, sizeof(*stat));
6838 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6839 &in, sizeof(in), stat, sizeof(*stat));
6844 * Do net to host conversion here
6847 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6856 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6857 afs_uint16 remotePort, size_t version_length,
6862 return MakeDebugCall(socket, remoteAddr, remotePort,
6863 RX_PACKET_TYPE_VERSION, a, 1, version,
6871 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6872 afs_uint16 remotePort, afs_int32 * nextConnection,
6873 int allConnections, afs_uint32 debugSupportedValues,
6874 struct rx_debugConn * conn,
6875 afs_uint32 * supportedValues)
6881 struct rx_debugIn in;
6885 * supportedValues is currently unused, but added to allow future
6886 * versioning of this function.
6889 *supportedValues = 0;
6890 if (allConnections) {
6891 in.type = htonl(RX_DEBUGI_GETALLCONN);
6893 in.type = htonl(RX_DEBUGI_GETCONN);
6895 in.index = htonl(*nextConnection);
6896 memset(conn, 0, sizeof(*conn));
6898 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6899 &in, sizeof(in), conn, sizeof(*conn));
6902 *nextConnection += 1;
6905 * Convert old connection format to new structure.
6908 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6909 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6910 #define MOVEvL(a) (conn->a = vL->a)
6912 /* any old or unrecognized version... */
6913 for (i = 0; i < RX_MAXCALLS; i++) {
6914 MOVEvL(callState[i]);
6915 MOVEvL(callMode[i]);
6916 MOVEvL(callFlags[i]);
6917 MOVEvL(callOther[i]);
6919 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6920 MOVEvL(secStats.type);
6921 MOVEvL(secStats.level);
6922 MOVEvL(secStats.flags);
6923 MOVEvL(secStats.expires);
6924 MOVEvL(secStats.packetsReceived);
6925 MOVEvL(secStats.packetsSent);
6926 MOVEvL(secStats.bytesReceived);
6927 MOVEvL(secStats.bytesSent);
6932 * Do net to host conversion here
6934 * I don't convert host or port since we are most likely
6935 * going to want these in NBO.
6937 conn->cid = ntohl(conn->cid);
6938 conn->serial = ntohl(conn->serial);
6939 for (i = 0; i < RX_MAXCALLS; i++) {
6940 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6942 conn->error = ntohl(conn->error);
6943 conn->secStats.flags = ntohl(conn->secStats.flags);
6944 conn->secStats.expires = ntohl(conn->secStats.expires);
6945 conn->secStats.packetsReceived =
6946 ntohl(conn->secStats.packetsReceived);
6947 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6948 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6949 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6950 conn->epoch = ntohl(conn->epoch);
6951 conn->natMTU = ntohl(conn->natMTU);
6958 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6959 afs_uint16 remotePort, afs_int32 * nextPeer,
6960 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6961 afs_uint32 * supportedValues)
6967 struct rx_debugIn in;
6970 * supportedValues is currently unused, but added to allow future
6971 * versioning of this function.
6974 *supportedValues = 0;
6975 in.type = htonl(RX_DEBUGI_GETPEER);
6976 in.index = htonl(*nextPeer);
6977 memset(peer, 0, sizeof(*peer));
6979 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6980 &in, sizeof(in), peer, sizeof(*peer));
6986 * Do net to host conversion here
6988 * I don't convert host or port since we are most likely
6989 * going to want these in NBO.
6991 peer->ifMTU = ntohs(peer->ifMTU);
6992 peer->idleWhen = ntohl(peer->idleWhen);
6993 peer->refCount = ntohs(peer->refCount);
6994 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6995 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6996 peer->rtt = ntohl(peer->rtt);
6997 peer->rtt_dev = ntohl(peer->rtt_dev);
6998 peer->timeout.sec = ntohl(peer->timeout.sec);
6999 peer->timeout.usec = ntohl(peer->timeout.usec);
7000 peer->nSent = ntohl(peer->nSent);
7001 peer->reSends = ntohl(peer->reSends);
7002 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7003 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7004 peer->rateFlag = ntohl(peer->rateFlag);
7005 peer->natMTU = ntohs(peer->natMTU);
7006 peer->maxMTU = ntohs(peer->maxMTU);
7007 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7008 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7009 peer->MTU = ntohs(peer->MTU);
7010 peer->cwind = ntohs(peer->cwind);
7011 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7012 peer->congestSeq = ntohs(peer->congestSeq);
7013 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7014 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7015 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7016 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7023 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7024 struct rx_debugPeer * peerStats)
7027 afs_int32 error = 1; /* default to "did not succeed" */
7028 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7030 MUTEX_ENTER(&rx_peerHashTable_lock);
7031 for(tp = rx_peerHashTable[hashValue];
7032 tp != NULL; tp = tp->next) {
7033 if (tp->host == peerHost)
7040 peerStats->host = tp->host;
7041 peerStats->port = tp->port;
7042 peerStats->ifMTU = tp->ifMTU;
7043 peerStats->idleWhen = tp->idleWhen;
7044 peerStats->refCount = tp->refCount;
7045 peerStats->burstSize = tp->burstSize;
7046 peerStats->burst = tp->burst;
7047 peerStats->burstWait.sec = tp->burstWait.sec;
7048 peerStats->burstWait.usec = tp->burstWait.usec;
7049 peerStats->rtt = tp->rtt;
7050 peerStats->rtt_dev = tp->rtt_dev;
7051 peerStats->timeout.sec = tp->timeout.sec;
7052 peerStats->timeout.usec = tp->timeout.usec;
7053 peerStats->nSent = tp->nSent;
7054 peerStats->reSends = tp->reSends;
7055 peerStats->inPacketSkew = tp->inPacketSkew;
7056 peerStats->outPacketSkew = tp->outPacketSkew;
7057 peerStats->rateFlag = tp->rateFlag;
7058 peerStats->natMTU = tp->natMTU;
7059 peerStats->maxMTU = tp->maxMTU;
7060 peerStats->maxDgramPackets = tp->maxDgramPackets;
7061 peerStats->ifDgramPackets = tp->ifDgramPackets;
7062 peerStats->MTU = tp->MTU;
7063 peerStats->cwind = tp->cwind;
7064 peerStats->nDgramPackets = tp->nDgramPackets;
7065 peerStats->congestSeq = tp->congestSeq;
7066 peerStats->bytesSent.high = tp->bytesSent.high;
7067 peerStats->bytesSent.low = tp->bytesSent.low;
7068 peerStats->bytesReceived.high = tp->bytesReceived.high;
7069 peerStats->bytesReceived.low = tp->bytesReceived.low;
7071 MUTEX_EXIT(&rx_peerHashTable_lock);
7079 struct rx_serverQueueEntry *np;
7082 struct rx_call *call;
7083 struct rx_serverQueueEntry *sq;
7087 if (rxinit_status == 1) {
7089 return; /* Already shutdown. */
7093 #ifndef AFS_PTHREAD_ENV
7094 FD_ZERO(&rx_selectMask);
7095 #endif /* AFS_PTHREAD_ENV */
7096 rxi_dataQuota = RX_MAX_QUOTA;
7097 #ifndef AFS_PTHREAD_ENV
7099 #endif /* AFS_PTHREAD_ENV */
7102 #ifndef AFS_PTHREAD_ENV
7103 #ifndef AFS_USE_GETTIMEOFDAY
7105 #endif /* AFS_USE_GETTIMEOFDAY */
7106 #endif /* AFS_PTHREAD_ENV */
7108 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7109 call = queue_First(&rx_freeCallQueue, rx_call);
7111 rxi_Free(call, sizeof(struct rx_call));
7114 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7115 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7121 struct rx_peer **peer_ptr, **peer_end;
7122 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7123 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7125 struct rx_peer *peer, *next;
7126 for (peer = *peer_ptr; peer; peer = next) {
7127 rx_interface_stat_p rpc_stat, nrpc_stat;
7130 (&peer->rpcStats, rpc_stat, nrpc_stat,
7131 rx_interface_stat)) {
7132 unsigned int num_funcs;
7135 queue_Remove(&rpc_stat->queue_header);
7136 queue_Remove(&rpc_stat->all_peers);
7137 num_funcs = rpc_stat->stats[0].func_total;
7139 sizeof(rx_interface_stat_t) +
7140 rpc_stat->stats[0].func_total *
7141 sizeof(rx_function_entry_v1_t);
7143 rxi_Free(rpc_stat, space);
7144 MUTEX_ENTER(&rx_rpc_stats);
7145 rxi_rpc_peer_stat_cnt -= num_funcs;
7146 MUTEX_EXIT(&rx_rpc_stats);
7150 if (rx_stats_active)
7151 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7155 for (i = 0; i < RX_MAX_SERVICES; i++) {
7157 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7159 for (i = 0; i < rx_hashTableSize; i++) {
7160 struct rx_connection *tc, *ntc;
7161 MUTEX_ENTER(&rx_connHashTable_lock);
7162 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7164 for (j = 0; j < RX_MAXCALLS; j++) {
7166 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7169 rxi_Free(tc, sizeof(*tc));
7171 MUTEX_EXIT(&rx_connHashTable_lock);
7174 MUTEX_ENTER(&freeSQEList_lock);
7176 while ((np = rx_FreeSQEList)) {
7177 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7178 MUTEX_DESTROY(&np->lock);
7179 rxi_Free(np, sizeof(*np));
7182 MUTEX_EXIT(&freeSQEList_lock);
7183 MUTEX_DESTROY(&freeSQEList_lock);
7184 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7185 MUTEX_DESTROY(&rx_connHashTable_lock);
7186 MUTEX_DESTROY(&rx_peerHashTable_lock);
7187 MUTEX_DESTROY(&rx_serverPool_lock);
7189 osi_Free(rx_connHashTable,
7190 rx_hashTableSize * sizeof(struct rx_connection *));
7191 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7193 UNPIN(rx_connHashTable,
7194 rx_hashTableSize * sizeof(struct rx_connection *));
7195 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7197 rxi_FreeAllPackets();
7199 MUTEX_ENTER(&rx_quota_mutex);
7200 rxi_dataQuota = RX_MAX_QUOTA;
7201 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7202 MUTEX_EXIT(&rx_quota_mutex);
7207 #ifdef RX_ENABLE_LOCKS
7209 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7211 if (!MUTEX_ISMINE(lockaddr))
7212 osi_Panic("Lock not held: %s", msg);
7214 #endif /* RX_ENABLE_LOCKS */
7219 * Routines to implement connection specific data.
7223 rx_KeyCreate(rx_destructor_t rtn)
7226 MUTEX_ENTER(&rxi_keyCreate_lock);
7227 key = rxi_keyCreate_counter++;
7228 rxi_keyCreate_destructor = (rx_destructor_t *)
7229 realloc((void *)rxi_keyCreate_destructor,
7230 (key + 1) * sizeof(rx_destructor_t));
7231 rxi_keyCreate_destructor[key] = rtn;
7232 MUTEX_EXIT(&rxi_keyCreate_lock);
7237 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7240 MUTEX_ENTER(&conn->conn_data_lock);
7241 if (!conn->specific) {
7242 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7243 for (i = 0; i < key; i++)
7244 conn->specific[i] = NULL;
7245 conn->nSpecific = key + 1;
7246 conn->specific[key] = ptr;
7247 } else if (key >= conn->nSpecific) {
7248 conn->specific = (void **)
7249 realloc(conn->specific, (key + 1) * sizeof(void *));
7250 for (i = conn->nSpecific; i < key; i++)
7251 conn->specific[i] = NULL;
7252 conn->nSpecific = key + 1;
7253 conn->specific[key] = ptr;
7255 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7256 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7257 conn->specific[key] = ptr;
7259 MUTEX_EXIT(&conn->conn_data_lock);
7263 rx_GetSpecific(struct rx_connection *conn, int key)
7266 MUTEX_ENTER(&conn->conn_data_lock);
7267 if (key >= conn->nSpecific)
7270 ptr = conn->specific[key];
7271 MUTEX_EXIT(&conn->conn_data_lock);
7275 #endif /* !KERNEL */
7278 * processStats is a queue used to store the statistics for the local
7279 * process. Its contents are similar to the contents of the rpcStats
7280 * queue on a rx_peer structure, but the actual data stored within
7281 * this queue contains totals across the lifetime of the process (assuming
7282 * the stats have not been reset) - unlike the per peer structures
7283 * which can come and go based upon the peer lifetime.
7286 static struct rx_queue processStats = { &processStats, &processStats };
7289 * peerStats is a queue used to store the statistics for all peer structs.
7290 * Its contents are the union of all the peer rpcStats queues.
7293 static struct rx_queue peerStats = { &peerStats, &peerStats };
7296 * rxi_monitor_processStats is used to turn process wide stat collection
7300 static int rxi_monitor_processStats = 0;
7303 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7306 static int rxi_monitor_peerStats = 0;
7309 * rxi_AddRpcStat - given all of the information for a particular rpc
7310 * call, create (if needed) and update the stat totals for the rpc.
7314 * IN stats - the queue of stats that will be updated with the new value
7316 * IN rxInterface - a unique number that identifies the rpc interface
7318 * IN currentFunc - the index of the function being invoked
7320 * IN totalFunc - the total number of functions in this interface
7322 * IN queueTime - the amount of time this function waited for a thread
7324 * IN execTime - the amount of time this function invocation took to execute
7326 * IN bytesSent - the number bytes sent by this invocation
7328 * IN bytesRcvd - the number bytes received by this invocation
7330 * IN isServer - if true, this invocation was made to a server
7332 * IN remoteHost - the ip address of the remote host
7334 * IN remotePort - the port of the remote host
7336 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7338 * INOUT counter - if a new stats structure is allocated, the counter will
7339 * be updated with the new number of allocated stat structures
7347 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7348 afs_uint32 currentFunc, afs_uint32 totalFunc,
7349 struct clock *queueTime, struct clock *execTime,
7350 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7351 afs_uint32 remoteHost, afs_uint32 remotePort,
7352 int addToPeerList, unsigned int *counter)
7355 rx_interface_stat_p rpc_stat, nrpc_stat;
7358 * See if there's already a structure for this interface
7361 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7362 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7363 && (rpc_stat->stats[0].remote_is_server == isServer))
7368 * Didn't find a match so allocate a new structure and add it to the
7372 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7373 || (rpc_stat->stats[0].interfaceId != rxInterface)
7374 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7379 sizeof(rx_interface_stat_t) +
7380 totalFunc * sizeof(rx_function_entry_v1_t);
7382 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7383 if (rpc_stat == NULL) {
7387 *counter += totalFunc;
7388 for (i = 0; i < totalFunc; i++) {
7389 rpc_stat->stats[i].remote_peer = remoteHost;
7390 rpc_stat->stats[i].remote_port = remotePort;
7391 rpc_stat->stats[i].remote_is_server = isServer;
7392 rpc_stat->stats[i].interfaceId = rxInterface;
7393 rpc_stat->stats[i].func_total = totalFunc;
7394 rpc_stat->stats[i].func_index = i;
7395 hzero(rpc_stat->stats[i].invocations);
7396 hzero(rpc_stat->stats[i].bytes_sent);
7397 hzero(rpc_stat->stats[i].bytes_rcvd);
7398 rpc_stat->stats[i].queue_time_sum.sec = 0;
7399 rpc_stat->stats[i].queue_time_sum.usec = 0;
7400 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7401 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7402 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7403 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7404 rpc_stat->stats[i].queue_time_max.sec = 0;
7405 rpc_stat->stats[i].queue_time_max.usec = 0;
7406 rpc_stat->stats[i].execution_time_sum.sec = 0;
7407 rpc_stat->stats[i].execution_time_sum.usec = 0;
7408 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7409 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7410 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7411 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7412 rpc_stat->stats[i].execution_time_max.sec = 0;
7413 rpc_stat->stats[i].execution_time_max.usec = 0;
7415 queue_Prepend(stats, rpc_stat);
7416 if (addToPeerList) {
7417 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7422 * Increment the stats for this function
7425 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7426 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7427 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7428 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7429 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7430 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7431 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7433 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7434 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7436 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7437 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7439 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7440 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7442 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7443 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7451 * rx_IncrementTimeAndCount - increment the times and count for a particular
7456 * IN peer - the peer who invoked the rpc
7458 * IN rxInterface - a unique number that identifies the rpc interface
7460 * IN currentFunc - the index of the function being invoked
7462 * IN totalFunc - the total number of functions in this interface
7464 * IN queueTime - the amount of time this function waited for a thread
7466 * IN execTime - the amount of time this function invocation took to execute
7468 * IN bytesSent - the number bytes sent by this invocation
7470 * IN bytesRcvd - the number bytes received by this invocation
7472 * IN isServer - if true, this invocation was made to a server
7480 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7481 afs_uint32 currentFunc, afs_uint32 totalFunc,
7482 struct clock *queueTime, struct clock *execTime,
7483 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7487 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7490 MUTEX_ENTER(&rx_rpc_stats);
7491 MUTEX_ENTER(&peer->peer_lock);
7493 if (rxi_monitor_peerStats) {
7494 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7495 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7496 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7499 if (rxi_monitor_processStats) {
7500 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7501 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7502 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7505 MUTEX_EXIT(&peer->peer_lock);
7506 MUTEX_EXIT(&rx_rpc_stats);
7511 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7515 * IN callerVersion - the rpc stat version of the caller.
7517 * IN count - the number of entries to marshall.
7519 * IN stats - pointer to stats to be marshalled.
7521 * OUT ptr - Where to store the marshalled data.
7528 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7529 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7535 * We only support the first version
7537 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7538 *(ptr++) = stats->remote_peer;
7539 *(ptr++) = stats->remote_port;
7540 *(ptr++) = stats->remote_is_server;
7541 *(ptr++) = stats->interfaceId;
7542 *(ptr++) = stats->func_total;
7543 *(ptr++) = stats->func_index;
7544 *(ptr++) = hgethi(stats->invocations);
7545 *(ptr++) = hgetlo(stats->invocations);
7546 *(ptr++) = hgethi(stats->bytes_sent);
7547 *(ptr++) = hgetlo(stats->bytes_sent);
7548 *(ptr++) = hgethi(stats->bytes_rcvd);
7549 *(ptr++) = hgetlo(stats->bytes_rcvd);
7550 *(ptr++) = stats->queue_time_sum.sec;
7551 *(ptr++) = stats->queue_time_sum.usec;
7552 *(ptr++) = stats->queue_time_sum_sqr.sec;
7553 *(ptr++) = stats->queue_time_sum_sqr.usec;
7554 *(ptr++) = stats->queue_time_min.sec;
7555 *(ptr++) = stats->queue_time_min.usec;
7556 *(ptr++) = stats->queue_time_max.sec;
7557 *(ptr++) = stats->queue_time_max.usec;
7558 *(ptr++) = stats->execution_time_sum.sec;
7559 *(ptr++) = stats->execution_time_sum.usec;
7560 *(ptr++) = stats->execution_time_sum_sqr.sec;
7561 *(ptr++) = stats->execution_time_sum_sqr.usec;
7562 *(ptr++) = stats->execution_time_min.sec;
7563 *(ptr++) = stats->execution_time_min.usec;
7564 *(ptr++) = stats->execution_time_max.sec;
7565 *(ptr++) = stats->execution_time_max.usec;
7571 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7576 * IN callerVersion - the rpc stat version of the caller
7578 * OUT myVersion - the rpc stat version of this function
7580 * OUT clock_sec - local time seconds
7582 * OUT clock_usec - local time microseconds
7584 * OUT allocSize - the number of bytes allocated to contain stats
7586 * OUT statCount - the number stats retrieved from this process.
7588 * OUT stats - the actual stats retrieved from this process.
7592 * Returns void. If successful, stats will != NULL.
7596 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7597 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7598 size_t * allocSize, afs_uint32 * statCount,
7599 afs_uint32 ** stats)
7609 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7612 * Check to see if stats are enabled
7615 MUTEX_ENTER(&rx_rpc_stats);
7616 if (!rxi_monitor_processStats) {
7617 MUTEX_EXIT(&rx_rpc_stats);
7621 clock_GetTime(&now);
7622 *clock_sec = now.sec;
7623 *clock_usec = now.usec;
7626 * Allocate the space based upon the caller version
7628 * If the client is at an older version than we are,
7629 * we return the statistic data in the older data format, but
7630 * we still return our version number so the client knows we
7631 * are maintaining more data than it can retrieve.
7634 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7635 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7636 *statCount = rxi_rpc_process_stat_cnt;
7639 * This can't happen yet, but in the future version changes
7640 * can be handled by adding additional code here
7644 if (space > (size_t) 0) {
7646 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7649 rx_interface_stat_p rpc_stat, nrpc_stat;
7653 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7655 * Copy the data based upon the caller version
7657 rx_MarshallProcessRPCStats(callerVersion,
7658 rpc_stat->stats[0].func_total,
7659 rpc_stat->stats, &ptr);
7665 MUTEX_EXIT(&rx_rpc_stats);
7670 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7674 * IN callerVersion - the rpc stat version of the caller
7676 * OUT myVersion - the rpc stat version of this function
7678 * OUT clock_sec - local time seconds
7680 * OUT clock_usec - local time microseconds
7682 * OUT allocSize - the number of bytes allocated to contain stats
7684 * OUT statCount - the number of stats retrieved from the individual
7687 * OUT stats - the actual stats retrieved from the individual peer structures.
7691 * Returns void. If successful, stats will != NULL.
7695 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7696 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7697 size_t * allocSize, afs_uint32 * statCount,
7698 afs_uint32 ** stats)
7708 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7711 * Check to see if stats are enabled
7714 MUTEX_ENTER(&rx_rpc_stats);
7715 if (!rxi_monitor_peerStats) {
7716 MUTEX_EXIT(&rx_rpc_stats);
7720 clock_GetTime(&now);
7721 *clock_sec = now.sec;
7722 *clock_usec = now.usec;
7725 * Allocate the space based upon the caller version
7727 * If the client is at an older version than we are,
7728 * we return the statistic data in the older data format, but
7729 * we still return our version number so the client knows we
7730 * are maintaining more data than it can retrieve.
7733 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7734 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7735 *statCount = rxi_rpc_peer_stat_cnt;
7738 * This can't happen yet, but in the future version changes
7739 * can be handled by adding additional code here
7743 if (space > (size_t) 0) {
7745 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7748 rx_interface_stat_p rpc_stat, nrpc_stat;
7752 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7754 * We have to fix the offset of rpc_stat since we are
7755 * keeping this structure on two rx_queues. The rx_queue
7756 * package assumes that the rx_queue member is the first
7757 * member of the structure. That is, rx_queue assumes that
7758 * any one item is only on one queue at a time. We are
7759 * breaking that assumption and so we have to do a little
7760 * math to fix our pointers.
7763 fix_offset = (char *)rpc_stat;
7764 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7765 rpc_stat = (rx_interface_stat_p) fix_offset;
7768 * Copy the data based upon the caller version
7770 rx_MarshallProcessRPCStats(callerVersion,
7771 rpc_stat->stats[0].func_total,
7772 rpc_stat->stats, &ptr);
7778 MUTEX_EXIT(&rx_rpc_stats);
7783 * rx_FreeRPCStats - free memory allocated by
7784 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7788 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7789 * rx_RetrievePeerRPCStats
7791 * IN allocSize - the number of bytes in stats.
7799 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7801 rxi_Free(stats, allocSize);
7805 * rx_queryProcessRPCStats - see if process rpc stat collection is
7806 * currently enabled.
7812 * Returns 0 if stats are not enabled != 0 otherwise
7816 rx_queryProcessRPCStats(void)
7819 MUTEX_ENTER(&rx_rpc_stats);
7820 rc = rxi_monitor_processStats;
7821 MUTEX_EXIT(&rx_rpc_stats);
7826 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7832 * Returns 0 if stats are not enabled != 0 otherwise
7836 rx_queryPeerRPCStats(void)
7839 MUTEX_ENTER(&rx_rpc_stats);
7840 rc = rxi_monitor_peerStats;
7841 MUTEX_EXIT(&rx_rpc_stats);
7846 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7856 rx_enableProcessRPCStats(void)
7858 MUTEX_ENTER(&rx_rpc_stats);
7859 rx_enable_stats = 1;
7860 rxi_monitor_processStats = 1;
7861 MUTEX_EXIT(&rx_rpc_stats);
7865 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7875 rx_enablePeerRPCStats(void)
7877 MUTEX_ENTER(&rx_rpc_stats);
7878 rx_enable_stats = 1;
7879 rxi_monitor_peerStats = 1;
7880 MUTEX_EXIT(&rx_rpc_stats);
7884 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7894 rx_disableProcessRPCStats(void)
7896 rx_interface_stat_p rpc_stat, nrpc_stat;
7899 MUTEX_ENTER(&rx_rpc_stats);
7902 * Turn off process statistics and if peer stats is also off, turn
7906 rxi_monitor_processStats = 0;
7907 if (rxi_monitor_peerStats == 0) {
7908 rx_enable_stats = 0;
7911 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7912 unsigned int num_funcs = 0;
7915 queue_Remove(rpc_stat);
7916 num_funcs = rpc_stat->stats[0].func_total;
7918 sizeof(rx_interface_stat_t) +
7919 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7921 rxi_Free(rpc_stat, space);
7922 rxi_rpc_process_stat_cnt -= num_funcs;
7924 MUTEX_EXIT(&rx_rpc_stats);
7928 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7938 rx_disablePeerRPCStats(void)
7940 struct rx_peer **peer_ptr, **peer_end;
7943 MUTEX_ENTER(&rx_rpc_stats);
7946 * Turn off peer statistics and if process stats is also off, turn
7950 rxi_monitor_peerStats = 0;
7951 if (rxi_monitor_processStats == 0) {
7952 rx_enable_stats = 0;
7955 MUTEX_ENTER(&rx_peerHashTable_lock);
7956 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7957 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7959 struct rx_peer *peer, *next, *prev;
7960 for (prev = peer = *peer_ptr; peer; peer = next) {
7962 code = MUTEX_TRYENTER(&peer->peer_lock);
7964 rx_interface_stat_p rpc_stat, nrpc_stat;
7967 (&peer->rpcStats, rpc_stat, nrpc_stat,
7968 rx_interface_stat)) {
7969 unsigned int num_funcs = 0;
7972 queue_Remove(&rpc_stat->queue_header);
7973 queue_Remove(&rpc_stat->all_peers);
7974 num_funcs = rpc_stat->stats[0].func_total;
7976 sizeof(rx_interface_stat_t) +
7977 rpc_stat->stats[0].func_total *
7978 sizeof(rx_function_entry_v1_t);
7980 rxi_Free(rpc_stat, space);
7981 rxi_rpc_peer_stat_cnt -= num_funcs;
7983 MUTEX_EXIT(&peer->peer_lock);
7984 if (prev == *peer_ptr) {
7994 MUTEX_EXIT(&rx_peerHashTable_lock);
7995 MUTEX_EXIT(&rx_rpc_stats);
7999 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8004 * IN clearFlag - flag indicating which stats to clear
8012 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8014 rx_interface_stat_p rpc_stat, nrpc_stat;
8016 MUTEX_ENTER(&rx_rpc_stats);
8018 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8019 unsigned int num_funcs = 0, i;
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 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8075 * IN clearFlag - flag indicating which stats to clear
8083 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8085 rx_interface_stat_p rpc_stat, nrpc_stat;
8087 MUTEX_ENTER(&rx_rpc_stats);
8089 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8090 unsigned int num_funcs = 0, i;
8093 * We have to fix the offset of rpc_stat since we are
8094 * keeping this structure on two rx_queues. The rx_queue
8095 * package assumes that the rx_queue member is the first
8096 * member of the structure. That is, rx_queue assumes that
8097 * any one item is only on one queue at a time. We are
8098 * breaking that assumption and so we have to do a little
8099 * math to fix our pointers.
8102 fix_offset = (char *)rpc_stat;
8103 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8104 rpc_stat = (rx_interface_stat_p) fix_offset;
8106 num_funcs = rpc_stat->stats[0].func_total;
8107 for (i = 0; i < num_funcs; i++) {
8108 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8109 hzero(rpc_stat->stats[i].invocations);
8111 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8112 hzero(rpc_stat->stats[i].bytes_sent);
8114 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8115 hzero(rpc_stat->stats[i].bytes_rcvd);
8117 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8118 rpc_stat->stats[i].queue_time_sum.sec = 0;
8119 rpc_stat->stats[i].queue_time_sum.usec = 0;
8121 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8122 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8123 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8125 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8126 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8127 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8129 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8130 rpc_stat->stats[i].queue_time_max.sec = 0;
8131 rpc_stat->stats[i].queue_time_max.usec = 0;
8133 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8134 rpc_stat->stats[i].execution_time_sum.sec = 0;
8135 rpc_stat->stats[i].execution_time_sum.usec = 0;
8137 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8138 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8139 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8141 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8142 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8143 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8145 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8146 rpc_stat->stats[i].execution_time_max.sec = 0;
8147 rpc_stat->stats[i].execution_time_max.usec = 0;
8152 MUTEX_EXIT(&rx_rpc_stats);
8156 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8157 * is authorized to enable/disable/clear RX statistics.
8159 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8162 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8164 rxi_rxstat_userok = proc;
8168 rx_RxStatUserOk(struct rx_call *call)
8170 if (!rxi_rxstat_userok)
8172 return rxi_rxstat_userok(call);
8177 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8178 * function in the MSVC runtime DLL (msvcrt.dll).
8180 * Note: the system serializes calls to this function.
8183 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8184 DWORD reason, /* reason function is being called */
8185 LPVOID reserved) /* reserved for future use */
8188 case DLL_PROCESS_ATTACH:
8189 /* library is being attached to a process */
8193 case DLL_PROCESS_DETACH:
8200 #endif /* AFS_NT40_ENV */
8203 int rx_DumpCalls(FILE *outputFile, char *cookie)
8205 #ifdef RXDEBUG_PACKET
8206 #ifdef KDUMP_RX_LOCK
8207 struct rx_call_rx_lock *c;
8214 #define RXDPRINTF sprintf
8215 #define RXDPRINTOUT output
8217 #define RXDPRINTF fprintf
8218 #define RXDPRINTOUT outputFile
8221 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8223 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8226 for (c = rx_allCallsp; c; c = c->allNextp) {
8227 u_short rqc, tqc, iovqc;
8228 struct rx_packet *p, *np;
8230 MUTEX_ENTER(&c->lock);
8231 queue_Count(&c->rq, p, np, rx_packet, rqc);
8232 queue_Count(&c->tq, p, np, rx_packet, tqc);
8233 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8235 RXDPRINTF(RXDPRINTOUT, "%s - call=0x%p, id=%u, state=%u, mode=%u, conn=%p, epoch=%u, cid=%u, callNum=%u, connFlags=0x%x, flags=0x%x, "
8236 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8237 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8238 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8239 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8240 #ifdef RX_ENABLE_LOCKS
8243 #ifdef RX_REFCOUNT_CHECK
8244 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8245 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8248 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,
8249 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8250 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8251 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8252 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8253 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8254 #ifdef RX_ENABLE_LOCKS
8255 , (afs_uint32)c->refCount
8257 #ifdef RX_REFCOUNT_CHECK
8258 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8261 MUTEX_EXIT(&c->lock);
8264 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8267 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8269 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8271 #endif /* RXDEBUG_PACKET */