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 %p, "
804 "serviceSecurityIndex %d)\n",
805 ntohl(shost), ntohs(sport), sservice, securityObject,
806 serviceSecurityIndex));
808 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
809 * the case of kmem_alloc? */
810 conn = rxi_AllocConnection();
811 #ifdef RX_ENABLE_LOCKS
812 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
813 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
814 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
817 MUTEX_ENTER(&rx_connHashTable_lock);
818 cid = (rx_nextCid += RX_MAXCALLS);
819 conn->type = RX_CLIENT_CONNECTION;
821 conn->epoch = rx_epoch;
822 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
823 conn->serviceId = sservice;
824 conn->securityObject = securityObject;
825 conn->securityData = (void *) 0;
826 conn->securityIndex = serviceSecurityIndex;
827 rx_SetConnDeadTime(conn, rx_connDeadTime);
828 conn->ackRate = RX_FAST_ACK_RATE;
830 conn->specific = NULL;
831 conn->challengeEvent = NULL;
832 conn->delayedAbortEvent = NULL;
833 conn->abortCount = 0;
835 for (i = 0; i < RX_MAXCALLS; i++) {
836 conn->twind[i] = rx_initSendWindow;
837 conn->rwind[i] = rx_initReceiveWindow;
840 RXS_NewConnection(securityObject, conn);
842 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
844 conn->refCount++; /* no lock required since only this thread knows... */
845 conn->next = rx_connHashTable[hashindex];
846 rx_connHashTable[hashindex] = conn;
848 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
849 MUTEX_EXIT(&rx_connHashTable_lock);
855 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
857 /* The idea is to set the dead time to a value that allows several
858 * keepalives to be dropped without timing out the connection. */
859 conn->secondsUntilDead = MAX(seconds, 6);
860 conn->secondsUntilPing = conn->secondsUntilDead / 6;
863 int rxi_lowPeerRefCount = 0;
864 int rxi_lowConnRefCount = 0;
867 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
868 * NOTE: must not be called with rx_connHashTable_lock held.
871 rxi_CleanupConnection(struct rx_connection *conn)
873 /* Notify the service exporter, if requested, that this connection
874 * is being destroyed */
875 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
876 (*conn->service->destroyConnProc) (conn);
878 /* Notify the security module that this connection is being destroyed */
879 RXS_DestroyConnection(conn->securityObject, conn);
881 /* If this is the last connection using the rx_peer struct, set its
882 * idle time to now. rxi_ReapConnections will reap it if it's still
883 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
885 MUTEX_ENTER(&rx_peerHashTable_lock);
886 if (conn->peer->refCount < 2) {
887 conn->peer->idleWhen = clock_Sec();
888 if (conn->peer->refCount < 1) {
889 conn->peer->refCount = 1;
890 if (rx_stats_active) {
891 MUTEX_ENTER(&rx_stats_mutex);
892 rxi_lowPeerRefCount++;
893 MUTEX_EXIT(&rx_stats_mutex);
897 conn->peer->refCount--;
898 MUTEX_EXIT(&rx_peerHashTable_lock);
902 if (conn->type == RX_SERVER_CONNECTION)
903 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
905 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
908 if (conn->specific) {
910 for (i = 0; i < conn->nSpecific; i++) {
911 if (conn->specific[i] && rxi_keyCreate_destructor[i])
912 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
913 conn->specific[i] = NULL;
915 free(conn->specific);
917 conn->specific = NULL;
921 MUTEX_DESTROY(&conn->conn_call_lock);
922 MUTEX_DESTROY(&conn->conn_data_lock);
923 CV_DESTROY(&conn->conn_call_cv);
925 rxi_FreeConnection(conn);
928 /* Destroy the specified connection */
930 rxi_DestroyConnection(struct rx_connection *conn)
932 MUTEX_ENTER(&rx_connHashTable_lock);
933 rxi_DestroyConnectionNoLock(conn);
934 /* conn should be at the head of the cleanup list */
935 if (conn == rx_connCleanup_list) {
936 rx_connCleanup_list = rx_connCleanup_list->next;
937 MUTEX_EXIT(&rx_connHashTable_lock);
938 rxi_CleanupConnection(conn);
940 #ifdef RX_ENABLE_LOCKS
942 MUTEX_EXIT(&rx_connHashTable_lock);
944 #endif /* RX_ENABLE_LOCKS */
948 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
950 struct rx_connection **conn_ptr;
952 struct rx_packet *packet;
959 MUTEX_ENTER(&conn->conn_data_lock);
960 if (conn->refCount > 0)
963 if (rx_stats_active) {
964 MUTEX_ENTER(&rx_stats_mutex);
965 rxi_lowConnRefCount++;
966 MUTEX_EXIT(&rx_stats_mutex);
970 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
971 /* Busy; wait till the last guy before proceeding */
972 MUTEX_EXIT(&conn->conn_data_lock);
977 /* If the client previously called rx_NewCall, but it is still
978 * waiting, treat this as a running call, and wait to destroy the
979 * connection later when the call completes. */
980 if ((conn->type == RX_CLIENT_CONNECTION)
981 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
982 conn->flags |= RX_CONN_DESTROY_ME;
983 MUTEX_EXIT(&conn->conn_data_lock);
987 MUTEX_EXIT(&conn->conn_data_lock);
989 /* Check for extant references to this connection */
990 for (i = 0; i < RX_MAXCALLS; i++) {
991 struct rx_call *call = conn->call[i];
994 if (conn->type == RX_CLIENT_CONNECTION) {
995 MUTEX_ENTER(&call->lock);
996 if (call->delayedAckEvent) {
997 /* Push the final acknowledgment out now--there
998 * won't be a subsequent call to acknowledge the
999 * last reply packets */
1000 rxevent_Cancel(call->delayedAckEvent, call,
1001 RX_CALL_REFCOUNT_DELAY);
1002 if (call->state == RX_STATE_PRECALL
1003 || call->state == RX_STATE_ACTIVE) {
1004 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1006 rxi_AckAll(NULL, call, 0);
1009 MUTEX_EXIT(&call->lock);
1013 #ifdef RX_ENABLE_LOCKS
1015 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1016 MUTEX_EXIT(&conn->conn_data_lock);
1018 /* Someone is accessing a packet right now. */
1022 #endif /* RX_ENABLE_LOCKS */
1025 /* Don't destroy the connection if there are any call
1026 * structures still in use */
1027 MUTEX_ENTER(&conn->conn_data_lock);
1028 conn->flags |= RX_CONN_DESTROY_ME;
1029 MUTEX_EXIT(&conn->conn_data_lock);
1034 if (conn->delayedAbortEvent) {
1035 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1036 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1038 MUTEX_ENTER(&conn->conn_data_lock);
1039 rxi_SendConnectionAbort(conn, packet, 0, 1);
1040 MUTEX_EXIT(&conn->conn_data_lock);
1041 rxi_FreePacket(packet);
1045 /* Remove from connection hash table before proceeding */
1047 &rx_connHashTable[CONN_HASH
1048 (peer->host, peer->port, conn->cid, conn->epoch,
1050 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1051 if (*conn_ptr == conn) {
1052 *conn_ptr = conn->next;
1056 /* if the conn that we are destroying was the last connection, then we
1057 * clear rxLastConn as well */
1058 if (rxLastConn == conn)
1061 /* Make sure the connection is completely reset before deleting it. */
1062 /* get rid of pending events that could zap us later */
1063 if (conn->challengeEvent)
1064 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1065 if (conn->checkReachEvent)
1066 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1068 /* Add the connection to the list of destroyed connections that
1069 * need to be cleaned up. This is necessary to avoid deadlocks
1070 * in the routines we call to inform others that this connection is
1071 * being destroyed. */
1072 conn->next = rx_connCleanup_list;
1073 rx_connCleanup_list = conn;
1076 /* Externally available version */
1078 rx_DestroyConnection(struct rx_connection *conn)
1083 rxi_DestroyConnection(conn);
1088 rx_GetConnection(struct rx_connection *conn)
1093 MUTEX_ENTER(&conn->conn_data_lock);
1095 MUTEX_EXIT(&conn->conn_data_lock);
1099 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1100 /* Wait for the transmit queue to no longer be busy.
1101 * requires the call->lock to be held */
1102 static void rxi_WaitforTQBusy(struct rx_call *call) {
1103 while (call->flags & RX_CALL_TQ_BUSY) {
1104 call->flags |= RX_CALL_TQ_WAIT;
1106 #ifdef RX_ENABLE_LOCKS
1107 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1108 CV_WAIT(&call->cv_tq, &call->lock);
1109 #else /* RX_ENABLE_LOCKS */
1110 osi_rxSleep(&call->tq);
1111 #endif /* RX_ENABLE_LOCKS */
1113 if (call->tqWaiters == 0) {
1114 call->flags &= ~RX_CALL_TQ_WAIT;
1120 /* Start a new rx remote procedure call, on the specified connection.
1121 * If wait is set to 1, wait for a free call channel; otherwise return
1122 * 0. Maxtime gives the maximum number of seconds this call may take,
1123 * after rx_NewCall returns. After this time interval, a call to any
1124 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1125 * For fine grain locking, we hold the conn_call_lock in order to
1126 * to ensure that we don't get signalle after we found a call in an active
1127 * state and before we go to sleep.
1130 rx_NewCall(struct rx_connection *conn)
1133 struct rx_call *call;
1134 struct clock queueTime;
1138 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1141 clock_GetTime(&queueTime);
1142 MUTEX_ENTER(&conn->conn_call_lock);
1145 * Check if there are others waiting for a new call.
1146 * If so, let them go first to avoid starving them.
1147 * This is a fairly simple scheme, and might not be
1148 * a complete solution for large numbers of waiters.
1150 * makeCallWaiters keeps track of the number of
1151 * threads waiting to make calls and the
1152 * RX_CONN_MAKECALL_WAITING flag bit is used to
1153 * indicate that there are indeed calls waiting.
1154 * The flag is set when the waiter is incremented.
1155 * It is only cleared in rx_EndCall when
1156 * makeCallWaiters is 0. This prevents us from
1157 * accidently destroying the connection while it
1158 * is potentially about to be used.
1160 MUTEX_ENTER(&conn->conn_data_lock);
1161 if (conn->makeCallWaiters) {
1162 conn->flags |= RX_CONN_MAKECALL_WAITING;
1163 conn->makeCallWaiters++;
1164 MUTEX_EXIT(&conn->conn_data_lock);
1166 #ifdef RX_ENABLE_LOCKS
1167 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1171 MUTEX_ENTER(&conn->conn_data_lock);
1172 conn->makeCallWaiters--;
1174 MUTEX_EXIT(&conn->conn_data_lock);
1177 for (i = 0; i < RX_MAXCALLS; i++) {
1178 call = conn->call[i];
1180 MUTEX_ENTER(&call->lock);
1181 if (call->state == RX_STATE_DALLY) {
1182 rxi_ResetCall(call, 0);
1183 (*call->callNumber)++;
1186 MUTEX_EXIT(&call->lock);
1188 call = rxi_NewCall(conn, i);
1192 if (i < RX_MAXCALLS) {
1195 MUTEX_ENTER(&conn->conn_data_lock);
1196 conn->flags |= RX_CONN_MAKECALL_WAITING;
1197 conn->makeCallWaiters++;
1198 MUTEX_EXIT(&conn->conn_data_lock);
1200 #ifdef RX_ENABLE_LOCKS
1201 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1205 MUTEX_ENTER(&conn->conn_data_lock);
1206 conn->makeCallWaiters--;
1207 MUTEX_EXIT(&conn->conn_data_lock);
1210 * Wake up anyone else who might be giving us a chance to
1211 * run (see code above that avoids resource starvation).
1213 #ifdef RX_ENABLE_LOCKS
1214 CV_BROADCAST(&conn->conn_call_cv);
1219 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1221 /* Client is initially in send mode */
1222 call->state = RX_STATE_ACTIVE;
1223 call->error = conn->error;
1225 call->mode = RX_MODE_ERROR;
1227 call->mode = RX_MODE_SENDING;
1229 /* remember start time for call in case we have hard dead time limit */
1230 call->queueTime = queueTime;
1231 clock_GetTime(&call->startTime);
1232 hzero(call->bytesSent);
1233 hzero(call->bytesRcvd);
1235 /* Turn on busy protocol. */
1236 rxi_KeepAliveOn(call);
1238 MUTEX_EXIT(&call->lock);
1239 MUTEX_EXIT(&conn->conn_call_lock);
1242 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1243 /* Now, if TQ wasn't cleared earlier, do it now. */
1244 MUTEX_ENTER(&call->lock);
1245 rxi_WaitforTQBusy(call);
1246 if (call->flags & RX_CALL_TQ_CLEARME) {
1247 rxi_ClearTransmitQueue(call, 1);
1248 /*queue_Init(&call->tq);*/
1250 MUTEX_EXIT(&call->lock);
1251 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1253 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1258 rxi_HasActiveCalls(struct rx_connection *aconn)
1261 struct rx_call *tcall;
1265 for (i = 0; i < RX_MAXCALLS; i++) {
1266 if ((tcall = aconn->call[i])) {
1267 if ((tcall->state == RX_STATE_ACTIVE)
1268 || (tcall->state == RX_STATE_PRECALL)) {
1279 rxi_GetCallNumberVector(struct rx_connection *aconn,
1280 afs_int32 * aint32s)
1283 struct rx_call *tcall;
1287 for (i = 0; i < RX_MAXCALLS; i++) {
1288 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1289 aint32s[i] = aconn->callNumber[i] + 1;
1291 aint32s[i] = aconn->callNumber[i];
1298 rxi_SetCallNumberVector(struct rx_connection *aconn,
1299 afs_int32 * aint32s)
1302 struct rx_call *tcall;
1306 for (i = 0; i < RX_MAXCALLS; i++) {
1307 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1308 aconn->callNumber[i] = aint32s[i] - 1;
1310 aconn->callNumber[i] = aint32s[i];
1316 /* Advertise a new service. A service is named locally by a UDP port
1317 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1320 char *serviceName; Name for identification purposes (e.g. the
1321 service name might be used for probing for
1324 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1325 char *serviceName, struct rx_securityClass **securityObjects,
1326 int nSecurityObjects,
1327 afs_int32(*serviceProc) (struct rx_call * acall))
1329 osi_socket socket = OSI_NULLSOCKET;
1330 struct rx_service *tservice;
1336 if (serviceId == 0) {
1338 "rx_NewService: service id for service %s is not non-zero.\n",
1345 "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",
1353 tservice = rxi_AllocService();
1355 for (i = 0; i < RX_MAX_SERVICES; i++) {
1356 struct rx_service *service = rx_services[i];
1358 if (port == service->servicePort && host == service->serviceHost) {
1359 if (service->serviceId == serviceId) {
1360 /* The identical service has already been
1361 * installed; if the caller was intending to
1362 * change the security classes used by this
1363 * service, he/she loses. */
1365 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1366 serviceName, serviceId, service->serviceName);
1368 rxi_FreeService(tservice);
1371 /* Different service, same port: re-use the socket
1372 * which is bound to the same port */
1373 socket = service->socket;
1376 if (socket == OSI_NULLSOCKET) {
1377 /* If we don't already have a socket (from another
1378 * service on same port) get a new one */
1379 socket = rxi_GetHostUDPSocket(host, port);
1380 if (socket == OSI_NULLSOCKET) {
1382 rxi_FreeService(tservice);
1387 service->socket = socket;
1388 service->serviceHost = host;
1389 service->servicePort = port;
1390 service->serviceId = serviceId;
1391 service->serviceName = serviceName;
1392 service->nSecurityObjects = nSecurityObjects;
1393 service->securityObjects = securityObjects;
1394 service->minProcs = 0;
1395 service->maxProcs = 1;
1396 service->idleDeadTime = 60;
1397 service->idleDeadErr = 0;
1398 service->connDeadTime = rx_connDeadTime;
1399 service->executeRequestProc = serviceProc;
1400 service->checkReach = 0;
1401 rx_services[i] = service; /* not visible until now */
1407 rxi_FreeService(tservice);
1408 (osi_Msg "rx_NewService: cannot support > %d services\n",
1413 /* Set configuration options for all of a service's security objects */
1416 rx_SetSecurityConfiguration(struct rx_service *service,
1417 rx_securityConfigVariables type,
1421 for (i = 0; i<service->nSecurityObjects; i++) {
1422 if (service->securityObjects[i]) {
1423 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1431 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1432 struct rx_securityClass **securityObjects, int nSecurityObjects,
1433 afs_int32(*serviceProc) (struct rx_call * acall))
1435 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1438 /* Generic request processing loop. This routine should be called
1439 * by the implementation dependent rx_ServerProc. If socketp is
1440 * non-null, it will be set to the file descriptor that this thread
1441 * is now listening on. If socketp is null, this routine will never
1444 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1446 struct rx_call *call;
1448 struct rx_service *tservice = NULL;
1455 call = rx_GetCall(threadID, tservice, socketp);
1456 if (socketp && *socketp != OSI_NULLSOCKET) {
1457 /* We are now a listener thread */
1462 /* if server is restarting( typically smooth shutdown) then do not
1463 * allow any new calls.
1466 if (rx_tranquil && (call != NULL)) {
1470 MUTEX_ENTER(&call->lock);
1472 rxi_CallError(call, RX_RESTARTING);
1473 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1475 MUTEX_EXIT(&call->lock);
1479 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1480 #ifdef RX_ENABLE_LOCKS
1482 #endif /* RX_ENABLE_LOCKS */
1483 afs_termState = AFSOP_STOP_AFS;
1484 afs_osi_Wakeup(&afs_termState);
1485 #ifdef RX_ENABLE_LOCKS
1487 #endif /* RX_ENABLE_LOCKS */
1492 tservice = call->conn->service;
1494 if (tservice->beforeProc)
1495 (*tservice->beforeProc) (call);
1497 code = call->conn->service->executeRequestProc(call);
1499 if (tservice->afterProc)
1500 (*tservice->afterProc) (call, code);
1502 rx_EndCall(call, code);
1503 if (rx_stats_active) {
1504 MUTEX_ENTER(&rx_stats_mutex);
1506 MUTEX_EXIT(&rx_stats_mutex);
1513 rx_WakeupServerProcs(void)
1515 struct rx_serverQueueEntry *np, *tqp;
1519 MUTEX_ENTER(&rx_serverPool_lock);
1521 #ifdef RX_ENABLE_LOCKS
1522 if (rx_waitForPacket)
1523 CV_BROADCAST(&rx_waitForPacket->cv);
1524 #else /* RX_ENABLE_LOCKS */
1525 if (rx_waitForPacket)
1526 osi_rxWakeup(rx_waitForPacket);
1527 #endif /* RX_ENABLE_LOCKS */
1528 MUTEX_ENTER(&freeSQEList_lock);
1529 for (np = rx_FreeSQEList; np; np = tqp) {
1530 tqp = *(struct rx_serverQueueEntry **)np;
1531 #ifdef RX_ENABLE_LOCKS
1532 CV_BROADCAST(&np->cv);
1533 #else /* RX_ENABLE_LOCKS */
1535 #endif /* RX_ENABLE_LOCKS */
1537 MUTEX_EXIT(&freeSQEList_lock);
1538 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1539 #ifdef RX_ENABLE_LOCKS
1540 CV_BROADCAST(&np->cv);
1541 #else /* RX_ENABLE_LOCKS */
1543 #endif /* RX_ENABLE_LOCKS */
1545 MUTEX_EXIT(&rx_serverPool_lock);
1550 * One thing that seems to happen is that all the server threads get
1551 * tied up on some empty or slow call, and then a whole bunch of calls
1552 * arrive at once, using up the packet pool, so now there are more
1553 * empty calls. The most critical resources here are server threads
1554 * and the free packet pool. The "doreclaim" code seems to help in
1555 * general. I think that eventually we arrive in this state: there
1556 * are lots of pending calls which do have all their packets present,
1557 * so they won't be reclaimed, are multi-packet calls, so they won't
1558 * be scheduled until later, and thus are tying up most of the free
1559 * packet pool for a very long time.
1561 * 1. schedule multi-packet calls if all the packets are present.
1562 * Probably CPU-bound operation, useful to return packets to pool.
1563 * Do what if there is a full window, but the last packet isn't here?
1564 * 3. preserve one thread which *only* runs "best" calls, otherwise
1565 * it sleeps and waits for that type of call.
1566 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1567 * the current dataquota business is badly broken. The quota isn't adjusted
1568 * to reflect how many packets are presently queued for a running call.
1569 * So, when we schedule a queued call with a full window of packets queued
1570 * up for it, that *should* free up a window full of packets for other 2d-class
1571 * calls to be able to use from the packet pool. But it doesn't.
1573 * NB. Most of the time, this code doesn't run -- since idle server threads
1574 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1575 * as a new call arrives.
1577 /* Sleep until a call arrives. Returns a pointer to the call, ready
1578 * for an rx_Read. */
1579 #ifdef RX_ENABLE_LOCKS
1581 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1583 struct rx_serverQueueEntry *sq;
1584 struct rx_call *call = (struct rx_call *)0;
1585 struct rx_service *service = NULL;
1588 MUTEX_ENTER(&freeSQEList_lock);
1590 if ((sq = rx_FreeSQEList)) {
1591 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1592 MUTEX_EXIT(&freeSQEList_lock);
1593 } else { /* otherwise allocate a new one and return that */
1594 MUTEX_EXIT(&freeSQEList_lock);
1595 sq = (struct rx_serverQueueEntry *)
1596 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1597 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1598 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1601 MUTEX_ENTER(&rx_serverPool_lock);
1602 if (cur_service != NULL) {
1603 ReturnToServerPool(cur_service);
1606 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1607 struct rx_call *tcall, *ncall, *choice2 = NULL;
1609 /* Scan for eligible incoming calls. A call is not eligible
1610 * if the maximum number of calls for its service type are
1611 * already executing */
1612 /* One thread will process calls FCFS (to prevent starvation),
1613 * while the other threads may run ahead looking for calls which
1614 * have all their input data available immediately. This helps
1615 * keep threads from blocking, waiting for data from the client. */
1616 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1617 service = tcall->conn->service;
1618 if (!QuotaOK(service)) {
1621 MUTEX_ENTER(&rx_pthread_mutex);
1622 if (tno == rxi_fcfs_thread_num
1623 || !tcall->queue_item_header.next) {
1624 MUTEX_EXIT(&rx_pthread_mutex);
1625 /* If we're the fcfs thread , then we'll just use
1626 * this call. If we haven't been able to find an optimal
1627 * choice, and we're at the end of the list, then use a
1628 * 2d choice if one has been identified. Otherwise... */
1629 call = (choice2 ? choice2 : tcall);
1630 service = call->conn->service;
1632 MUTEX_EXIT(&rx_pthread_mutex);
1633 if (!queue_IsEmpty(&tcall->rq)) {
1634 struct rx_packet *rp;
1635 rp = queue_First(&tcall->rq, rx_packet);
1636 if (rp->header.seq == 1) {
1638 || (rp->header.flags & RX_LAST_PACKET)) {
1640 } else if (rxi_2dchoice && !choice2
1641 && !(tcall->flags & RX_CALL_CLEARED)
1642 && (tcall->rprev > rxi_HardAckRate)) {
1652 ReturnToServerPool(service);
1659 MUTEX_EXIT(&rx_serverPool_lock);
1660 MUTEX_ENTER(&call->lock);
1662 if (call->flags & RX_CALL_WAIT_PROC) {
1663 call->flags &= ~RX_CALL_WAIT_PROC;
1664 MUTEX_ENTER(&rx_waiting_mutex);
1666 MUTEX_EXIT(&rx_waiting_mutex);
1669 if (call->state != RX_STATE_PRECALL || call->error) {
1670 MUTEX_EXIT(&call->lock);
1671 MUTEX_ENTER(&rx_serverPool_lock);
1672 ReturnToServerPool(service);
1677 if (queue_IsEmpty(&call->rq)
1678 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1679 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1681 CLEAR_CALL_QUEUE_LOCK(call);
1684 /* If there are no eligible incoming calls, add this process
1685 * to the idle server queue, to wait for one */
1689 *socketp = OSI_NULLSOCKET;
1691 sq->socketp = socketp;
1692 queue_Append(&rx_idleServerQueue, sq);
1693 #ifndef AFS_AIX41_ENV
1694 rx_waitForPacket = sq;
1696 rx_waitingForPacket = sq;
1697 #endif /* AFS_AIX41_ENV */
1699 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1701 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1702 MUTEX_EXIT(&rx_serverPool_lock);
1703 return (struct rx_call *)0;
1706 } while (!(call = sq->newcall)
1707 && !(socketp && *socketp != OSI_NULLSOCKET));
1708 MUTEX_EXIT(&rx_serverPool_lock);
1710 MUTEX_ENTER(&call->lock);
1716 MUTEX_ENTER(&freeSQEList_lock);
1717 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1718 rx_FreeSQEList = sq;
1719 MUTEX_EXIT(&freeSQEList_lock);
1722 clock_GetTime(&call->startTime);
1723 call->state = RX_STATE_ACTIVE;
1724 call->mode = RX_MODE_RECEIVING;
1725 #ifdef RX_KERNEL_TRACE
1726 if (ICL_SETACTIVE(afs_iclSetp)) {
1727 int glockOwner = ISAFS_GLOCK();
1730 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1731 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1738 rxi_calltrace(RX_CALL_START, call);
1739 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1740 call->conn->service->servicePort, call->conn->service->serviceId,
1743 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1744 MUTEX_EXIT(&call->lock);
1746 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1751 #else /* RX_ENABLE_LOCKS */
1753 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1755 struct rx_serverQueueEntry *sq;
1756 struct rx_call *call = (struct rx_call *)0, *choice2;
1757 struct rx_service *service = NULL;
1761 MUTEX_ENTER(&freeSQEList_lock);
1763 if ((sq = rx_FreeSQEList)) {
1764 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1765 MUTEX_EXIT(&freeSQEList_lock);
1766 } else { /* otherwise allocate a new one and return that */
1767 MUTEX_EXIT(&freeSQEList_lock);
1768 sq = (struct rx_serverQueueEntry *)
1769 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1770 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1771 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1773 MUTEX_ENTER(&sq->lock);
1775 if (cur_service != NULL) {
1776 cur_service->nRequestsRunning--;
1777 if (cur_service->nRequestsRunning < cur_service->minProcs)
1781 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1782 struct rx_call *tcall, *ncall;
1783 /* Scan for eligible incoming calls. A call is not eligible
1784 * if the maximum number of calls for its service type are
1785 * already executing */
1786 /* One thread will process calls FCFS (to prevent starvation),
1787 * while the other threads may run ahead looking for calls which
1788 * have all their input data available immediately. This helps
1789 * keep threads from blocking, waiting for data from the client. */
1790 choice2 = (struct rx_call *)0;
1791 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1792 service = tcall->conn->service;
1793 if (QuotaOK(service)) {
1794 MUTEX_ENTER(&rx_pthread_mutex);
1795 if (tno == rxi_fcfs_thread_num
1796 || !tcall->queue_item_header.next) {
1797 MUTEX_EXIT(&rx_pthread_mutex);
1798 /* If we're the fcfs thread, then we'll just use
1799 * this call. If we haven't been able to find an optimal
1800 * choice, and we're at the end of the list, then use a
1801 * 2d choice if one has been identified. Otherwise... */
1802 call = (choice2 ? choice2 : tcall);
1803 service = call->conn->service;
1805 MUTEX_EXIT(&rx_pthread_mutex);
1806 if (!queue_IsEmpty(&tcall->rq)) {
1807 struct rx_packet *rp;
1808 rp = queue_First(&tcall->rq, rx_packet);
1809 if (rp->header.seq == 1
1811 || (rp->header.flags & RX_LAST_PACKET))) {
1813 } else if (rxi_2dchoice && !choice2
1814 && !(tcall->flags & RX_CALL_CLEARED)
1815 && (tcall->rprev > rxi_HardAckRate)) {
1829 /* we can't schedule a call if there's no data!!! */
1830 /* send an ack if there's no data, if we're missing the
1831 * first packet, or we're missing something between first
1832 * and last -- there's a "hole" in the incoming data. */
1833 if (queue_IsEmpty(&call->rq)
1834 || queue_First(&call->rq, rx_packet)->header.seq != 1
1835 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1836 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1838 call->flags &= (~RX_CALL_WAIT_PROC);
1839 service->nRequestsRunning++;
1840 /* just started call in minProcs pool, need fewer to maintain
1842 if (service->nRequestsRunning <= service->minProcs)
1846 /* MUTEX_EXIT(&call->lock); */
1848 /* If there are no eligible incoming calls, add this process
1849 * to the idle server queue, to wait for one */
1852 *socketp = OSI_NULLSOCKET;
1854 sq->socketp = socketp;
1855 queue_Append(&rx_idleServerQueue, sq);
1859 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1861 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1862 return (struct rx_call *)0;
1865 } while (!(call = sq->newcall)
1866 && !(socketp && *socketp != OSI_NULLSOCKET));
1868 MUTEX_EXIT(&sq->lock);
1870 MUTEX_ENTER(&freeSQEList_lock);
1871 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1872 rx_FreeSQEList = sq;
1873 MUTEX_EXIT(&freeSQEList_lock);
1876 clock_GetTime(&call->startTime);
1877 call->state = RX_STATE_ACTIVE;
1878 call->mode = RX_MODE_RECEIVING;
1879 #ifdef RX_KERNEL_TRACE
1880 if (ICL_SETACTIVE(afs_iclSetp)) {
1881 int glockOwner = ISAFS_GLOCK();
1884 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1885 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1892 rxi_calltrace(RX_CALL_START, call);
1893 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
1894 call->conn->service->servicePort, call->conn->service->serviceId,
1897 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1904 #endif /* RX_ENABLE_LOCKS */
1908 /* Establish a procedure to be called when a packet arrives for a
1909 * call. This routine will be called at most once after each call,
1910 * and will also be called if there is an error condition on the or
1911 * the call is complete. Used by multi rx to build a selection
1912 * function which determines which of several calls is likely to be a
1913 * good one to read from.
1914 * NOTE: the way this is currently implemented it is probably only a
1915 * good idea to (1) use it immediately after a newcall (clients only)
1916 * and (2) only use it once. Other uses currently void your warranty
1919 rx_SetArrivalProc(struct rx_call *call,
1920 void (*proc) (struct rx_call * call,
1923 void * handle, int arg)
1925 call->arrivalProc = proc;
1926 call->arrivalProcHandle = handle;
1927 call->arrivalProcArg = arg;
1930 /* Call is finished (possibly prematurely). Return rc to the peer, if
1931 * appropriate, and return the final error code from the conversation
1935 rx_EndCall(struct rx_call *call, afs_int32 rc)
1937 struct rx_connection *conn = call->conn;
1938 struct rx_service *service;
1944 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
1945 call, rc, call->error, call->abortCode));
1948 MUTEX_ENTER(&call->lock);
1950 if (rc == 0 && call->error == 0) {
1951 call->abortCode = 0;
1952 call->abortCount = 0;
1955 call->arrivalProc = (void (*)())0;
1956 if (rc && call->error == 0) {
1957 rxi_CallError(call, rc);
1958 /* Send an abort message to the peer if this error code has
1959 * only just been set. If it was set previously, assume the
1960 * peer has already been sent the error code or will request it
1962 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1964 if (conn->type == RX_SERVER_CONNECTION) {
1965 /* Make sure reply or at least dummy reply is sent */
1966 if (call->mode == RX_MODE_RECEIVING) {
1967 rxi_WriteProc(call, 0, 0);
1969 if (call->mode == RX_MODE_SENDING) {
1970 rxi_FlushWrite(call);
1972 service = conn->service;
1973 rxi_calltrace(RX_CALL_END, call);
1974 /* Call goes to hold state until reply packets are acknowledged */
1975 if (call->tfirst + call->nSoftAcked < call->tnext) {
1976 call->state = RX_STATE_HOLD;
1978 call->state = RX_STATE_DALLY;
1979 rxi_ClearTransmitQueue(call, 0);
1980 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
1981 rxevent_Cancel(call->keepAliveEvent, call,
1982 RX_CALL_REFCOUNT_ALIVE);
1984 } else { /* Client connection */
1986 /* Make sure server receives input packets, in the case where
1987 * no reply arguments are expected */
1988 if ((call->mode == RX_MODE_SENDING)
1989 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
1990 (void)rxi_ReadProc(call, &dummy, 1);
1993 /* If we had an outstanding delayed ack, be nice to the server
1994 * and force-send it now.
1996 if (call->delayedAckEvent) {
1997 rxevent_Cancel(call->delayedAckEvent, call,
1998 RX_CALL_REFCOUNT_DELAY);
1999 call->delayedAckEvent = NULL;
2000 rxi_SendDelayedAck(NULL, call, NULL);
2003 /* We need to release the call lock since it's lower than the
2004 * conn_call_lock and we don't want to hold the conn_call_lock
2005 * over the rx_ReadProc call. The conn_call_lock needs to be held
2006 * here for the case where rx_NewCall is perusing the calls on
2007 * the connection structure. We don't want to signal until
2008 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2009 * have checked this call, found it active and by the time it
2010 * goes to sleep, will have missed the signal.
2012 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2013 * there are threads waiting to use the conn object.
2015 MUTEX_EXIT(&call->lock);
2016 MUTEX_ENTER(&conn->conn_call_lock);
2017 MUTEX_ENTER(&call->lock);
2018 MUTEX_ENTER(&conn->conn_data_lock);
2019 conn->flags |= RX_CONN_BUSY;
2020 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2021 if (conn->makeCallWaiters == 0)
2022 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2023 MUTEX_EXIT(&conn->conn_data_lock);
2024 #ifdef RX_ENABLE_LOCKS
2025 CV_BROADCAST(&conn->conn_call_cv);
2030 #ifdef RX_ENABLE_LOCKS
2032 MUTEX_EXIT(&conn->conn_data_lock);
2034 #endif /* RX_ENABLE_LOCKS */
2035 call->state = RX_STATE_DALLY;
2037 error = call->error;
2039 /* currentPacket, nLeft, and NFree must be zeroed here, because
2040 * ResetCall cannot: ResetCall may be called at splnet(), in the
2041 * kernel version, and may interrupt the macros rx_Read or
2042 * rx_Write, which run at normal priority for efficiency. */
2043 if (call->currentPacket) {
2044 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2045 rxi_FreePacket(call->currentPacket);
2046 call->currentPacket = (struct rx_packet *)0;
2049 call->nLeft = call->nFree = call->curlen = 0;
2051 /* Free any packets from the last call to ReadvProc/WritevProc */
2052 #ifdef RXDEBUG_PACKET
2054 #endif /* RXDEBUG_PACKET */
2055 rxi_FreePackets(0, &call->iovq);
2057 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2058 MUTEX_EXIT(&call->lock);
2059 if (conn->type == RX_CLIENT_CONNECTION) {
2060 MUTEX_EXIT(&conn->conn_call_lock);
2061 conn->flags &= ~RX_CONN_BUSY;
2065 * Map errors to the local host's errno.h format.
2067 error = ntoh_syserr_conv(error);
2071 #if !defined(KERNEL)
2073 /* Call this routine when shutting down a server or client (especially
2074 * clients). This will allow Rx to gracefully garbage collect server
2075 * connections, and reduce the number of retries that a server might
2076 * make to a dead client.
2077 * This is not quite right, since some calls may still be ongoing and
2078 * we can't lock them to destroy them. */
2082 struct rx_connection **conn_ptr, **conn_end;
2086 if (rxinit_status == 1) {
2088 return; /* Already shutdown. */
2090 rxi_DeleteCachedConnections();
2091 if (rx_connHashTable) {
2092 MUTEX_ENTER(&rx_connHashTable_lock);
2093 for (conn_ptr = &rx_connHashTable[0], conn_end =
2094 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2096 struct rx_connection *conn, *next;
2097 for (conn = *conn_ptr; conn; conn = next) {
2099 if (conn->type == RX_CLIENT_CONNECTION) {
2100 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2102 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2103 #ifdef RX_ENABLE_LOCKS
2104 rxi_DestroyConnectionNoLock(conn);
2105 #else /* RX_ENABLE_LOCKS */
2106 rxi_DestroyConnection(conn);
2107 #endif /* RX_ENABLE_LOCKS */
2111 #ifdef RX_ENABLE_LOCKS
2112 while (rx_connCleanup_list) {
2113 struct rx_connection *conn;
2114 conn = rx_connCleanup_list;
2115 rx_connCleanup_list = rx_connCleanup_list->next;
2116 MUTEX_EXIT(&rx_connHashTable_lock);
2117 rxi_CleanupConnection(conn);
2118 MUTEX_ENTER(&rx_connHashTable_lock);
2120 MUTEX_EXIT(&rx_connHashTable_lock);
2121 #endif /* RX_ENABLE_LOCKS */
2126 afs_winsockCleanup();
2134 /* if we wakeup packet waiter too often, can get in loop with two
2135 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2137 rxi_PacketsUnWait(void)
2139 if (!rx_waitingForPackets) {
2143 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2144 return; /* still over quota */
2147 rx_waitingForPackets = 0;
2148 #ifdef RX_ENABLE_LOCKS
2149 CV_BROADCAST(&rx_waitingForPackets_cv);
2151 osi_rxWakeup(&rx_waitingForPackets);
2157 /* ------------------Internal interfaces------------------------- */
2159 /* Return this process's service structure for the
2160 * specified socket and service */
2162 rxi_FindService(osi_socket socket, u_short serviceId)
2164 struct rx_service **sp;
2165 for (sp = &rx_services[0]; *sp; sp++) {
2166 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2172 #ifdef RXDEBUG_PACKET
2173 #ifdef KDUMP_RX_LOCK
2174 static struct rx_call_rx_lock *rx_allCallsp = 0;
2176 static struct rx_call *rx_allCallsp = 0;
2178 #endif /* RXDEBUG_PACKET */
2180 /* Allocate a call structure, for the indicated channel of the
2181 * supplied connection. The mode and state of the call must be set by
2182 * the caller. Returns the call with mutex locked. */
2184 rxi_NewCall(struct rx_connection *conn, int channel)
2186 struct rx_call *call;
2187 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2188 struct rx_call *cp; /* Call pointer temp */
2189 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2190 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2192 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2194 /* Grab an existing call structure, or allocate a new one.
2195 * Existing call structures are assumed to have been left reset by
2197 MUTEX_ENTER(&rx_freeCallQueue_lock);
2199 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2201 * EXCEPT that the TQ might not yet be cleared out.
2202 * Skip over those with in-use TQs.
2205 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2206 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2212 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2213 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2214 call = queue_First(&rx_freeCallQueue, rx_call);
2215 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2217 if (rx_stats_active)
2218 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2219 MUTEX_EXIT(&rx_freeCallQueue_lock);
2220 MUTEX_ENTER(&call->lock);
2221 CLEAR_CALL_QUEUE_LOCK(call);
2222 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2223 /* Now, if TQ wasn't cleared earlier, do it now. */
2224 rxi_WaitforTQBusy(call);
2225 if (call->flags & RX_CALL_TQ_CLEARME) {
2226 rxi_ClearTransmitQueue(call, 1);
2227 /*queue_Init(&call->tq);*/
2229 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2230 /* Bind the call to its connection structure */
2232 rxi_ResetCall(call, 1);
2235 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2236 #ifdef RXDEBUG_PACKET
2237 call->allNextp = rx_allCallsp;
2238 rx_allCallsp = call;
2240 #endif /* RXDEBUG_PACKET */
2241 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2243 MUTEX_EXIT(&rx_freeCallQueue_lock);
2244 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2245 MUTEX_ENTER(&call->lock);
2246 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2247 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2248 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2250 /* Initialize once-only items */
2251 queue_Init(&call->tq);
2252 queue_Init(&call->rq);
2253 queue_Init(&call->iovq);
2254 #ifdef RXDEBUG_PACKET
2255 call->rqc = call->tqc = call->iovqc = 0;
2256 #endif /* RXDEBUG_PACKET */
2257 /* Bind the call to its connection structure (prereq for reset) */
2259 rxi_ResetCall(call, 1);
2261 call->channel = channel;
2262 call->callNumber = &conn->callNumber[channel];
2263 call->rwind = conn->rwind[channel];
2264 call->twind = conn->twind[channel];
2265 /* Note that the next expected call number is retained (in
2266 * conn->callNumber[i]), even if we reallocate the call structure
2268 conn->call[channel] = call;
2269 /* if the channel's never been used (== 0), we should start at 1, otherwise
2270 * the call number is valid from the last time this channel was used */
2271 if (*call->callNumber == 0)
2272 *call->callNumber = 1;
2277 /* A call has been inactive long enough that so we can throw away
2278 * state, including the call structure, which is placed on the call
2280 * Call is locked upon entry.
2281 * haveCTLock set if called from rxi_ReapConnections
2283 #ifdef RX_ENABLE_LOCKS
2285 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2286 #else /* RX_ENABLE_LOCKS */
2288 rxi_FreeCall(struct rx_call *call)
2289 #endif /* RX_ENABLE_LOCKS */
2291 int channel = call->channel;
2292 struct rx_connection *conn = call->conn;
2295 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2296 (*call->callNumber)++;
2297 rxi_ResetCall(call, 0);
2298 call->conn->call[channel] = (struct rx_call *)0;
2300 MUTEX_ENTER(&rx_freeCallQueue_lock);
2301 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2302 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2303 /* A call may be free even though its transmit queue is still in use.
2304 * Since we search the call list from head to tail, put busy calls at
2305 * the head of the list, and idle calls at the tail.
2307 if (call->flags & RX_CALL_TQ_BUSY)
2308 queue_Prepend(&rx_freeCallQueue, call);
2310 queue_Append(&rx_freeCallQueue, call);
2311 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2312 queue_Append(&rx_freeCallQueue, call);
2313 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2314 if (rx_stats_active)
2315 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2316 MUTEX_EXIT(&rx_freeCallQueue_lock);
2318 /* Destroy the connection if it was previously slated for
2319 * destruction, i.e. the Rx client code previously called
2320 * rx_DestroyConnection (client connections), or
2321 * rxi_ReapConnections called the same routine (server
2322 * connections). Only do this, however, if there are no
2323 * outstanding calls. Note that for fine grain locking, there appears
2324 * to be a deadlock in that rxi_FreeCall has a call locked and
2325 * DestroyConnectionNoLock locks each call in the conn. But note a
2326 * few lines up where we have removed this call from the conn.
2327 * If someone else destroys a connection, they either have no
2328 * call lock held or are going through this section of code.
2330 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2331 MUTEX_ENTER(&conn->conn_data_lock);
2333 MUTEX_EXIT(&conn->conn_data_lock);
2334 #ifdef RX_ENABLE_LOCKS
2336 rxi_DestroyConnectionNoLock(conn);
2338 rxi_DestroyConnection(conn);
2339 #else /* RX_ENABLE_LOCKS */
2340 rxi_DestroyConnection(conn);
2341 #endif /* RX_ENABLE_LOCKS */
2345 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2347 rxi_Alloc(size_t size)
2351 if (rx_stats_active)
2352 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2355 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2356 afs_osi_Alloc_NoSleep(size);
2361 osi_Panic("rxi_Alloc error");
2367 rxi_Free(void *addr, size_t size)
2369 if (rx_stats_active)
2370 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2371 osi_Free(addr, size);
2375 rxi_SetPeerMtu(afs_uint32 host, afs_uint32 port, int mtu)
2377 struct rx_peer **peer_ptr, **peer_end;
2380 MUTEX_ENTER(&rx_peerHashTable_lock);
2382 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2383 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2385 struct rx_peer *peer, *next;
2386 for (peer = *peer_ptr; peer; peer = next) {
2388 if (host == peer->host) {
2389 MUTEX_ENTER(&peer->peer_lock);
2390 peer->ifMTU=MIN(mtu, peer->ifMTU);
2391 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2392 MUTEX_EXIT(&peer->peer_lock);
2397 struct rx_peer *peer;
2398 hashIndex = PEER_HASH(host, port);
2399 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2400 if ((peer->host == host) && (peer->port == port)) {
2401 MUTEX_ENTER(&peer->peer_lock);
2402 peer->ifMTU=MIN(mtu, peer->ifMTU);
2403 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2404 MUTEX_EXIT(&peer->peer_lock);
2408 MUTEX_EXIT(&rx_peerHashTable_lock);
2411 /* Find the peer process represented by the supplied (host,port)
2412 * combination. If there is no appropriate active peer structure, a
2413 * new one will be allocated and initialized
2414 * The origPeer, if set, is a pointer to a peer structure on which the
2415 * refcount will be be decremented. This is used to replace the peer
2416 * structure hanging off a connection structure */
2418 rxi_FindPeer(afs_uint32 host, u_short port,
2419 struct rx_peer *origPeer, int create)
2423 hashIndex = PEER_HASH(host, port);
2424 MUTEX_ENTER(&rx_peerHashTable_lock);
2425 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2426 if ((pp->host == host) && (pp->port == port))
2431 pp = rxi_AllocPeer(); /* This bzero's *pp */
2432 pp->host = host; /* set here or in InitPeerParams is zero */
2434 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2435 queue_Init(&pp->congestionQueue);
2436 queue_Init(&pp->rpcStats);
2437 pp->next = rx_peerHashTable[hashIndex];
2438 rx_peerHashTable[hashIndex] = pp;
2439 rxi_InitPeerParams(pp);
2440 if (rx_stats_active)
2441 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2448 origPeer->refCount--;
2449 MUTEX_EXIT(&rx_peerHashTable_lock);
2454 /* Find the connection at (host, port) started at epoch, and with the
2455 * given connection id. Creates the server connection if necessary.
2456 * The type specifies whether a client connection or a server
2457 * connection is desired. In both cases, (host, port) specify the
2458 * peer's (host, pair) pair. Client connections are not made
2459 * automatically by this routine. The parameter socket gives the
2460 * socket descriptor on which the packet was received. This is used,
2461 * in the case of server connections, to check that *new* connections
2462 * come via a valid (port, serviceId). Finally, the securityIndex
2463 * parameter must match the existing index for the connection. If a
2464 * server connection is created, it will be created using the supplied
2465 * index, if the index is valid for this service */
2466 struct rx_connection *
2467 rxi_FindConnection(osi_socket socket, afs_int32 host,
2468 u_short port, u_short serviceId, afs_uint32 cid,
2469 afs_uint32 epoch, int type, u_int securityIndex)
2471 int hashindex, flag, i;
2472 struct rx_connection *conn;
2473 hashindex = CONN_HASH(host, port, cid, epoch, type);
2474 MUTEX_ENTER(&rx_connHashTable_lock);
2475 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2476 rx_connHashTable[hashindex],
2479 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2480 && (epoch == conn->epoch)) {
2481 struct rx_peer *pp = conn->peer;
2482 if (securityIndex != conn->securityIndex) {
2483 /* this isn't supposed to happen, but someone could forge a packet
2484 * like this, and there seems to be some CM bug that makes this
2485 * happen from time to time -- in which case, the fileserver
2487 MUTEX_EXIT(&rx_connHashTable_lock);
2488 return (struct rx_connection *)0;
2490 if (pp->host == host && pp->port == port)
2492 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2494 /* So what happens when it's a callback connection? */
2495 if ( /*type == RX_CLIENT_CONNECTION && */
2496 (conn->epoch & 0x80000000))
2500 /* the connection rxLastConn that was used the last time is not the
2501 ** one we are looking for now. Hence, start searching in the hash */
2503 conn = rx_connHashTable[hashindex];
2508 struct rx_service *service;
2509 if (type == RX_CLIENT_CONNECTION) {
2510 MUTEX_EXIT(&rx_connHashTable_lock);
2511 return (struct rx_connection *)0;
2513 service = rxi_FindService(socket, serviceId);
2514 if (!service || (securityIndex >= service->nSecurityObjects)
2515 || (service->securityObjects[securityIndex] == 0)) {
2516 MUTEX_EXIT(&rx_connHashTable_lock);
2517 return (struct rx_connection *)0;
2519 conn = rxi_AllocConnection(); /* This bzero's the connection */
2520 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2521 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2522 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2523 conn->next = rx_connHashTable[hashindex];
2524 rx_connHashTable[hashindex] = conn;
2525 conn->peer = rxi_FindPeer(host, port, 0, 1);
2526 conn->type = RX_SERVER_CONNECTION;
2527 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2528 conn->epoch = epoch;
2529 conn->cid = cid & RX_CIDMASK;
2530 /* conn->serial = conn->lastSerial = 0; */
2531 /* conn->timeout = 0; */
2532 conn->ackRate = RX_FAST_ACK_RATE;
2533 conn->service = service;
2534 conn->serviceId = serviceId;
2535 conn->securityIndex = securityIndex;
2536 conn->securityObject = service->securityObjects[securityIndex];
2537 conn->nSpecific = 0;
2538 conn->specific = NULL;
2539 rx_SetConnDeadTime(conn, service->connDeadTime);
2540 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2541 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2542 for (i = 0; i < RX_MAXCALLS; i++) {
2543 conn->twind[i] = rx_initSendWindow;
2544 conn->rwind[i] = rx_initReceiveWindow;
2546 /* Notify security object of the new connection */
2547 RXS_NewConnection(conn->securityObject, conn);
2548 /* XXXX Connection timeout? */
2549 if (service->newConnProc)
2550 (*service->newConnProc) (conn);
2551 if (rx_stats_active)
2552 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2555 MUTEX_ENTER(&conn->conn_data_lock);
2557 MUTEX_EXIT(&conn->conn_data_lock);
2559 rxLastConn = conn; /* store this connection as the last conn used */
2560 MUTEX_EXIT(&rx_connHashTable_lock);
2564 /* There are two packet tracing routines available for testing and monitoring
2565 * Rx. One is called just after every packet is received and the other is
2566 * called just before every packet is sent. Received packets, have had their
2567 * headers decoded, and packets to be sent have not yet had their headers
2568 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2569 * containing the network address. Both can be modified. The return value, if
2570 * non-zero, indicates that the packet should be dropped. */
2572 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2573 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2575 /* A packet has been received off the interface. Np is the packet, socket is
2576 * the socket number it was received from (useful in determining which service
2577 * this packet corresponds to), and (host, port) reflect the host,port of the
2578 * sender. This call returns the packet to the caller if it is finished with
2579 * it, rather than de-allocating it, just as a small performance hack */
2582 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2583 afs_uint32 host, u_short port, int *tnop,
2584 struct rx_call **newcallp)
2586 struct rx_call *call;
2587 struct rx_connection *conn;
2589 afs_uint32 currentCallNumber;
2595 struct rx_packet *tnp;
2598 /* We don't print out the packet until now because (1) the time may not be
2599 * accurate enough until now in the lwp implementation (rx_Listener only gets
2600 * the time after the packet is read) and (2) from a protocol point of view,
2601 * this is the first time the packet has been seen */
2602 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2603 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2604 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2605 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2606 np->header.epoch, np->header.cid, np->header.callNumber,
2607 np->header.seq, np->header.flags, np));
2610 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2611 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2614 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2615 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2618 /* If an input tracer function is defined, call it with the packet and
2619 * network address. Note this function may modify its arguments. */
2620 if (rx_justReceived) {
2621 struct sockaddr_in addr;
2623 addr.sin_family = AF_INET;
2624 addr.sin_port = port;
2625 addr.sin_addr.s_addr = host;
2626 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2627 addr.sin_len = sizeof(addr);
2628 #endif /* AFS_OSF_ENV */
2629 drop = (*rx_justReceived) (np, &addr);
2630 /* drop packet if return value is non-zero */
2633 port = addr.sin_port; /* in case fcn changed addr */
2634 host = addr.sin_addr.s_addr;
2638 /* If packet was not sent by the client, then *we* must be the client */
2639 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2640 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2642 /* Find the connection (or fabricate one, if we're the server & if
2643 * necessary) associated with this packet */
2645 rxi_FindConnection(socket, host, port, np->header.serviceId,
2646 np->header.cid, np->header.epoch, type,
2647 np->header.securityIndex);
2650 /* If no connection found or fabricated, just ignore the packet.
2651 * (An argument could be made for sending an abort packet for
2656 MUTEX_ENTER(&conn->conn_data_lock);
2657 if (conn->maxSerial < np->header.serial)
2658 conn->maxSerial = np->header.serial;
2659 MUTEX_EXIT(&conn->conn_data_lock);
2661 /* If the connection is in an error state, send an abort packet and ignore
2662 * the incoming packet */
2664 /* Don't respond to an abort packet--we don't want loops! */
2665 MUTEX_ENTER(&conn->conn_data_lock);
2666 if (np->header.type != RX_PACKET_TYPE_ABORT)
2667 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2669 MUTEX_EXIT(&conn->conn_data_lock);
2673 /* Check for connection-only requests (i.e. not call specific). */
2674 if (np->header.callNumber == 0) {
2675 switch (np->header.type) {
2676 case RX_PACKET_TYPE_ABORT: {
2677 /* What if the supplied error is zero? */
2678 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2679 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2680 rxi_ConnectionError(conn, errcode);
2681 MUTEX_ENTER(&conn->conn_data_lock);
2683 MUTEX_EXIT(&conn->conn_data_lock);
2686 case RX_PACKET_TYPE_CHALLENGE:
2687 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2688 MUTEX_ENTER(&conn->conn_data_lock);
2690 MUTEX_EXIT(&conn->conn_data_lock);
2692 case RX_PACKET_TYPE_RESPONSE:
2693 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2694 MUTEX_ENTER(&conn->conn_data_lock);
2696 MUTEX_EXIT(&conn->conn_data_lock);
2698 case RX_PACKET_TYPE_PARAMS:
2699 case RX_PACKET_TYPE_PARAMS + 1:
2700 case RX_PACKET_TYPE_PARAMS + 2:
2701 /* ignore these packet types for now */
2702 MUTEX_ENTER(&conn->conn_data_lock);
2704 MUTEX_EXIT(&conn->conn_data_lock);
2709 /* Should not reach here, unless the peer is broken: send an
2711 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2712 MUTEX_ENTER(&conn->conn_data_lock);
2713 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2715 MUTEX_EXIT(&conn->conn_data_lock);
2720 channel = np->header.cid & RX_CHANNELMASK;
2721 call = conn->call[channel];
2722 #ifdef RX_ENABLE_LOCKS
2724 MUTEX_ENTER(&call->lock);
2725 /* Test to see if call struct is still attached to conn. */
2726 if (call != conn->call[channel]) {
2728 MUTEX_EXIT(&call->lock);
2729 if (type == RX_SERVER_CONNECTION) {
2730 call = conn->call[channel];
2731 /* If we started with no call attached and there is one now,
2732 * another thread is also running this routine and has gotten
2733 * the connection channel. We should drop this packet in the tests
2734 * below. If there was a call on this connection and it's now
2735 * gone, then we'll be making a new call below.
2736 * If there was previously a call and it's now different then
2737 * the old call was freed and another thread running this routine
2738 * has created a call on this channel. One of these two threads
2739 * has a packet for the old call and the code below handles those
2743 MUTEX_ENTER(&call->lock);
2745 /* This packet can't be for this call. If the new call address is
2746 * 0 then no call is running on this channel. If there is a call
2747 * then, since this is a client connection we're getting data for
2748 * it must be for the previous call.
2750 if (rx_stats_active)
2751 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2752 MUTEX_ENTER(&conn->conn_data_lock);
2754 MUTEX_EXIT(&conn->conn_data_lock);
2759 currentCallNumber = conn->callNumber[channel];
2761 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2762 if (np->header.callNumber < currentCallNumber) {
2763 if (rx_stats_active)
2764 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2765 #ifdef RX_ENABLE_LOCKS
2767 MUTEX_EXIT(&call->lock);
2769 MUTEX_ENTER(&conn->conn_data_lock);
2771 MUTEX_EXIT(&conn->conn_data_lock);
2775 MUTEX_ENTER(&conn->conn_call_lock);
2776 call = rxi_NewCall(conn, channel);
2777 MUTEX_EXIT(&conn->conn_call_lock);
2778 *call->callNumber = np->header.callNumber;
2780 if (np->header.callNumber == 0)
2781 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d",
2782 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2783 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2784 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2786 call->state = RX_STATE_PRECALL;
2787 clock_GetTime(&call->queueTime);
2788 hzero(call->bytesSent);
2789 hzero(call->bytesRcvd);
2791 * If the number of queued calls exceeds the overload
2792 * threshold then abort this call.
2794 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2795 struct rx_packet *tp;
2797 rxi_CallError(call, rx_BusyError);
2798 tp = rxi_SendCallAbort(call, np, 1, 0);
2799 MUTEX_EXIT(&call->lock);
2800 MUTEX_ENTER(&conn->conn_data_lock);
2802 MUTEX_EXIT(&conn->conn_data_lock);
2803 if (rx_stats_active)
2804 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2807 rxi_KeepAliveOn(call);
2808 } else if (np->header.callNumber != currentCallNumber) {
2809 /* Wait until the transmit queue is idle before deciding
2810 * whether to reset the current call. Chances are that the
2811 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2814 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2815 while ((call->state == RX_STATE_ACTIVE)
2816 && (call->flags & RX_CALL_TQ_BUSY)) {
2817 call->flags |= RX_CALL_TQ_WAIT;
2819 #ifdef RX_ENABLE_LOCKS
2820 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2821 CV_WAIT(&call->cv_tq, &call->lock);
2822 #else /* RX_ENABLE_LOCKS */
2823 osi_rxSleep(&call->tq);
2824 #endif /* RX_ENABLE_LOCKS */
2826 if (call->tqWaiters == 0)
2827 call->flags &= ~RX_CALL_TQ_WAIT;
2829 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2830 /* If the new call cannot be taken right now send a busy and set
2831 * the error condition in this call, so that it terminates as
2832 * quickly as possible */
2833 if (call->state == RX_STATE_ACTIVE) {
2834 struct rx_packet *tp;
2836 rxi_CallError(call, RX_CALL_DEAD);
2837 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2839 MUTEX_EXIT(&call->lock);
2840 MUTEX_ENTER(&conn->conn_data_lock);
2842 MUTEX_EXIT(&conn->conn_data_lock);
2845 rxi_ResetCall(call, 0);
2846 *call->callNumber = np->header.callNumber;
2848 if (np->header.callNumber == 0)
2849 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
2850 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2851 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2852 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
2854 call->state = RX_STATE_PRECALL;
2855 clock_GetTime(&call->queueTime);
2856 hzero(call->bytesSent);
2857 hzero(call->bytesRcvd);
2859 * If the number of queued calls exceeds the overload
2860 * threshold then abort this call.
2862 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2863 struct rx_packet *tp;
2865 rxi_CallError(call, rx_BusyError);
2866 tp = rxi_SendCallAbort(call, np, 1, 0);
2867 MUTEX_EXIT(&call->lock);
2868 MUTEX_ENTER(&conn->conn_data_lock);
2870 MUTEX_EXIT(&conn->conn_data_lock);
2871 if (rx_stats_active)
2872 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2875 rxi_KeepAliveOn(call);
2877 /* Continuing call; do nothing here. */
2879 } else { /* we're the client */
2880 /* Ignore all incoming acknowledgements for calls in DALLY state */
2881 if (call && (call->state == RX_STATE_DALLY)
2882 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2883 if (rx_stats_active)
2884 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2885 #ifdef RX_ENABLE_LOCKS
2887 MUTEX_EXIT(&call->lock);
2890 MUTEX_ENTER(&conn->conn_data_lock);
2892 MUTEX_EXIT(&conn->conn_data_lock);
2896 /* Ignore anything that's not relevant to the current call. If there
2897 * isn't a current call, then no packet is relevant. */
2898 if (!call || (np->header.callNumber != currentCallNumber)) {
2899 if (rx_stats_active)
2900 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2901 #ifdef RX_ENABLE_LOCKS
2903 MUTEX_EXIT(&call->lock);
2906 MUTEX_ENTER(&conn->conn_data_lock);
2908 MUTEX_EXIT(&conn->conn_data_lock);
2911 /* If the service security object index stamped in the packet does not
2912 * match the connection's security index, ignore the packet */
2913 if (np->header.securityIndex != conn->securityIndex) {
2914 #ifdef RX_ENABLE_LOCKS
2915 MUTEX_EXIT(&call->lock);
2917 MUTEX_ENTER(&conn->conn_data_lock);
2919 MUTEX_EXIT(&conn->conn_data_lock);
2923 /* If we're receiving the response, then all transmit packets are
2924 * implicitly acknowledged. Get rid of them. */
2925 if (np->header.type == RX_PACKET_TYPE_DATA) {
2926 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2927 /* XXX Hack. Because we must release the global rx lock when
2928 * sending packets (osi_NetSend) we drop all acks while we're
2929 * traversing the tq in rxi_Start sending packets out because
2930 * packets may move to the freePacketQueue as result of being here!
2931 * So we drop these packets until we're safely out of the
2932 * traversing. Really ugly!
2933 * For fine grain RX locking, we set the acked field in the
2934 * packets and let rxi_Start remove them from the transmit queue.
2936 if (call->flags & RX_CALL_TQ_BUSY) {
2937 #ifdef RX_ENABLE_LOCKS
2938 rxi_SetAcksInTransmitQueue(call);
2941 return np; /* xmitting; drop packet */
2944 rxi_ClearTransmitQueue(call, 0);
2946 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2947 rxi_ClearTransmitQueue(call, 0);
2948 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2950 if (np->header.type == RX_PACKET_TYPE_ACK) {
2951 /* now check to see if this is an ack packet acknowledging that the
2952 * server actually *lost* some hard-acked data. If this happens we
2953 * ignore this packet, as it may indicate that the server restarted in
2954 * the middle of a call. It is also possible that this is an old ack
2955 * packet. We don't abort the connection in this case, because this
2956 * *might* just be an old ack packet. The right way to detect a server
2957 * restart in the midst of a call is to notice that the server epoch
2959 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2960 * XXX unacknowledged. I think that this is off-by-one, but
2961 * XXX I don't dare change it just yet, since it will
2962 * XXX interact badly with the server-restart detection
2963 * XXX code in receiveackpacket. */
2964 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2965 if (rx_stats_active)
2966 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2967 MUTEX_EXIT(&call->lock);
2968 MUTEX_ENTER(&conn->conn_data_lock);
2970 MUTEX_EXIT(&conn->conn_data_lock);
2974 } /* else not a data packet */
2977 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2978 /* Set remote user defined status from packet */
2979 call->remoteStatus = np->header.userStatus;
2981 /* Note the gap between the expected next packet and the actual
2982 * packet that arrived, when the new packet has a smaller serial number
2983 * than expected. Rioses frequently reorder packets all by themselves,
2984 * so this will be quite important with very large window sizes.
2985 * Skew is checked against 0 here to avoid any dependence on the type of
2986 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2988 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2989 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2990 * I think using a beta of 1/8 is probably appropriate. 93.04.21
2992 MUTEX_ENTER(&conn->conn_data_lock);
2993 skew = conn->lastSerial - np->header.serial;
2994 conn->lastSerial = np->header.serial;
2995 MUTEX_EXIT(&conn->conn_data_lock);
2997 struct rx_peer *peer;
2999 if (skew > peer->inPacketSkew) {
3000 dpf(("*** In skew changed from %d to %d\n",
3001 peer->inPacketSkew, skew));
3002 peer->inPacketSkew = skew;
3006 /* Now do packet type-specific processing */
3007 switch (np->header.type) {
3008 case RX_PACKET_TYPE_DATA:
3009 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3012 case RX_PACKET_TYPE_ACK:
3013 /* Respond immediately to ack packets requesting acknowledgement
3015 if (np->header.flags & RX_REQUEST_ACK) {
3017 (void)rxi_SendCallAbort(call, 0, 1, 0);
3019 (void)rxi_SendAck(call, 0, np->header.serial,
3020 RX_ACK_PING_RESPONSE, 1);
3022 np = rxi_ReceiveAckPacket(call, np, 1);
3024 case RX_PACKET_TYPE_ABORT: {
3025 /* An abort packet: reset the call, passing the error up to the user. */
3026 /* What if error is zero? */
3027 /* What if the error is -1? the application will treat it as a timeout. */
3028 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3029 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3030 rxi_CallError(call, errdata);
3031 MUTEX_EXIT(&call->lock);
3032 MUTEX_ENTER(&conn->conn_data_lock);
3034 MUTEX_EXIT(&conn->conn_data_lock);
3035 return np; /* xmitting; drop packet */
3037 case RX_PACKET_TYPE_BUSY:
3040 case RX_PACKET_TYPE_ACKALL:
3041 /* All packets acknowledged, so we can drop all packets previously
3042 * readied for sending */
3043 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3044 /* XXX Hack. We because we can't release the global rx lock when
3045 * sending packets (osi_NetSend) we drop all ack pkts while we're
3046 * traversing the tq in rxi_Start sending packets out because
3047 * packets may move to the freePacketQueue as result of being
3048 * here! So we drop these packets until we're safely out of the
3049 * traversing. Really ugly!
3050 * For fine grain RX locking, we set the acked field in the packets
3051 * and let rxi_Start remove the packets from the transmit queue.
3053 if (call->flags & RX_CALL_TQ_BUSY) {
3054 #ifdef RX_ENABLE_LOCKS
3055 rxi_SetAcksInTransmitQueue(call);
3057 #else /* RX_ENABLE_LOCKS */
3058 MUTEX_EXIT(&call->lock);
3059 MUTEX_ENTER(&conn->conn_data_lock);
3061 MUTEX_EXIT(&conn->conn_data_lock);
3062 return np; /* xmitting; drop packet */
3063 #endif /* RX_ENABLE_LOCKS */
3065 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3066 rxi_ClearTransmitQueue(call, 0);
3067 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3070 /* Should not reach here, unless the peer is broken: send an abort
3072 rxi_CallError(call, RX_PROTOCOL_ERROR);
3073 np = rxi_SendCallAbort(call, np, 1, 0);
3076 /* Note when this last legitimate packet was received, for keep-alive
3077 * processing. Note, we delay getting the time until now in the hope that
3078 * the packet will be delivered to the user before any get time is required
3079 * (if not, then the time won't actually be re-evaluated here). */
3080 call->lastReceiveTime = clock_Sec();
3081 MUTEX_EXIT(&call->lock);
3082 MUTEX_ENTER(&conn->conn_data_lock);
3084 MUTEX_EXIT(&conn->conn_data_lock);
3088 /* return true if this is an "interesting" connection from the point of view
3089 of someone trying to debug the system */
3091 rxi_IsConnInteresting(struct rx_connection *aconn)
3094 struct rx_call *tcall;
3096 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3098 for (i = 0; i < RX_MAXCALLS; i++) {
3099 tcall = aconn->call[i];
3101 if ((tcall->state == RX_STATE_PRECALL)
3102 || (tcall->state == RX_STATE_ACTIVE))
3104 if ((tcall->mode == RX_MODE_SENDING)
3105 || (tcall->mode == RX_MODE_RECEIVING))
3113 /* if this is one of the last few packets AND it wouldn't be used by the
3114 receiving call to immediately satisfy a read request, then drop it on
3115 the floor, since accepting it might prevent a lock-holding thread from
3116 making progress in its reading. If a call has been cleared while in
3117 the precall state then ignore all subsequent packets until the call
3118 is assigned to a thread. */
3121 TooLow(struct rx_packet *ap, struct rx_call *acall)
3125 MUTEX_ENTER(&rx_quota_mutex);
3126 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3127 && (acall->state == RX_STATE_PRECALL))
3128 || ((rx_nFreePackets < rxi_dataQuota + 2)
3129 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3130 && (acall->flags & RX_CALL_READER_WAIT)))) {
3133 MUTEX_EXIT(&rx_quota_mutex);
3139 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3141 struct rx_connection *conn = arg1;
3142 struct rx_call *acall = arg2;
3143 struct rx_call *call = acall;
3144 struct clock when, now;
3147 MUTEX_ENTER(&conn->conn_data_lock);
3148 conn->checkReachEvent = NULL;
3149 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3152 MUTEX_EXIT(&conn->conn_data_lock);
3156 MUTEX_ENTER(&conn->conn_call_lock);
3157 MUTEX_ENTER(&conn->conn_data_lock);
3158 for (i = 0; i < RX_MAXCALLS; i++) {
3159 struct rx_call *tc = conn->call[i];
3160 if (tc && tc->state == RX_STATE_PRECALL) {
3166 /* Indicate that rxi_CheckReachEvent is no longer running by
3167 * clearing the flag. Must be atomic under conn_data_lock to
3168 * avoid a new call slipping by: rxi_CheckConnReach holds
3169 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3171 conn->flags &= ~RX_CONN_ATTACHWAIT;
3172 MUTEX_EXIT(&conn->conn_data_lock);
3173 MUTEX_EXIT(&conn->conn_call_lock);
3178 MUTEX_ENTER(&call->lock);
3179 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3181 MUTEX_EXIT(&call->lock);
3183 clock_GetTime(&now);
3185 when.sec += RX_CHECKREACH_TIMEOUT;
3186 MUTEX_ENTER(&conn->conn_data_lock);
3187 if (!conn->checkReachEvent) {
3189 conn->checkReachEvent =
3190 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3193 MUTEX_EXIT(&conn->conn_data_lock);
3199 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3201 struct rx_service *service = conn->service;
3202 struct rx_peer *peer = conn->peer;
3203 afs_uint32 now, lastReach;
3205 if (service->checkReach == 0)
3209 MUTEX_ENTER(&peer->peer_lock);
3210 lastReach = peer->lastReachTime;
3211 MUTEX_EXIT(&peer->peer_lock);
3212 if (now - lastReach < RX_CHECKREACH_TTL)
3215 MUTEX_ENTER(&conn->conn_data_lock);
3216 if (conn->flags & RX_CONN_ATTACHWAIT) {
3217 MUTEX_EXIT(&conn->conn_data_lock);
3220 conn->flags |= RX_CONN_ATTACHWAIT;
3221 MUTEX_EXIT(&conn->conn_data_lock);
3222 if (!conn->checkReachEvent)
3223 rxi_CheckReachEvent(NULL, conn, call);
3228 /* try to attach call, if authentication is complete */
3230 TryAttach(struct rx_call *acall, osi_socket socket,
3231 int *tnop, struct rx_call **newcallp,
3234 struct rx_connection *conn = acall->conn;
3236 if (conn->type == RX_SERVER_CONNECTION
3237 && acall->state == RX_STATE_PRECALL) {
3238 /* Don't attach until we have any req'd. authentication. */
3239 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3240 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3241 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3242 /* Note: this does not necessarily succeed; there
3243 * may not any proc available
3246 rxi_ChallengeOn(acall->conn);
3251 /* A data packet has been received off the interface. This packet is
3252 * appropriate to the call (the call is in the right state, etc.). This
3253 * routine can return a packet to the caller, for re-use */
3256 rxi_ReceiveDataPacket(struct rx_call *call,
3257 struct rx_packet *np, int istack,
3258 osi_socket socket, afs_uint32 host, u_short port,
3259 int *tnop, struct rx_call **newcallp)
3261 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3266 afs_uint32 serial=0, flags=0;
3268 struct rx_packet *tnp;
3269 struct clock when, now;
3270 if (rx_stats_active)
3271 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3274 /* If there are no packet buffers, drop this new packet, unless we can find
3275 * packet buffers from inactive calls */
3277 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3278 MUTEX_ENTER(&rx_freePktQ_lock);
3279 rxi_NeedMorePackets = TRUE;
3280 MUTEX_EXIT(&rx_freePktQ_lock);
3281 if (rx_stats_active)
3282 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3283 call->rprev = np->header.serial;
3284 rxi_calltrace(RX_TRACE_DROP, call);
3285 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3287 rxi_ClearReceiveQueue(call);
3288 clock_GetTime(&now);
3290 clock_Add(&when, &rx_softAckDelay);
3291 if (!call->delayedAckEvent
3292 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3293 rxevent_Cancel(call->delayedAckEvent, call,
3294 RX_CALL_REFCOUNT_DELAY);
3295 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3296 call->delayedAckEvent =
3297 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3299 /* we've damaged this call already, might as well do it in. */
3305 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3306 * packet is one of several packets transmitted as a single
3307 * datagram. Do not send any soft or hard acks until all packets
3308 * in a jumbogram have been processed. Send negative acks right away.
3310 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3311 /* tnp is non-null when there are more packets in the
3312 * current jumbo gram */
3319 seq = np->header.seq;
3320 serial = np->header.serial;
3321 flags = np->header.flags;
3323 /* If the call is in an error state, send an abort message */
3325 return rxi_SendCallAbort(call, np, istack, 0);
3327 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3328 * AFS 3.5 jumbogram. */
3329 if (flags & RX_JUMBO_PACKET) {
3330 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3335 if (np->header.spare != 0) {
3336 MUTEX_ENTER(&call->conn->conn_data_lock);
3337 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3338 MUTEX_EXIT(&call->conn->conn_data_lock);
3341 /* The usual case is that this is the expected next packet */
3342 if (seq == call->rnext) {
3344 /* Check to make sure it is not a duplicate of one already queued */
3345 if (queue_IsNotEmpty(&call->rq)
3346 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3347 if (rx_stats_active)
3348 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3349 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3350 rxevent_Cancel(call->delayedAckEvent, call,
3351 RX_CALL_REFCOUNT_DELAY);
3352 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3358 /* It's the next packet. Stick it on the receive queue
3359 * for this call. Set newPackets to make sure we wake
3360 * the reader once all packets have been processed */
3361 np->flags |= RX_PKTFLAG_RQ;
3362 queue_Prepend(&call->rq, np);
3363 #ifdef RXDEBUG_PACKET
3365 #endif /* RXDEBUG_PACKET */
3367 np = NULL; /* We can't use this anymore */
3370 /* If an ack is requested then set a flag to make sure we
3371 * send an acknowledgement for this packet */
3372 if (flags & RX_REQUEST_ACK) {
3373 ackNeeded = RX_ACK_REQUESTED;
3376 /* Keep track of whether we have received the last packet */
3377 if (flags & RX_LAST_PACKET) {
3378 call->flags |= RX_CALL_HAVE_LAST;
3382 /* Check whether we have all of the packets for this call */
3383 if (call->flags & RX_CALL_HAVE_LAST) {
3384 afs_uint32 tseq; /* temporary sequence number */
3385 struct rx_packet *tp; /* Temporary packet pointer */
3386 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3388 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3389 if (tseq != tp->header.seq)
3391 if (tp->header.flags & RX_LAST_PACKET) {
3392 call->flags |= RX_CALL_RECEIVE_DONE;
3399 /* Provide asynchronous notification for those who want it
3400 * (e.g. multi rx) */
3401 if (call->arrivalProc) {
3402 (*call->arrivalProc) (call, call->arrivalProcHandle,
3403 call->arrivalProcArg);
3404 call->arrivalProc = (void (*)())0;
3407 /* Update last packet received */
3410 /* If there is no server process serving this call, grab
3411 * one, if available. We only need to do this once. If a
3412 * server thread is available, this thread becomes a server
3413 * thread and the server thread becomes a listener thread. */
3415 TryAttach(call, socket, tnop, newcallp, 0);
3418 /* This is not the expected next packet. */
3420 /* Determine whether this is a new or old packet, and if it's
3421 * a new one, whether it fits into the current receive window.
3422 * Also figure out whether the packet was delivered in sequence.
3423 * We use the prev variable to determine whether the new packet
3424 * is the successor of its immediate predecessor in the
3425 * receive queue, and the missing flag to determine whether
3426 * any of this packets predecessors are missing. */
3428 afs_uint32 prev; /* "Previous packet" sequence number */
3429 struct rx_packet *tp; /* Temporary packet pointer */
3430 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3431 int missing; /* Are any predecessors missing? */
3433 /* If the new packet's sequence number has been sent to the
3434 * application already, then this is a duplicate */
3435 if (seq < call->rnext) {
3436 if (rx_stats_active)
3437 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3438 rxevent_Cancel(call->delayedAckEvent, call,
3439 RX_CALL_REFCOUNT_DELAY);
3440 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3446 /* If the sequence number is greater than what can be
3447 * accomodated by the current window, then send a negative
3448 * acknowledge and drop the packet */
3449 if ((call->rnext + call->rwind) <= seq) {
3450 rxevent_Cancel(call->delayedAckEvent, call,
3451 RX_CALL_REFCOUNT_DELAY);
3452 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3459 /* Look for the packet in the queue of old received packets */
3460 for (prev = call->rnext - 1, missing =
3461 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3462 /*Check for duplicate packet */
3463 if (seq == tp->header.seq) {
3464 if (rx_stats_active)
3465 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3466 rxevent_Cancel(call->delayedAckEvent, call,
3467 RX_CALL_REFCOUNT_DELAY);
3468 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3474 /* If we find a higher sequence packet, break out and
3475 * insert the new packet here. */
3476 if (seq < tp->header.seq)
3478 /* Check for missing packet */
3479 if (tp->header.seq != prev + 1) {
3483 prev = tp->header.seq;
3486 /* Keep track of whether we have received the last packet. */
3487 if (flags & RX_LAST_PACKET) {
3488 call->flags |= RX_CALL_HAVE_LAST;
3491 /* It's within the window: add it to the the receive queue.
3492 * tp is left by the previous loop either pointing at the
3493 * packet before which to insert the new packet, or at the
3494 * queue head if the queue is empty or the packet should be
3496 np->flags |= RX_PKTFLAG_RQ;
3497 #ifdef RXDEBUG_PACKET
3499 #endif /* RXDEBUG_PACKET */
3500 queue_InsertBefore(tp, np);
3504 /* Check whether we have all of the packets for this call */
3505 if ((call->flags & RX_CALL_HAVE_LAST)
3506 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3507 afs_uint32 tseq; /* temporary sequence number */
3510 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3511 if (tseq != tp->header.seq)
3513 if (tp->header.flags & RX_LAST_PACKET) {
3514 call->flags |= RX_CALL_RECEIVE_DONE;
3521 /* We need to send an ack of the packet is out of sequence,
3522 * or if an ack was requested by the peer. */
3523 if (seq != prev + 1 || missing) {
3524 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3525 } else if (flags & RX_REQUEST_ACK) {
3526 ackNeeded = RX_ACK_REQUESTED;
3529 /* Acknowledge the last packet for each call */
3530 if (flags & RX_LAST_PACKET) {
3541 * If the receiver is waiting for an iovec, fill the iovec
3542 * using the data from the receive queue */
3543 if (call->flags & RX_CALL_IOVEC_WAIT) {
3544 didHardAck = rxi_FillReadVec(call, serial);
3545 /* the call may have been aborted */
3554 /* Wakeup the reader if any */
3555 if ((call->flags & RX_CALL_READER_WAIT)
3556 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3557 || (call->iovNext >= call->iovMax)
3558 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3559 call->flags &= ~RX_CALL_READER_WAIT;
3560 #ifdef RX_ENABLE_LOCKS
3561 CV_BROADCAST(&call->cv_rq);
3563 osi_rxWakeup(&call->rq);
3569 * Send an ack when requested by the peer, or once every
3570 * rxi_SoftAckRate packets until the last packet has been
3571 * received. Always send a soft ack for the last packet in
3572 * the server's reply. */
3574 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3575 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3576 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3577 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3578 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3579 } else if (call->nSoftAcks) {
3580 clock_GetTime(&now);
3582 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3583 clock_Add(&when, &rx_lastAckDelay);
3585 clock_Add(&when, &rx_softAckDelay);
3587 if (!call->delayedAckEvent
3588 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3589 rxevent_Cancel(call->delayedAckEvent, call,
3590 RX_CALL_REFCOUNT_DELAY);
3591 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3592 call->delayedAckEvent =
3593 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3595 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3596 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3603 static void rxi_ComputeRate();
3607 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3609 struct rx_peer *peer = conn->peer;
3611 MUTEX_ENTER(&peer->peer_lock);
3612 peer->lastReachTime = clock_Sec();
3613 MUTEX_EXIT(&peer->peer_lock);
3615 MUTEX_ENTER(&conn->conn_data_lock);
3616 if (conn->flags & RX_CONN_ATTACHWAIT) {
3619 conn->flags &= ~RX_CONN_ATTACHWAIT;
3620 MUTEX_EXIT(&conn->conn_data_lock);
3622 for (i = 0; i < RX_MAXCALLS; i++) {
3623 struct rx_call *call = conn->call[i];
3626 MUTEX_ENTER(&call->lock);
3627 /* tnop can be null if newcallp is null */
3628 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3630 MUTEX_EXIT(&call->lock);
3634 MUTEX_EXIT(&conn->conn_data_lock);
3637 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3639 rx_ack_reason(int reason)
3642 case RX_ACK_REQUESTED:
3644 case RX_ACK_DUPLICATE:
3646 case RX_ACK_OUT_OF_SEQUENCE:
3648 case RX_ACK_EXCEEDS_WINDOW:
3650 case RX_ACK_NOSPACE:
3654 case RX_ACK_PING_RESPONSE:
3667 /* rxi_ComputePeerNetStats
3669 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3670 * estimates (like RTT and throughput) based on ack packets. Caller
3671 * must ensure that the packet in question is the right one (i.e.
3672 * serial number matches).
3675 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3676 struct rx_ackPacket *ap, struct rx_packet *np)
3678 struct rx_peer *peer = call->conn->peer;
3680 /* Use RTT if not delayed by client and
3681 * ignore packets that were retransmitted. */
3682 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3683 ap->reason != RX_ACK_DELAY &&
3684 clock_Eq(&p->timeSent, &p->firstSent))
3685 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3687 rxi_ComputeRate(peer, call, p, np, ap->reason);
3691 /* The real smarts of the whole thing. */
3693 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3696 struct rx_ackPacket *ap;
3698 struct rx_packet *tp;
3699 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3700 struct rx_connection *conn = call->conn;
3701 struct rx_peer *peer = conn->peer;
3704 /* because there are CM's that are bogus, sending weird values for this. */
3705 afs_uint32 skew = 0;
3711 int newAckCount = 0;
3712 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3713 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3715 if (rx_stats_active)
3716 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3717 ap = (struct rx_ackPacket *)rx_DataOf(np);
3718 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3720 return np; /* truncated ack packet */
3722 /* depends on ack packet struct */
3723 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3724 first = ntohl(ap->firstPacket);
3725 serial = ntohl(ap->serial);
3726 /* temporarily disabled -- needs to degrade over time
3727 * skew = ntohs(ap->maxSkew); */
3729 /* Ignore ack packets received out of order */
3730 if (first < call->tfirst) {
3734 if (np->header.flags & RX_SLOW_START_OK) {
3735 call->flags |= RX_CALL_SLOW_START_OK;
3738 if (ap->reason == RX_ACK_PING_RESPONSE)
3739 rxi_UpdatePeerReach(conn, call);
3743 if (rxdebug_active) {
3747 len = _snprintf(msg, sizeof(msg),
3748 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3749 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3750 ntohl(ap->serial), ntohl(ap->previousPacket),
3751 (unsigned int)np->header.seq, (unsigned int)skew,
3752 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3756 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3757 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3761 OutputDebugString(msg);
3763 #else /* AFS_NT40_ENV */
3766 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3767 ap->reason, ntohl(ap->previousPacket),
3768 (unsigned int)np->header.seq, (unsigned int)serial,
3769 (unsigned int)skew, ntohl(ap->firstPacket));
3772 for (offset = 0; offset < nAcks; offset++)
3773 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3778 #endif /* AFS_NT40_ENV */
3781 /* Update the outgoing packet skew value to the latest value of
3782 * the peer's incoming packet skew value. The ack packet, of
3783 * course, could arrive out of order, but that won't affect things
3785 MUTEX_ENTER(&peer->peer_lock);
3786 peer->outPacketSkew = skew;
3788 /* Check for packets that no longer need to be transmitted, and
3789 * discard them. This only applies to packets positively
3790 * acknowledged as having been sent to the peer's upper level.
3791 * All other packets must be retained. So only packets with
3792 * sequence numbers < ap->firstPacket are candidates. */
3793 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3794 if (tp->header.seq >= first)
3796 call->tfirst = tp->header.seq + 1;
3797 rxi_ComputePeerNetStats(call, tp, ap, np);
3798 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3801 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3802 /* XXX Hack. Because we have to release the global rx lock when sending
3803 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3804 * in rxi_Start sending packets out because packets may move to the
3805 * freePacketQueue as result of being here! So we drop these packets until
3806 * we're safely out of the traversing. Really ugly!
3807 * To make it even uglier, if we're using fine grain locking, we can
3808 * set the ack bits in the packets and have rxi_Start remove the packets
3809 * when it's done transmitting.
3811 if (call->flags & RX_CALL_TQ_BUSY) {
3812 #ifdef RX_ENABLE_LOCKS
3813 tp->flags |= RX_PKTFLAG_ACKED;
3814 call->flags |= RX_CALL_TQ_SOME_ACKED;
3815 #else /* RX_ENABLE_LOCKS */
3817 #endif /* RX_ENABLE_LOCKS */
3819 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3822 tp->flags &= ~RX_PKTFLAG_TQ;
3823 #ifdef RXDEBUG_PACKET
3825 #endif /* RXDEBUG_PACKET */
3826 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3831 /* Give rate detector a chance to respond to ping requests */
3832 if (ap->reason == RX_ACK_PING_RESPONSE) {
3833 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3837 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3839 /* Now go through explicit acks/nacks and record the results in
3840 * the waiting packets. These are packets that can't be released
3841 * yet, even with a positive acknowledge. This positive
3842 * acknowledge only means the packet has been received by the
3843 * peer, not that it will be retained long enough to be sent to
3844 * the peer's upper level. In addition, reset the transmit timers
3845 * of any missing packets (those packets that must be missing
3846 * because this packet was out of sequence) */
3848 call->nSoftAcked = 0;
3849 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3850 /* Update round trip time if the ack was stimulated on receipt
3852 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3853 #ifdef RX_ENABLE_LOCKS
3854 if (tp->header.seq >= first)
3855 #endif /* RX_ENABLE_LOCKS */
3856 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3857 rxi_ComputePeerNetStats(call, tp, ap, np);
3859 /* Set the acknowledge flag per packet based on the
3860 * information in the ack packet. An acknowlegded packet can
3861 * be downgraded when the server has discarded a packet it
3862 * soacked previously, or when an ack packet is received
3863 * out of sequence. */
3864 if (tp->header.seq < first) {
3865 /* Implicit ack information */
3866 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3869 tp->flags |= RX_PKTFLAG_ACKED;
3870 } else if (tp->header.seq < first + nAcks) {
3871 /* Explicit ack information: set it in the packet appropriately */
3872 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3873 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3875 tp->flags |= RX_PKTFLAG_ACKED;
3882 } else /* RX_ACK_TYPE_NACK */ {
3883 tp->flags &= ~RX_PKTFLAG_ACKED;
3887 tp->flags &= ~RX_PKTFLAG_ACKED;
3892 * Following the suggestion of Phil Kern, we back off the peer's
3893 * timeout value for future packets until a successful response
3894 * is received for an initial transmission.
3896 if (missing && !backedOff) {
3897 struct clock c = peer->timeout;
3898 struct clock max_to = {3, 0};
3900 clock_Add(&peer->timeout, &c);
3901 if (clock_Gt(&peer->timeout, &max_to))
3902 peer->timeout = max_to;
3906 /* If packet isn't yet acked, and it has been transmitted at least
3907 * once, reset retransmit time using latest timeout
3908 * ie, this should readjust the retransmit timer for all outstanding
3909 * packets... So we don't just retransmit when we should know better*/
3911 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3912 tp->retryTime = tp->timeSent;
3913 clock_Add(&tp->retryTime, &peer->timeout);
3914 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3915 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3919 /* If the window has been extended by this acknowledge packet,
3920 * then wakeup a sender waiting in alloc for window space, or try
3921 * sending packets now, if he's been sitting on packets due to
3922 * lack of window space */
3923 if (call->tnext < (call->tfirst + call->twind)) {
3924 #ifdef RX_ENABLE_LOCKS
3925 CV_SIGNAL(&call->cv_twind);
3927 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3928 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3929 osi_rxWakeup(&call->twind);
3932 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3933 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3937 /* if the ack packet has a receivelen field hanging off it,
3938 * update our state */
3939 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3942 /* If the ack packet has a "recommended" size that is less than
3943 * what I am using now, reduce my size to match */
3944 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
3945 (int)sizeof(afs_int32), &tSize);
3946 tSize = (afs_uint32) ntohl(tSize);
3947 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3949 /* Get the maximum packet size to send to this peer */
3950 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3952 tSize = (afs_uint32) ntohl(tSize);
3953 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3954 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3956 /* sanity check - peer might have restarted with different params.
3957 * If peer says "send less", dammit, send less... Peer should never
3958 * be unable to accept packets of the size that prior AFS versions would
3959 * send without asking. */
3960 if (peer->maxMTU != tSize) {
3961 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3963 peer->maxMTU = tSize;
3964 peer->MTU = MIN(tSize, peer->MTU);
3965 call->MTU = MIN(call->MTU, tSize);
3968 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3971 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
3972 (int)sizeof(afs_int32), &tSize);
3973 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3974 if (tSize < call->twind) { /* smaller than our send */
3975 call->twind = tSize; /* window, we must send less... */
3976 call->ssthresh = MIN(call->twind, call->ssthresh);
3977 call->conn->twind[call->channel] = call->twind;
3980 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3981 * network MTU confused with the loopback MTU. Calculate the
3982 * maximum MTU here for use in the slow start code below.
3984 maxMTU = peer->maxMTU;
3985 /* Did peer restart with older RX version? */
3986 if (peer->maxDgramPackets > 1) {
3987 peer->maxDgramPackets = 1;
3989 } else if (np->length >=
3990 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3993 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
3994 sizeof(afs_int32), &tSize);
3995 tSize = (afs_uint32) ntohl(tSize);
3997 * As of AFS 3.5 we set the send window to match the receive window.
3999 if (tSize < call->twind) {
4000 call->twind = tSize;
4001 call->conn->twind[call->channel] = call->twind;
4002 call->ssthresh = MIN(call->twind, call->ssthresh);
4003 } else if (tSize > call->twind) {
4004 call->twind = tSize;
4005 call->conn->twind[call->channel] = call->twind;
4009 * As of AFS 3.5, a jumbogram is more than one fixed size
4010 * packet transmitted in a single UDP datagram. If the remote
4011 * MTU is smaller than our local MTU then never send a datagram
4012 * larger than the natural MTU.
4015 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4016 (int)sizeof(afs_int32), &tSize);
4017 maxDgramPackets = (afs_uint32) ntohl(tSize);
4018 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4020 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4021 maxDgramPackets = MIN(maxDgramPackets, tSize);
4022 if (maxDgramPackets > 1) {
4023 peer->maxDgramPackets = maxDgramPackets;
4024 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4026 peer->maxDgramPackets = 1;
4027 call->MTU = peer->natMTU;
4029 } else if (peer->maxDgramPackets > 1) {
4030 /* Restarted with lower version of RX */
4031 peer->maxDgramPackets = 1;
4033 } else if (peer->maxDgramPackets > 1
4034 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4035 /* Restarted with lower version of RX */
4036 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4037 peer->natMTU = OLD_MAX_PACKET_SIZE;
4038 peer->MTU = OLD_MAX_PACKET_SIZE;
4039 peer->maxDgramPackets = 1;
4040 peer->nDgramPackets = 1;
4042 call->MTU = OLD_MAX_PACKET_SIZE;
4047 * Calculate how many datagrams were successfully received after
4048 * the first missing packet and adjust the negative ack counter
4053 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4054 if (call->nNacks < nNacked) {
4055 call->nNacks = nNacked;
4058 call->nAcks += newAckCount;
4062 if (call->flags & RX_CALL_FAST_RECOVER) {
4064 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4066 call->flags &= ~RX_CALL_FAST_RECOVER;
4067 call->cwind = call->nextCwind;
4068 call->nextCwind = 0;
4071 call->nCwindAcks = 0;
4072 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4073 /* Three negative acks in a row trigger congestion recovery */
4074 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4075 MUTEX_EXIT(&peer->peer_lock);
4076 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4077 /* someone else is waiting to start recovery */
4080 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4081 rxi_WaitforTQBusy(call);
4082 MUTEX_ENTER(&peer->peer_lock);
4083 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4084 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4085 call->flags |= RX_CALL_FAST_RECOVER;
4086 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4088 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4089 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4090 call->nextCwind = call->ssthresh;
4093 peer->MTU = call->MTU;
4094 peer->cwind = call->nextCwind;
4095 peer->nDgramPackets = call->nDgramPackets;
4097 call->congestSeq = peer->congestSeq;
4098 /* Reset the resend times on the packets that were nacked
4099 * so we will retransmit as soon as the window permits*/
4100 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4102 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4103 clock_Zero(&tp->retryTime);
4105 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4110 /* If cwind is smaller than ssthresh, then increase
4111 * the window one packet for each ack we receive (exponential
4113 * If cwind is greater than or equal to ssthresh then increase
4114 * the congestion window by one packet for each cwind acks we
4115 * receive (linear growth). */
4116 if (call->cwind < call->ssthresh) {
4118 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4119 call->nCwindAcks = 0;
4121 call->nCwindAcks += newAckCount;
4122 if (call->nCwindAcks >= call->cwind) {
4123 call->nCwindAcks = 0;
4124 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4128 * If we have received several acknowledgements in a row then
4129 * it is time to increase the size of our datagrams
4131 if ((int)call->nAcks > rx_nDgramThreshold) {
4132 if (peer->maxDgramPackets > 1) {
4133 if (call->nDgramPackets < peer->maxDgramPackets) {
4134 call->nDgramPackets++;
4136 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4137 } else if (call->MTU < peer->maxMTU) {
4138 call->MTU += peer->natMTU;
4139 call->MTU = MIN(call->MTU, peer->maxMTU);
4145 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4147 /* Servers need to hold the call until all response packets have
4148 * been acknowledged. Soft acks are good enough since clients
4149 * are not allowed to clear their receive queues. */
4150 if (call->state == RX_STATE_HOLD
4151 && call->tfirst + call->nSoftAcked >= call->tnext) {
4152 call->state = RX_STATE_DALLY;
4153 rxi_ClearTransmitQueue(call, 0);
4154 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4155 } else if (!queue_IsEmpty(&call->tq)) {
4156 rxi_Start(0, call, 0, istack);
4161 /* Received a response to a challenge packet */
4163 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4164 struct rx_packet *np, int istack)
4168 /* Ignore the packet if we're the client */
4169 if (conn->type == RX_CLIENT_CONNECTION)
4172 /* If already authenticated, ignore the packet (it's probably a retry) */
4173 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4176 /* Otherwise, have the security object evaluate the response packet */
4177 error = RXS_CheckResponse(conn->securityObject, conn, np);
4179 /* If the response is invalid, reset the connection, sending
4180 * an abort to the peer */
4184 rxi_ConnectionError(conn, error);
4185 MUTEX_ENTER(&conn->conn_data_lock);
4186 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4187 MUTEX_EXIT(&conn->conn_data_lock);
4190 /* If the response is valid, any calls waiting to attach
4191 * servers can now do so */
4194 for (i = 0; i < RX_MAXCALLS; i++) {
4195 struct rx_call *call = conn->call[i];
4197 MUTEX_ENTER(&call->lock);
4198 if (call->state == RX_STATE_PRECALL)
4199 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4200 /* tnop can be null if newcallp is null */
4201 MUTEX_EXIT(&call->lock);
4205 /* Update the peer reachability information, just in case
4206 * some calls went into attach-wait while we were waiting
4207 * for authentication..
4209 rxi_UpdatePeerReach(conn, NULL);
4214 /* A client has received an authentication challenge: the security
4215 * object is asked to cough up a respectable response packet to send
4216 * back to the server. The server is responsible for retrying the
4217 * challenge if it fails to get a response. */
4220 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4221 struct rx_packet *np, int istack)
4225 /* Ignore the challenge if we're the server */
4226 if (conn->type == RX_SERVER_CONNECTION)
4229 /* Ignore the challenge if the connection is otherwise idle; someone's
4230 * trying to use us as an oracle. */
4231 if (!rxi_HasActiveCalls(conn))
4234 /* Send the security object the challenge packet. It is expected to fill
4235 * in the response. */
4236 error = RXS_GetResponse(conn->securityObject, conn, np);
4238 /* If the security object is unable to return a valid response, reset the
4239 * connection and send an abort to the peer. Otherwise send the response
4240 * packet to the peer connection. */
4242 rxi_ConnectionError(conn, error);
4243 MUTEX_ENTER(&conn->conn_data_lock);
4244 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4245 MUTEX_EXIT(&conn->conn_data_lock);
4247 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4248 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4254 /* Find an available server process to service the current request in
4255 * the given call structure. If one isn't available, queue up this
4256 * call so it eventually gets one */
4258 rxi_AttachServerProc(struct rx_call *call,
4259 osi_socket socket, int *tnop,
4260 struct rx_call **newcallp)
4262 struct rx_serverQueueEntry *sq;
4263 struct rx_service *service = call->conn->service;
4266 /* May already be attached */
4267 if (call->state == RX_STATE_ACTIVE)
4270 MUTEX_ENTER(&rx_serverPool_lock);
4272 haveQuota = QuotaOK(service);
4273 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4274 /* If there are no processes available to service this call,
4275 * put the call on the incoming call queue (unless it's
4276 * already on the queue).
4278 #ifdef RX_ENABLE_LOCKS
4280 ReturnToServerPool(service);
4281 #endif /* RX_ENABLE_LOCKS */
4283 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4284 call->flags |= RX_CALL_WAIT_PROC;
4285 MUTEX_ENTER(&rx_waiting_mutex);
4288 MUTEX_EXIT(&rx_waiting_mutex);
4289 rxi_calltrace(RX_CALL_ARRIVAL, call);
4290 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4291 queue_Append(&rx_incomingCallQueue, call);
4294 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4296 /* If hot threads are enabled, and both newcallp and sq->socketp
4297 * are non-null, then this thread will process the call, and the
4298 * idle server thread will start listening on this threads socket.
4301 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4304 *sq->socketp = socket;
4305 clock_GetTime(&call->startTime);
4306 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4310 if (call->flags & RX_CALL_WAIT_PROC) {
4311 /* Conservative: I don't think this should happen */
4312 call->flags &= ~RX_CALL_WAIT_PROC;
4313 if (queue_IsOnQueue(call)) {
4316 MUTEX_ENTER(&rx_waiting_mutex);
4318 MUTEX_EXIT(&rx_waiting_mutex);
4321 call->state = RX_STATE_ACTIVE;
4322 call->mode = RX_MODE_RECEIVING;
4323 #ifdef RX_KERNEL_TRACE
4325 int glockOwner = ISAFS_GLOCK();
4328 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4329 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4335 if (call->flags & RX_CALL_CLEARED) {
4336 /* send an ack now to start the packet flow up again */
4337 call->flags &= ~RX_CALL_CLEARED;
4338 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4340 #ifdef RX_ENABLE_LOCKS
4343 service->nRequestsRunning++;
4344 if (service->nRequestsRunning <= service->minProcs)
4350 MUTEX_EXIT(&rx_serverPool_lock);
4353 /* Delay the sending of an acknowledge event for a short while, while
4354 * a new call is being prepared (in the case of a client) or a reply
4355 * is being prepared (in the case of a server). Rather than sending
4356 * an ack packet, an ACKALL packet is sent. */
4358 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4360 #ifdef RX_ENABLE_LOCKS
4362 MUTEX_ENTER(&call->lock);
4363 call->delayedAckEvent = NULL;
4364 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4366 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4367 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4369 MUTEX_EXIT(&call->lock);
4370 #else /* RX_ENABLE_LOCKS */
4372 call->delayedAckEvent = NULL;
4373 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4374 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4375 #endif /* RX_ENABLE_LOCKS */
4379 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4381 struct rx_call *call = arg1;
4382 #ifdef RX_ENABLE_LOCKS
4384 MUTEX_ENTER(&call->lock);
4385 if (event == call->delayedAckEvent)
4386 call->delayedAckEvent = NULL;
4387 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4389 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4391 MUTEX_EXIT(&call->lock);
4392 #else /* RX_ENABLE_LOCKS */
4394 call->delayedAckEvent = NULL;
4395 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4396 #endif /* RX_ENABLE_LOCKS */
4400 #ifdef RX_ENABLE_LOCKS
4401 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4402 * clearing them out.
4405 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4407 struct rx_packet *p, *tp;
4410 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4411 p->flags |= RX_PKTFLAG_ACKED;
4415 call->flags |= RX_CALL_TQ_CLEARME;
4416 call->flags |= RX_CALL_TQ_SOME_ACKED;
4419 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4420 call->tfirst = call->tnext;
4421 call->nSoftAcked = 0;
4423 if (call->flags & RX_CALL_FAST_RECOVER) {
4424 call->flags &= ~RX_CALL_FAST_RECOVER;
4425 call->cwind = call->nextCwind;
4426 call->nextCwind = 0;
4429 CV_SIGNAL(&call->cv_twind);
4431 #endif /* RX_ENABLE_LOCKS */
4433 /* Clear out the transmit queue for the current call (all packets have
4434 * been received by peer) */
4436 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4438 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4439 struct rx_packet *p, *tp;
4441 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4443 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4444 p->flags |= RX_PKTFLAG_ACKED;
4448 call->flags |= RX_CALL_TQ_CLEARME;
4449 call->flags |= RX_CALL_TQ_SOME_ACKED;
4452 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4453 #ifdef RXDEBUG_PACKET
4455 #endif /* RXDEBUG_PACKET */
4456 rxi_FreePackets(0, &call->tq);
4457 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4458 call->flags &= ~RX_CALL_TQ_CLEARME;
4460 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4462 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4463 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4464 call->nSoftAcked = 0;
4466 if (call->flags & RX_CALL_FAST_RECOVER) {
4467 call->flags &= ~RX_CALL_FAST_RECOVER;
4468 call->cwind = call->nextCwind;
4470 #ifdef RX_ENABLE_LOCKS
4471 CV_SIGNAL(&call->cv_twind);
4473 osi_rxWakeup(&call->twind);
4478 rxi_ClearReceiveQueue(struct rx_call *call)
4480 if (queue_IsNotEmpty(&call->rq)) {
4483 count = rxi_FreePackets(0, &call->rq);
4484 rx_packetReclaims += count;
4485 #ifdef RXDEBUG_PACKET
4487 if ( call->rqc != 0 )
4488 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0", call, call->rqc));
4490 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4492 if (call->state == RX_STATE_PRECALL) {
4493 call->flags |= RX_CALL_CLEARED;
4497 /* Send an abort packet for the specified call */
4499 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4500 int istack, int force)
4503 struct clock when, now;
4508 /* Clients should never delay abort messages */
4509 if (rx_IsClientConn(call->conn))
4512 if (call->abortCode != call->error) {
4513 call->abortCode = call->error;
4514 call->abortCount = 0;
4517 if (force || rxi_callAbortThreshhold == 0
4518 || call->abortCount < rxi_callAbortThreshhold) {
4519 if (call->delayedAbortEvent) {
4520 rxevent_Cancel(call->delayedAbortEvent, call,
4521 RX_CALL_REFCOUNT_ABORT);
4523 error = htonl(call->error);
4526 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4527 (char *)&error, sizeof(error), istack);
4528 } else if (!call->delayedAbortEvent) {
4529 clock_GetTime(&now);
4531 clock_Addmsec(&when, rxi_callAbortDelay);
4532 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4533 call->delayedAbortEvent =
4534 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4539 /* Send an abort packet for the specified connection. Packet is an
4540 * optional pointer to a packet that can be used to send the abort.
4541 * Once the number of abort messages reaches the threshhold, an
4542 * event is scheduled to send the abort. Setting the force flag
4543 * overrides sending delayed abort messages.
4545 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4546 * to send the abort packet.
4549 rxi_SendConnectionAbort(struct rx_connection *conn,
4550 struct rx_packet *packet, int istack, int force)
4553 struct clock when, now;
4558 /* Clients should never delay abort messages */
4559 if (rx_IsClientConn(conn))
4562 if (force || rxi_connAbortThreshhold == 0
4563 || conn->abortCount < rxi_connAbortThreshhold) {
4564 if (conn->delayedAbortEvent) {
4565 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4567 error = htonl(conn->error);
4569 MUTEX_EXIT(&conn->conn_data_lock);
4571 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4572 RX_PACKET_TYPE_ABORT, (char *)&error,
4573 sizeof(error), istack);
4574 MUTEX_ENTER(&conn->conn_data_lock);
4575 } else if (!conn->delayedAbortEvent) {
4576 clock_GetTime(&now);
4578 clock_Addmsec(&when, rxi_connAbortDelay);
4579 conn->delayedAbortEvent =
4580 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4585 /* Associate an error all of the calls owned by a connection. Called
4586 * with error non-zero. This is only for really fatal things, like
4587 * bad authentication responses. The connection itself is set in
4588 * error at this point, so that future packets received will be
4591 rxi_ConnectionError(struct rx_connection *conn,
4597 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d", conn, error));
4599 MUTEX_ENTER(&conn->conn_data_lock);
4600 if (conn->challengeEvent)
4601 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4602 if (conn->checkReachEvent) {
4603 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4604 conn->checkReachEvent = 0;
4605 conn->flags &= ~RX_CONN_ATTACHWAIT;
4608 MUTEX_EXIT(&conn->conn_data_lock);
4609 for (i = 0; i < RX_MAXCALLS; i++) {
4610 struct rx_call *call = conn->call[i];
4612 MUTEX_ENTER(&call->lock);
4613 rxi_CallError(call, error);
4614 MUTEX_EXIT(&call->lock);
4617 conn->error = error;
4618 if (rx_stats_active)
4619 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4624 rxi_CallError(struct rx_call *call, afs_int32 error)
4627 osirx_AssertMine(&call->lock, "rxi_CallError");
4629 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d", call, error, call->error));
4631 error = call->error;
4633 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4634 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4635 rxi_ResetCall(call, 0);
4638 rxi_ResetCall(call, 0);
4640 call->error = error;
4641 call->mode = RX_MODE_ERROR;
4644 /* Reset various fields in a call structure, and wakeup waiting
4645 * processes. Some fields aren't changed: state & mode are not
4646 * touched (these must be set by the caller), and bufptr, nLeft, and
4647 * nFree are not reset, since these fields are manipulated by
4648 * unprotected macros, and may only be reset by non-interrupting code.
4651 /* this code requires that call->conn be set properly as a pre-condition. */
4652 #endif /* ADAPT_WINDOW */
4655 rxi_ResetCall(struct rx_call *call, int newcall)
4658 struct rx_peer *peer;
4659 struct rx_packet *packet;
4661 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4663 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
4665 /* Notify anyone who is waiting for asynchronous packet arrival */
4666 if (call->arrivalProc) {
4667 (*call->arrivalProc) (call, call->arrivalProcHandle,
4668 call->arrivalProcArg);
4669 call->arrivalProc = (void (*)())0;
4672 if (call->delayedAbortEvent) {
4673 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4674 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4676 rxi_SendCallAbort(call, packet, 0, 1);
4677 rxi_FreePacket(packet);
4682 * Update the peer with the congestion information in this call
4683 * so other calls on this connection can pick up where this call
4684 * left off. If the congestion sequence numbers don't match then
4685 * another call experienced a retransmission.
4687 peer = call->conn->peer;
4688 MUTEX_ENTER(&peer->peer_lock);
4690 if (call->congestSeq == peer->congestSeq) {
4691 peer->cwind = MAX(peer->cwind, call->cwind);
4692 peer->MTU = MAX(peer->MTU, call->MTU);
4693 peer->nDgramPackets =
4694 MAX(peer->nDgramPackets, call->nDgramPackets);
4697 call->abortCode = 0;
4698 call->abortCount = 0;
4700 if (peer->maxDgramPackets > 1) {
4701 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4703 call->MTU = peer->MTU;
4705 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4706 call->ssthresh = rx_maxSendWindow;
4707 call->nDgramPackets = peer->nDgramPackets;
4708 call->congestSeq = peer->congestSeq;
4709 MUTEX_EXIT(&peer->peer_lock);
4711 flags = call->flags;
4712 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4713 if (flags & RX_CALL_TQ_BUSY) {
4714 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4715 call->flags |= (flags & RX_CALL_TQ_WAIT);
4716 #ifdef RX_ENABLE_LOCKS
4717 CV_WAIT(&call->cv_tq, &call->lock);
4718 #else /* RX_ENABLE_LOCKS */
4719 osi_rxSleep(&call->tq);
4720 #endif /* RX_ENABLE_LOCKS */
4722 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4724 rxi_ClearTransmitQueue(call, 1);
4725 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4726 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4727 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4730 while (call->tqWaiters) {
4731 #ifdef RX_ENABLE_LOCKS
4732 CV_BROADCAST(&call->cv_tq);
4733 #else /* RX_ENABLE_LOCKS */
4734 osi_rxWakeup(&call->tq);
4735 #endif /* RX_ENABLE_LOCKS */
4740 rxi_ClearReceiveQueue(call);
4741 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4743 if (call->currentPacket) {
4744 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4745 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4746 queue_Prepend(&call->iovq, call->currentPacket);
4747 #ifdef RXDEBUG_PACKET
4749 #endif /* RXDEBUG_PACKET */
4750 call->currentPacket = (struct rx_packet *)0;
4752 call->curlen = call->nLeft = call->nFree = 0;
4754 #ifdef RXDEBUG_PACKET
4757 rxi_FreePackets(0, &call->iovq);
4760 call->twind = call->conn->twind[call->channel];
4761 call->rwind = call->conn->rwind[call->channel];
4762 call->nSoftAcked = 0;
4763 call->nextCwind = 0;
4766 call->nCwindAcks = 0;
4767 call->nSoftAcks = 0;
4768 call->nHardAcks = 0;
4770 call->tfirst = call->rnext = call->tnext = 1;
4772 call->lastAcked = 0;
4773 call->localStatus = call->remoteStatus = 0;
4775 if (flags & RX_CALL_READER_WAIT) {
4776 #ifdef RX_ENABLE_LOCKS
4777 CV_BROADCAST(&call->cv_rq);
4779 osi_rxWakeup(&call->rq);
4782 if (flags & RX_CALL_WAIT_PACKETS) {
4783 MUTEX_ENTER(&rx_freePktQ_lock);
4784 rxi_PacketsUnWait(); /* XXX */
4785 MUTEX_EXIT(&rx_freePktQ_lock);
4787 #ifdef RX_ENABLE_LOCKS
4788 CV_SIGNAL(&call->cv_twind);
4790 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4791 osi_rxWakeup(&call->twind);
4794 #ifdef RX_ENABLE_LOCKS
4795 /* The following ensures that we don't mess with any queue while some
4796 * other thread might also be doing so. The call_queue_lock field is
4797 * is only modified under the call lock. If the call is in the process
4798 * of being removed from a queue, the call is not locked until the
4799 * the queue lock is dropped and only then is the call_queue_lock field
4800 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4801 * Note that any other routine which removes a call from a queue has to
4802 * obtain the queue lock before examing the queue and removing the call.
4804 if (call->call_queue_lock) {
4805 MUTEX_ENTER(call->call_queue_lock);
4806 if (queue_IsOnQueue(call)) {
4808 if (flags & RX_CALL_WAIT_PROC) {
4810 MUTEX_ENTER(&rx_waiting_mutex);
4812 MUTEX_EXIT(&rx_waiting_mutex);
4815 MUTEX_EXIT(call->call_queue_lock);
4816 CLEAR_CALL_QUEUE_LOCK(call);
4818 #else /* RX_ENABLE_LOCKS */
4819 if (queue_IsOnQueue(call)) {
4821 if (flags & RX_CALL_WAIT_PROC)
4824 #endif /* RX_ENABLE_LOCKS */
4826 rxi_KeepAliveOff(call);
4827 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4830 /* Send an acknowledge for the indicated packet (seq,serial) of the
4831 * indicated call, for the indicated reason (reason). This
4832 * acknowledge will specifically acknowledge receiving the packet, and
4833 * will also specify which other packets for this call have been
4834 * received. This routine returns the packet that was used to the
4835 * caller. The caller is responsible for freeing it or re-using it.
4836 * This acknowledgement also returns the highest sequence number
4837 * actually read out by the higher level to the sender; the sender
4838 * promises to keep around packets that have not been read by the
4839 * higher level yet (unless, of course, the sender decides to abort
4840 * the call altogether). Any of p, seq, serial, pflags, or reason may
4841 * be set to zero without ill effect. That is, if they are zero, they
4842 * will not convey any information.
4843 * NOW there is a trailer field, after the ack where it will safely be
4844 * ignored by mundanes, which indicates the maximum size packet this
4845 * host can swallow. */
4847 struct rx_packet *optionalPacket; use to send ack (or null)
4848 int seq; Sequence number of the packet we are acking
4849 int serial; Serial number of the packet
4850 int pflags; Flags field from packet header
4851 int reason; Reason an acknowledge was prompted
4855 rxi_SendAck(struct rx_call *call,
4856 struct rx_packet *optionalPacket, int serial, int reason,
4859 struct rx_ackPacket *ap;
4860 struct rx_packet *rqp;
4861 struct rx_packet *nxp; /* For queue_Scan */
4862 struct rx_packet *p;
4865 #ifdef RX_ENABLE_TSFPQ
4866 struct rx_ts_info_t * rx_ts_info;
4870 * Open the receive window once a thread starts reading packets
4872 if (call->rnext > 1) {
4873 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4876 call->nHardAcks = 0;
4877 call->nSoftAcks = 0;
4878 if (call->rnext > call->lastAcked)
4879 call->lastAcked = call->rnext;
4883 rx_computelen(p, p->length); /* reset length, you never know */
4884 } /* where that's been... */
4885 #ifdef RX_ENABLE_TSFPQ
4887 RX_TS_INFO_GET(rx_ts_info);
4888 if ((p = rx_ts_info->local_special_packet)) {
4889 rx_computelen(p, p->length);
4890 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4891 rx_ts_info->local_special_packet = p;
4892 } else { /* We won't send the ack, but don't panic. */
4893 return optionalPacket;
4897 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4898 /* We won't send the ack, but don't panic. */
4899 return optionalPacket;
4904 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4907 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4908 #ifndef RX_ENABLE_TSFPQ
4909 if (!optionalPacket)
4912 return optionalPacket;
4914 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4915 if (rx_Contiguous(p) < templ) {
4916 #ifndef RX_ENABLE_TSFPQ
4917 if (!optionalPacket)
4920 return optionalPacket;
4925 /* MTUXXX failing to send an ack is very serious. We should */
4926 /* try as hard as possible to send even a partial ack; it's */
4927 /* better than nothing. */
4928 ap = (struct rx_ackPacket *)rx_DataOf(p);
4929 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4930 ap->reason = reason;
4932 /* The skew computation used to be bogus, I think it's better now. */
4933 /* We should start paying attention to skew. XXX */
4934 ap->serial = htonl(serial);
4935 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4937 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4938 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4940 /* No fear of running out of ack packet here because there can only be at most
4941 * one window full of unacknowledged packets. The window size must be constrained
4942 * to be less than the maximum ack size, of course. Also, an ack should always
4943 * fit into a single packet -- it should not ever be fragmented. */
4944 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4945 if (!rqp || !call->rq.next
4946 || (rqp->header.seq > (call->rnext + call->rwind))) {
4947 #ifndef RX_ENABLE_TSFPQ
4948 if (!optionalPacket)
4951 rxi_CallError(call, RX_CALL_DEAD);
4952 return optionalPacket;
4955 while (rqp->header.seq > call->rnext + offset)
4956 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4957 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4959 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4960 #ifndef RX_ENABLE_TSFPQ
4961 if (!optionalPacket)
4964 rxi_CallError(call, RX_CALL_DEAD);
4965 return optionalPacket;
4970 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4972 /* these are new for AFS 3.3 */
4973 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4974 templ = htonl(templ);
4975 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4976 templ = htonl(call->conn->peer->ifMTU);
4977 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4978 sizeof(afs_int32), &templ);
4980 /* new for AFS 3.4 */
4981 templ = htonl(call->rwind);
4982 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4983 sizeof(afs_int32), &templ);
4985 /* new for AFS 3.5 */
4986 templ = htonl(call->conn->peer->ifDgramPackets);
4987 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4988 sizeof(afs_int32), &templ);
4990 p->header.serviceId = call->conn->serviceId;
4991 p->header.cid = (call->conn->cid | call->channel);
4992 p->header.callNumber = *call->callNumber;
4994 p->header.securityIndex = call->conn->securityIndex;
4995 p->header.epoch = call->conn->epoch;
4996 p->header.type = RX_PACKET_TYPE_ACK;
4997 p->header.flags = RX_SLOW_START_OK;
4998 if (reason == RX_ACK_PING) {
4999 p->header.flags |= RX_REQUEST_ACK;
5001 clock_GetTime(&call->pingRequestTime);
5004 if (call->conn->type == RX_CLIENT_CONNECTION)
5005 p->header.flags |= RX_CLIENT_INITIATED;
5009 if (rxdebug_active) {
5013 len = _snprintf(msg, sizeof(msg),
5014 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5015 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5016 ntohl(ap->serial), ntohl(ap->previousPacket),
5017 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5018 ap->nAcks, ntohs(ap->bufferSpace) );
5022 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5023 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5027 OutputDebugString(msg);
5029 #else /* AFS_NT40_ENV */
5031 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5032 ap->reason, ntohl(ap->previousPacket),
5033 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5035 for (offset = 0; offset < ap->nAcks; offset++)
5036 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5041 #endif /* AFS_NT40_ENV */
5044 int i, nbytes = p->length;
5046 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5047 if (nbytes <= p->wirevec[i].iov_len) {
5050 savelen = p->wirevec[i].iov_len;
5052 p->wirevec[i].iov_len = nbytes;
5054 rxi_Send(call, p, istack);
5055 p->wirevec[i].iov_len = savelen;
5059 nbytes -= p->wirevec[i].iov_len;
5062 if (rx_stats_active)
5063 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5064 #ifndef RX_ENABLE_TSFPQ
5065 if (!optionalPacket)
5068 return optionalPacket; /* Return packet for re-use by caller */
5071 /* Send all of the packets in the list in single datagram */
5073 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5074 int istack, int moreFlag, struct clock *now,
5075 struct clock *retryTime, int resending)
5080 struct rx_connection *conn = call->conn;
5081 struct rx_peer *peer = conn->peer;
5083 MUTEX_ENTER(&peer->peer_lock);
5086 peer->reSends += len;
5087 if (rx_stats_active)
5088 rx_MutexAdd(rx_stats.dataPacketsSent, len, rx_stats_mutex);
5089 MUTEX_EXIT(&peer->peer_lock);
5091 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5095 /* Set the packet flags and schedule the resend events */
5096 /* Only request an ack for the last packet in the list */
5097 for (i = 0; i < len; i++) {
5098 list[i]->retryTime = *retryTime;
5099 if (list[i]->header.serial) {
5100 /* Exponentially backoff retry times */
5101 if (list[i]->backoff < MAXBACKOFF) {
5102 /* so it can't stay == 0 */
5103 list[i]->backoff = (list[i]->backoff << 1) + 1;
5106 clock_Addmsec(&(list[i]->retryTime),
5107 ((afs_uint32) list[i]->backoff) << 8);
5110 /* Wait a little extra for the ack on the last packet */
5111 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5112 clock_Addmsec(&(list[i]->retryTime), 400);
5115 /* Record the time sent */
5116 list[i]->timeSent = *now;
5118 /* Ask for an ack on retransmitted packets, on every other packet
5119 * if the peer doesn't support slow start. Ask for an ack on every
5120 * packet until the congestion window reaches the ack rate. */
5121 if (list[i]->header.serial) {
5123 if (rx_stats_active)
5124 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5126 /* improved RTO calculation- not Karn */
5127 list[i]->firstSent = *now;
5128 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5129 || (!(call->flags & RX_CALL_SLOW_START_OK)
5130 && (list[i]->header.seq & 1)))) {
5135 /* Tag this packet as not being the last in this group,
5136 * for the receiver's benefit */
5137 if (i < len - 1 || moreFlag) {
5138 list[i]->header.flags |= RX_MORE_PACKETS;
5141 /* Install the new retransmit time for the packet, and
5142 * record the time sent */
5143 list[i]->timeSent = *now;
5147 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5150 /* Since we're about to send a data packet to the peer, it's
5151 * safe to nuke any scheduled end-of-packets ack */
5152 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5154 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5155 MUTEX_EXIT(&call->lock);
5157 rxi_SendPacketList(call, conn, list, len, istack);
5159 rxi_SendPacket(call, conn, list[0], istack);
5161 MUTEX_ENTER(&call->lock);
5162 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5164 /* Update last send time for this call (for keep-alive
5165 * processing), and for the connection (so that we can discover
5166 * idle connections) */
5167 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5170 /* When sending packets we need to follow these rules:
5171 * 1. Never send more than maxDgramPackets in a jumbogram.
5172 * 2. Never send a packet with more than two iovecs in a jumbogram.
5173 * 3. Never send a retransmitted packet in a jumbogram.
5174 * 4. Never send more than cwind/4 packets in a jumbogram
5175 * We always keep the last list we should have sent so we
5176 * can set the RX_MORE_PACKETS flags correctly.
5179 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5180 int istack, struct clock *now, struct clock *retryTime,
5183 int i, cnt, lastCnt = 0;
5184 struct rx_packet **listP, **lastP = 0;
5185 struct rx_peer *peer = call->conn->peer;
5186 int morePackets = 0;
5188 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5189 /* Does the current packet force us to flush the current list? */
5191 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5192 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5194 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5196 /* If the call enters an error state stop sending, or if
5197 * we entered congestion recovery mode, stop sending */
5198 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5206 /* Add the current packet to the list if it hasn't been acked.
5207 * Otherwise adjust the list pointer to skip the current packet. */
5208 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5210 /* Do we need to flush the list? */
5211 if (cnt >= (int)peer->maxDgramPackets
5212 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5213 || list[i]->header.serial
5214 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5216 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5217 retryTime, resending);
5218 /* If the call enters an error state stop sending, or if
5219 * we entered congestion recovery mode, stop sending */
5221 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5226 listP = &list[i + 1];
5231 osi_Panic("rxi_SendList error");
5233 listP = &list[i + 1];
5237 /* Send the whole list when the call is in receive mode, when
5238 * the call is in eof mode, when we are in fast recovery mode,
5239 * and when we have the last packet */
5240 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5241 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5242 || (call->flags & RX_CALL_FAST_RECOVER)) {
5243 /* Check for the case where the current list contains
5244 * an acked packet. Since we always send retransmissions
5245 * in a separate packet, we only need to check the first
5246 * packet in the list */
5247 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5251 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5252 retryTime, resending);
5253 /* If the call enters an error state stop sending, or if
5254 * we entered congestion recovery mode, stop sending */
5255 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5259 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5262 } else if (lastCnt > 0) {
5263 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5268 #ifdef RX_ENABLE_LOCKS
5269 /* Call rxi_Start, below, but with the call lock held. */
5271 rxi_StartUnlocked(struct rxevent *event,
5272 void *arg0, void *arg1, int istack)
5274 struct rx_call *call = arg0;
5276 MUTEX_ENTER(&call->lock);
5277 rxi_Start(event, call, arg1, istack);
5278 MUTEX_EXIT(&call->lock);
5280 #endif /* RX_ENABLE_LOCKS */
5282 /* This routine is called when new packets are readied for
5283 * transmission and when retransmission may be necessary, or when the
5284 * transmission window or burst count are favourable. This should be
5285 * better optimized for new packets, the usual case, now that we've
5286 * got rid of queues of send packets. XXXXXXXXXXX */
5288 rxi_Start(struct rxevent *event,
5289 void *arg0, void *arg1, int istack)
5291 struct rx_call *call = arg0;
5293 struct rx_packet *p;
5294 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5295 struct rx_peer *peer = call->conn->peer;
5296 struct clock now, usenow, retryTime;
5300 struct rx_packet **xmitList;
5303 /* If rxi_Start is being called as a result of a resend event,
5304 * then make sure that the event pointer is removed from the call
5305 * structure, since there is no longer a per-call retransmission
5307 if (event && event == call->resendEvent) {
5308 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5309 call->resendEvent = NULL;
5311 if (queue_IsEmpty(&call->tq)) {
5315 /* Timeouts trigger congestion recovery */
5316 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5317 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5318 /* someone else is waiting to start recovery */
5321 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5322 rxi_WaitforTQBusy(call);
5323 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5324 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5325 call->flags |= RX_CALL_FAST_RECOVER;
5326 if (peer->maxDgramPackets > 1) {
5327 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5329 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5331 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5332 call->nDgramPackets = 1;
5334 call->nextCwind = 1;
5337 MUTEX_ENTER(&peer->peer_lock);
5338 peer->MTU = call->MTU;
5339 peer->cwind = call->cwind;
5340 peer->nDgramPackets = 1;
5342 call->congestSeq = peer->congestSeq;
5343 MUTEX_EXIT(&peer->peer_lock);
5344 /* Clear retry times on packets. Otherwise, it's possible for
5345 * some packets in the queue to force resends at rates faster
5346 * than recovery rates.
5348 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5349 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5350 clock_Zero(&p->retryTime);
5355 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5356 if (rx_stats_active)
5357 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5362 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5363 /* Get clock to compute the re-transmit time for any packets
5364 * in this burst. Note, if we back off, it's reasonable to
5365 * back off all of the packets in the same manner, even if
5366 * some of them have been retransmitted more times than more
5368 * Do a dance to avoid blocking after setting now. */
5369 MUTEX_ENTER(&peer->peer_lock);
5370 retryTime = peer->timeout;
5371 MUTEX_EXIT(&peer->peer_lock);
5372 clock_GetTime(&now);
5373 clock_Add(&retryTime, &now);
5375 /* Send (or resend) any packets that need it, subject to
5376 * window restrictions and congestion burst control
5377 * restrictions. Ask for an ack on the last packet sent in
5378 * this burst. For now, we're relying upon the window being
5379 * considerably bigger than the largest number of packets that
5380 * are typically sent at once by one initial call to
5381 * rxi_Start. This is probably bogus (perhaps we should ask
5382 * for an ack when we're half way through the current
5383 * window?). Also, for non file transfer applications, this
5384 * may end up asking for an ack for every packet. Bogus. XXXX
5387 * But check whether we're here recursively, and let the other guy
5390 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5391 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5392 call->flags |= RX_CALL_TQ_BUSY;
5394 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5396 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5397 call->flags &= ~RX_CALL_NEED_START;
5398 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5400 maxXmitPackets = MIN(call->twind, call->cwind);
5401 xmitList = (struct rx_packet **)
5402 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5403 /* XXXX else we must drop any mtx we hold */
5404 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5406 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5408 if (xmitList == NULL)
5409 osi_Panic("rxi_Start, failed to allocate xmit list");
5410 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5411 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5412 /* We shouldn't be sending packets if a thread is waiting
5413 * to initiate congestion recovery */
5414 dpf(("call %d waiting to initiate fast recovery\n",
5415 *(call->callNumber)));
5419 && (call->flags & RX_CALL_FAST_RECOVER)) {
5420 /* Only send one packet during fast recovery */
5421 dpf(("call %d restricted to one packet per send during fast recovery\n",
5422 *(call->callNumber)));
5425 if ((p->flags & RX_PKTFLAG_FREE)
5426 || (!queue_IsEnd(&call->tq, nxp)
5427 && (nxp->flags & RX_PKTFLAG_FREE))
5428 || (p == (struct rx_packet *)&rx_freePacketQueue)
5429 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5430 osi_Panic("rxi_Start: xmit queue clobbered");
5432 if (p->flags & RX_PKTFLAG_ACKED) {
5433 /* Since we may block, don't trust this */
5434 usenow.sec = usenow.usec = 0;
5435 if (rx_stats_active)
5436 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5437 continue; /* Ignore this packet if it has been acknowledged */
5440 /* Turn off all flags except these ones, which are the same
5441 * on each transmission */
5442 p->header.flags &= RX_PRESET_FLAGS;
5444 if (p->header.seq >=
5445 call->tfirst + MIN((int)call->twind,
5446 (int)(call->nSoftAcked +
5448 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5449 /* Note: if we're waiting for more window space, we can
5450 * still send retransmits; hence we don't return here, but
5451 * break out to schedule a retransmit event */
5452 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5453 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5458 /* Transmit the packet if it needs to be sent. */
5459 if (!clock_Lt(&now, &p->retryTime)) {
5460 if (nXmitPackets == maxXmitPackets) {
5461 rxi_SendXmitList(call, xmitList, nXmitPackets,
5462 istack, &now, &retryTime,
5464 osi_Free(xmitList, maxXmitPackets *
5465 sizeof(struct rx_packet *));
5468 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u nextRetry %u.%06u\n",
5469 *(call->callNumber), p,
5471 p->retryTime.sec, p->retryTime.usec,
5472 retryTime.sec, retryTime.usec));
5473 xmitList[nXmitPackets++] = p;
5477 /* xmitList now hold pointers to all of the packets that are
5478 * ready to send. Now we loop to send the packets */
5479 if (nXmitPackets > 0) {
5480 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5481 &now, &retryTime, resending);
5484 maxXmitPackets * sizeof(struct rx_packet *));
5486 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5488 * TQ references no longer protected by this flag; they must remain
5489 * protected by the global lock.
5491 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5492 call->flags &= ~RX_CALL_TQ_BUSY;
5493 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5494 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5495 call, call->tqWaiters, call->flags));
5496 #ifdef RX_ENABLE_LOCKS
5497 osirx_AssertMine(&call->lock, "rxi_Start start");
5498 CV_BROADCAST(&call->cv_tq);
5499 #else /* RX_ENABLE_LOCKS */
5500 osi_rxWakeup(&call->tq);
5501 #endif /* RX_ENABLE_LOCKS */
5506 /* We went into the error state while sending packets. Now is
5507 * the time to reset the call. This will also inform the using
5508 * process that the call is in an error state.
5510 if (rx_stats_active)
5511 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5512 call->flags &= ~RX_CALL_TQ_BUSY;
5513 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5514 dpf(("call error %d while xmit %p has %d waiters and flags %d\n",
5515 call->error, call, call->tqWaiters, call->flags));
5516 #ifdef RX_ENABLE_LOCKS
5517 osirx_AssertMine(&call->lock, "rxi_Start middle");
5518 CV_BROADCAST(&call->cv_tq);
5519 #else /* RX_ENABLE_LOCKS */
5520 osi_rxWakeup(&call->tq);
5521 #endif /* RX_ENABLE_LOCKS */
5523 rxi_CallError(call, call->error);
5526 #ifdef RX_ENABLE_LOCKS
5527 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5529 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5530 /* Some packets have received acks. If they all have, we can clear
5531 * the transmit queue.
5534 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5535 if (p->header.seq < call->tfirst
5536 && (p->flags & RX_PKTFLAG_ACKED)) {
5538 p->flags &= ~RX_PKTFLAG_TQ;
5539 #ifdef RXDEBUG_PACKET
5547 call->flags |= RX_CALL_TQ_CLEARME;
5549 #endif /* RX_ENABLE_LOCKS */
5550 /* Don't bother doing retransmits if the TQ is cleared. */
5551 if (call->flags & RX_CALL_TQ_CLEARME) {
5552 rxi_ClearTransmitQueue(call, 1);
5554 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5557 /* Always post a resend event, if there is anything in the
5558 * queue, and resend is possible. There should be at least
5559 * one unacknowledged packet in the queue ... otherwise none
5560 * of these packets should be on the queue in the first place.
5562 if (call->resendEvent) {
5563 /* Cancel the existing event and post a new one */
5564 rxevent_Cancel(call->resendEvent, call,
5565 RX_CALL_REFCOUNT_RESEND);
5568 /* The retry time is the retry time on the first unacknowledged
5569 * packet inside the current window */
5571 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5572 /* Don't set timers for packets outside the window */
5573 if (p->header.seq >= call->tfirst + call->twind) {
5577 if (!(p->flags & RX_PKTFLAG_ACKED)
5578 && !clock_IsZero(&p->retryTime)) {
5580 retryTime = p->retryTime;
5585 /* Post a new event to re-run rxi_Start when retries may be needed */
5586 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5587 #ifdef RX_ENABLE_LOCKS
5588 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5590 rxevent_PostNow2(&retryTime, &usenow,
5592 (void *)call, 0, istack);
5593 #else /* RX_ENABLE_LOCKS */
5595 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5596 (void *)call, 0, istack);
5597 #endif /* RX_ENABLE_LOCKS */
5600 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5601 } while (call->flags & RX_CALL_NEED_START);
5603 * TQ references no longer protected by this flag; they must remain
5604 * protected by the global lock.
5606 call->flags &= ~RX_CALL_TQ_BUSY;
5607 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5608 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5609 call, call->tqWaiters, call->flags));
5610 #ifdef RX_ENABLE_LOCKS
5611 osirx_AssertMine(&call->lock, "rxi_Start end");
5612 CV_BROADCAST(&call->cv_tq);
5613 #else /* RX_ENABLE_LOCKS */
5614 osi_rxWakeup(&call->tq);
5615 #endif /* RX_ENABLE_LOCKS */
5618 call->flags |= RX_CALL_NEED_START;
5620 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5622 if (call->resendEvent) {
5623 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5628 /* Also adjusts the keep alive parameters for the call, to reflect
5629 * that we have just sent a packet (so keep alives aren't sent
5632 rxi_Send(struct rx_call *call, struct rx_packet *p,
5635 struct rx_connection *conn = call->conn;
5637 /* Stamp each packet with the user supplied status */
5638 p->header.userStatus = call->localStatus;
5640 /* Allow the security object controlling this call's security to
5641 * make any last-minute changes to the packet */
5642 RXS_SendPacket(conn->securityObject, call, p);
5644 /* Since we're about to send SOME sort of packet to the peer, it's
5645 * safe to nuke any scheduled end-of-packets ack */
5646 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5648 /* Actually send the packet, filling in more connection-specific fields */
5649 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5650 MUTEX_EXIT(&call->lock);
5651 rxi_SendPacket(call, conn, p, istack);
5652 MUTEX_ENTER(&call->lock);
5653 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5655 /* Update last send time for this call (for keep-alive
5656 * processing), and for the connection (so that we can discover
5657 * idle connections) */
5658 conn->lastSendTime = call->lastSendTime = clock_Sec();
5659 /* Don't count keepalives here, so idleness can be tracked. */
5660 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5661 call->lastSendData = call->lastSendTime;
5665 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5666 * that things are fine. Also called periodically to guarantee that nothing
5667 * falls through the cracks (e.g. (error + dally) connections have keepalive
5668 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5670 * haveCTLock Set if calling from rxi_ReapConnections
5672 #ifdef RX_ENABLE_LOCKS
5674 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5675 #else /* RX_ENABLE_LOCKS */
5677 rxi_CheckCall(struct rx_call *call)
5678 #endif /* RX_ENABLE_LOCKS */
5680 struct rx_connection *conn = call->conn;
5682 afs_uint32 deadTime;
5684 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5685 if (call->flags & RX_CALL_TQ_BUSY) {
5686 /* Call is active and will be reset by rxi_Start if it's
5687 * in an error state.
5692 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5694 (((afs_uint32) conn->secondsUntilDead << 10) +
5695 ((afs_uint32) conn->peer->rtt >> 3) +
5696 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5698 /* These are computed to the second (+- 1 second). But that's
5699 * good enough for these values, which should be a significant
5700 * number of seconds. */
5701 if (now > (call->lastReceiveTime + deadTime)) {
5702 if (call->state == RX_STATE_ACTIVE) {
5704 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5706 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5707 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5708 ip_stack_t *ipst = ns->netstack_ip;
5710 ire = ire_cache_lookup(call->conn->peer->host
5711 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5713 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5715 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5722 if (ire && ire->ire_max_frag > 0)
5723 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5724 #if defined(GLOBAL_NETSTACKID)
5728 #endif /* ADAPT_PMTU */
5729 rxi_CallError(call, RX_CALL_DEAD);
5732 #ifdef RX_ENABLE_LOCKS
5733 /* Cancel pending events */
5734 rxevent_Cancel(call->delayedAckEvent, call,
5735 RX_CALL_REFCOUNT_DELAY);
5736 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5737 rxevent_Cancel(call->keepAliveEvent, call,
5738 RX_CALL_REFCOUNT_ALIVE);
5739 if (call->refCount == 0) {
5740 rxi_FreeCall(call, haveCTLock);
5744 #else /* RX_ENABLE_LOCKS */
5747 #endif /* RX_ENABLE_LOCKS */
5749 /* Non-active calls are destroyed if they are not responding
5750 * to pings; active calls are simply flagged in error, so the
5751 * attached process can die reasonably gracefully. */
5753 /* see if we have a non-activity timeout */
5754 if (call->startWait && conn->idleDeadTime
5755 && ((call->startWait + conn->idleDeadTime) < now) &&
5756 (call->flags & RX_CALL_READER_WAIT)) {
5757 if (call->state == RX_STATE_ACTIVE) {
5758 rxi_CallError(call, RX_CALL_TIMEOUT);
5762 if (call->lastSendData && conn->idleDeadTime && (conn->idleDeadErr != 0)
5763 && ((call->lastSendData + conn->idleDeadTime) < now)) {
5764 if (call->state == RX_STATE_ACTIVE) {
5765 rxi_CallError(call, conn->idleDeadErr);
5769 /* see if we have a hard timeout */
5770 if (conn->hardDeadTime
5771 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5772 if (call->state == RX_STATE_ACTIVE)
5773 rxi_CallError(call, RX_CALL_TIMEOUT);
5780 /* When a call is in progress, this routine is called occasionally to
5781 * make sure that some traffic has arrived (or been sent to) the peer.
5782 * If nothing has arrived in a reasonable amount of time, the call is
5783 * declared dead; if nothing has been sent for a while, we send a
5784 * keep-alive packet (if we're actually trying to keep the call alive)
5787 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5789 struct rx_call *call = arg1;
5790 struct rx_connection *conn;
5793 MUTEX_ENTER(&call->lock);
5794 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5795 if (event == call->keepAliveEvent)
5796 call->keepAliveEvent = NULL;
5799 #ifdef RX_ENABLE_LOCKS
5800 if (rxi_CheckCall(call, 0)) {
5801 MUTEX_EXIT(&call->lock);
5804 #else /* RX_ENABLE_LOCKS */
5805 if (rxi_CheckCall(call))
5807 #endif /* RX_ENABLE_LOCKS */
5809 /* Don't try to keep alive dallying calls */
5810 if (call->state == RX_STATE_DALLY) {
5811 MUTEX_EXIT(&call->lock);
5816 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
5817 /* Don't try to send keepalives if there is unacknowledged data */
5818 /* the rexmit code should be good enough, this little hack
5819 * doesn't quite work XXX */
5820 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5822 rxi_ScheduleKeepAliveEvent(call);
5823 MUTEX_EXIT(&call->lock);
5828 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
5830 if (!call->keepAliveEvent) {
5831 struct clock when, now;
5832 clock_GetTime(&now);
5834 when.sec += call->conn->secondsUntilPing;
5835 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5836 call->keepAliveEvent =
5837 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5841 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5843 rxi_KeepAliveOn(struct rx_call *call)
5845 /* Pretend last packet received was received now--i.e. if another
5846 * packet isn't received within the keep alive time, then the call
5847 * will die; Initialize last send time to the current time--even
5848 * if a packet hasn't been sent yet. This will guarantee that a
5849 * keep-alive is sent within the ping time */
5850 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5851 rxi_ScheduleKeepAliveEvent(call);
5854 /* This routine is called to send connection abort messages
5855 * that have been delayed to throttle looping clients. */
5857 rxi_SendDelayedConnAbort(struct rxevent *event,
5858 void *arg1, void *unused)
5860 struct rx_connection *conn = arg1;
5863 struct rx_packet *packet;
5865 MUTEX_ENTER(&conn->conn_data_lock);
5866 conn->delayedAbortEvent = NULL;
5867 error = htonl(conn->error);
5869 MUTEX_EXIT(&conn->conn_data_lock);
5870 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5873 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5874 RX_PACKET_TYPE_ABORT, (char *)&error,
5876 rxi_FreePacket(packet);
5880 /* This routine is called to send call abort messages
5881 * that have been delayed to throttle looping clients. */
5883 rxi_SendDelayedCallAbort(struct rxevent *event,
5884 void *arg1, void *dummy)
5886 struct rx_call *call = arg1;
5889 struct rx_packet *packet;
5891 MUTEX_ENTER(&call->lock);
5892 call->delayedAbortEvent = NULL;
5893 error = htonl(call->error);
5895 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5898 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5899 (char *)&error, sizeof(error), 0);
5900 rxi_FreePacket(packet);
5902 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5903 MUTEX_EXIT(&call->lock);
5906 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5907 * seconds) to ask the client to authenticate itself. The routine
5908 * issues a challenge to the client, which is obtained from the
5909 * security object associated with the connection */
5911 rxi_ChallengeEvent(struct rxevent *event,
5912 void *arg0, void *arg1, int tries)
5914 struct rx_connection *conn = arg0;
5916 conn->challengeEvent = NULL;
5917 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5918 struct rx_packet *packet;
5919 struct clock when, now;
5922 /* We've failed to authenticate for too long.
5923 * Reset any calls waiting for authentication;
5924 * they are all in RX_STATE_PRECALL.
5928 MUTEX_ENTER(&conn->conn_call_lock);
5929 for (i = 0; i < RX_MAXCALLS; i++) {
5930 struct rx_call *call = conn->call[i];
5932 MUTEX_ENTER(&call->lock);
5933 if (call->state == RX_STATE_PRECALL) {
5934 rxi_CallError(call, RX_CALL_DEAD);
5935 rxi_SendCallAbort(call, NULL, 0, 0);
5937 MUTEX_EXIT(&call->lock);
5940 MUTEX_EXIT(&conn->conn_call_lock);
5944 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5946 /* If there's no packet available, do this later. */
5947 RXS_GetChallenge(conn->securityObject, conn, packet);
5948 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5949 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5950 rxi_FreePacket(packet);
5952 clock_GetTime(&now);
5954 when.sec += RX_CHALLENGE_TIMEOUT;
5955 conn->challengeEvent =
5956 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5961 /* Call this routine to start requesting the client to authenticate
5962 * itself. This will continue until authentication is established,
5963 * the call times out, or an invalid response is returned. The
5964 * security object associated with the connection is asked to create
5965 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5966 * defined earlier. */
5968 rxi_ChallengeOn(struct rx_connection *conn)
5970 if (!conn->challengeEvent) {
5971 RXS_CreateChallenge(conn->securityObject, conn);
5972 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5977 /* Compute round trip time of the packet provided, in *rttp.
5980 /* rxi_ComputeRoundTripTime is called with peer locked. */
5981 /* sentp and/or peer may be null */
5983 rxi_ComputeRoundTripTime(struct rx_packet *p,
5984 struct clock *sentp,
5985 struct rx_peer *peer)
5987 struct clock thisRtt, *rttp = &thisRtt;
5991 clock_GetTime(rttp);
5993 if (clock_Lt(rttp, sentp)) {
5995 return; /* somebody set the clock back, don't count this time. */
5997 clock_Sub(rttp, sentp);
5998 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
5999 p->header.callNumber, p, rttp->sec, rttp->usec));
6001 if (rttp->sec == 0 && rttp->usec == 0) {
6003 * The actual round trip time is shorter than the
6004 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6005 * Since we can't tell which at the moment we will assume 1ms.
6010 if (rx_stats_active) {
6011 MUTEX_ENTER(&rx_stats_mutex);
6012 if (clock_Lt(rttp, &rx_stats.minRtt))
6013 rx_stats.minRtt = *rttp;
6014 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
6015 if (rttp->sec > 60) {
6016 MUTEX_EXIT(&rx_stats_mutex);
6017 return; /* somebody set the clock ahead */
6019 rx_stats.maxRtt = *rttp;
6021 clock_Add(&rx_stats.totalRtt, rttp);
6022 rx_stats.nRttSamples++;
6023 MUTEX_EXIT(&rx_stats_mutex);
6026 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6028 /* Apply VanJacobson round-trip estimations */
6033 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6034 * srtt is stored as fixed point with 3 bits after the binary
6035 * point (i.e., scaled by 8). The following magic is
6036 * equivalent to the smoothing algorithm in rfc793 with an
6037 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6038 * srtt'*8 = rtt + srtt*7
6039 * srtt'*8 = srtt*8 + rtt - srtt
6040 * srtt' = srtt + rtt/8 - srtt/8
6041 * srtt' = srtt + (rtt - srtt)/8
6044 delta = _8THMSEC(rttp) - peer->rtt;
6045 peer->rtt += (delta >> 3);
6048 * We accumulate a smoothed rtt variance (actually, a smoothed
6049 * mean difference), then set the retransmit timer to smoothed
6050 * rtt + 4 times the smoothed variance (was 2x in van's original
6051 * paper, but 4x works better for me, and apparently for him as
6053 * rttvar is stored as
6054 * fixed point with 2 bits after the binary point (scaled by
6055 * 4). The following is equivalent to rfc793 smoothing with
6056 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6057 * rttvar'*4 = rttvar*3 + |delta|
6058 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6059 * rttvar' = rttvar + |delta|/4 - rttvar/4
6060 * rttvar' = rttvar + (|delta| - rttvar)/4
6061 * This replaces rfc793's wired-in beta.
6062 * dev*4 = dev*4 + (|actual - expected| - dev)
6068 delta -= (peer->rtt_dev << 1);
6069 peer->rtt_dev += (delta >> 3);
6071 /* I don't have a stored RTT so I start with this value. Since I'm
6072 * probably just starting a call, and will be pushing more data down
6073 * this, I expect congestion to increase rapidly. So I fudge a
6074 * little, and I set deviance to half the rtt. In practice,
6075 * deviance tends to approach something a little less than
6076 * half the smoothed rtt. */
6077 peer->rtt = _8THMSEC(rttp) + 8;
6078 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6080 /* the timeout is RTT + 4*MDEV but no less than rx_minPeerTimeout msec.
6081 * This is because one end or the other of these connections is usually
6082 * in a user process, and can be switched and/or swapped out. So on fast,
6083 * reliable networks, the timeout would otherwise be too short. */
6084 rtt_timeout = MAX(((peer->rtt >> 3) + peer->rtt_dev), rx_minPeerTimeout);
6085 clock_Zero(&(peer->timeout));
6086 clock_Addmsec(&(peer->timeout), rtt_timeout);
6088 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6089 p->header.callNumber, p, MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6093 /* Find all server connections that have not been active for a long time, and
6096 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6098 struct clock now, when;
6099 clock_GetTime(&now);
6101 /* Find server connection structures that haven't been used for
6102 * greater than rx_idleConnectionTime */
6104 struct rx_connection **conn_ptr, **conn_end;
6105 int i, havecalls = 0;
6106 MUTEX_ENTER(&rx_connHashTable_lock);
6107 for (conn_ptr = &rx_connHashTable[0], conn_end =
6108 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6110 struct rx_connection *conn, *next;
6111 struct rx_call *call;
6115 for (conn = *conn_ptr; conn; conn = next) {
6116 /* XXX -- Shouldn't the connection be locked? */
6119 for (i = 0; i < RX_MAXCALLS; i++) {
6120 call = conn->call[i];
6124 code = MUTEX_TRYENTER(&call->lock);
6127 #ifdef RX_ENABLE_LOCKS
6128 result = rxi_CheckCall(call, 1);
6129 #else /* RX_ENABLE_LOCKS */
6130 result = rxi_CheckCall(call);
6131 #endif /* RX_ENABLE_LOCKS */
6132 MUTEX_EXIT(&call->lock);
6134 /* If CheckCall freed the call, it might
6135 * have destroyed the connection as well,
6136 * which screws up the linked lists.
6142 if (conn->type == RX_SERVER_CONNECTION) {
6143 /* This only actually destroys the connection if
6144 * there are no outstanding calls */
6145 MUTEX_ENTER(&conn->conn_data_lock);
6146 if (!havecalls && !conn->refCount
6147 && ((conn->lastSendTime + rx_idleConnectionTime) <
6149 conn->refCount++; /* it will be decr in rx_DestroyConn */
6150 MUTEX_EXIT(&conn->conn_data_lock);
6151 #ifdef RX_ENABLE_LOCKS
6152 rxi_DestroyConnectionNoLock(conn);
6153 #else /* RX_ENABLE_LOCKS */
6154 rxi_DestroyConnection(conn);
6155 #endif /* RX_ENABLE_LOCKS */
6157 #ifdef RX_ENABLE_LOCKS
6159 MUTEX_EXIT(&conn->conn_data_lock);
6161 #endif /* RX_ENABLE_LOCKS */
6165 #ifdef RX_ENABLE_LOCKS
6166 while (rx_connCleanup_list) {
6167 struct rx_connection *conn;
6168 conn = rx_connCleanup_list;
6169 rx_connCleanup_list = rx_connCleanup_list->next;
6170 MUTEX_EXIT(&rx_connHashTable_lock);
6171 rxi_CleanupConnection(conn);
6172 MUTEX_ENTER(&rx_connHashTable_lock);
6174 MUTEX_EXIT(&rx_connHashTable_lock);
6175 #endif /* RX_ENABLE_LOCKS */
6178 /* Find any peer structures that haven't been used (haven't had an
6179 * associated connection) for greater than rx_idlePeerTime */
6181 struct rx_peer **peer_ptr, **peer_end;
6183 MUTEX_ENTER(&rx_rpc_stats);
6184 MUTEX_ENTER(&rx_peerHashTable_lock);
6185 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6186 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6188 struct rx_peer *peer, *next, *prev;
6189 for (prev = peer = *peer_ptr; peer; peer = next) {
6191 code = MUTEX_TRYENTER(&peer->peer_lock);
6192 if ((code) && (peer->refCount == 0)
6193 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6194 rx_interface_stat_p rpc_stat, nrpc_stat;
6196 MUTEX_EXIT(&peer->peer_lock);
6197 MUTEX_DESTROY(&peer->peer_lock);
6199 (&peer->rpcStats, rpc_stat, nrpc_stat,
6200 rx_interface_stat)) {
6201 unsigned int num_funcs;
6204 queue_Remove(&rpc_stat->queue_header);
6205 queue_Remove(&rpc_stat->all_peers);
6206 num_funcs = rpc_stat->stats[0].func_total;
6208 sizeof(rx_interface_stat_t) +
6209 rpc_stat->stats[0].func_total *
6210 sizeof(rx_function_entry_v1_t);
6212 rxi_Free(rpc_stat, space);
6213 rxi_rpc_peer_stat_cnt -= num_funcs;
6216 if (rx_stats_active)
6217 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6218 if (peer == *peer_ptr) {
6225 MUTEX_EXIT(&peer->peer_lock);
6231 MUTEX_EXIT(&rx_peerHashTable_lock);
6232 MUTEX_EXIT(&rx_rpc_stats);
6235 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6236 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6237 * GC, just below. Really, we shouldn't have to keep moving packets from
6238 * one place to another, but instead ought to always know if we can
6239 * afford to hold onto a packet in its particular use. */
6240 MUTEX_ENTER(&rx_freePktQ_lock);
6241 if (rx_waitingForPackets) {
6242 rx_waitingForPackets = 0;
6243 #ifdef RX_ENABLE_LOCKS
6244 CV_BROADCAST(&rx_waitingForPackets_cv);
6246 osi_rxWakeup(&rx_waitingForPackets);
6249 MUTEX_EXIT(&rx_freePktQ_lock);
6252 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6253 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6257 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6258 * rx.h is sort of strange this is better. This is called with a security
6259 * object before it is discarded. Each connection using a security object has
6260 * its own refcount to the object so it won't actually be freed until the last
6261 * connection is destroyed.
6263 * This is the only rxs module call. A hold could also be written but no one
6267 rxs_Release(struct rx_securityClass *aobj)
6269 return RXS_Close(aobj);
6273 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6274 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6275 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6276 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6278 /* Adjust our estimate of the transmission rate to this peer, given
6279 * that the packet p was just acked. We can adjust peer->timeout and
6280 * call->twind. Pragmatically, this is called
6281 * only with packets of maximal length.
6282 * Called with peer and call locked.
6286 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6287 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6289 afs_int32 xferSize, xferMs;
6293 /* Count down packets */
6294 if (peer->rateFlag > 0)
6296 /* Do nothing until we're enabled */
6297 if (peer->rateFlag != 0)
6302 /* Count only when the ack seems legitimate */
6303 switch (ackReason) {
6304 case RX_ACK_REQUESTED:
6306 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6310 case RX_ACK_PING_RESPONSE:
6311 if (p) /* want the response to ping-request, not data send */
6313 clock_GetTime(&newTO);
6314 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6315 clock_Sub(&newTO, &call->pingRequestTime);
6316 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6320 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6327 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)",
6328 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
6329 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6331 /* Track only packets that are big enough. */
6332 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6336 /* absorb RTT data (in milliseconds) for these big packets */
6337 if (peer->smRtt == 0) {
6338 peer->smRtt = xferMs;
6340 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6345 if (peer->countDown) {
6349 peer->countDown = 10; /* recalculate only every so often */
6351 /* In practice, we can measure only the RTT for full packets,
6352 * because of the way Rx acks the data that it receives. (If it's
6353 * smaller than a full packet, it often gets implicitly acked
6354 * either by the call response (from a server) or by the next call
6355 * (from a client), and either case confuses transmission times
6356 * with processing times.) Therefore, replace the above
6357 * more-sophisticated processing with a simpler version, where the
6358 * smoothed RTT is kept for full-size packets, and the time to
6359 * transmit a windowful of full-size packets is simply RTT *
6360 * windowSize. Again, we take two steps:
6361 - ensure the timeout is large enough for a single packet's RTT;
6362 - ensure that the window is small enough to fit in the desired timeout.*/
6364 /* First, the timeout check. */
6365 minTime = peer->smRtt;
6366 /* Get a reasonable estimate for a timeout period */
6368 newTO.sec = minTime / 1000;
6369 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6371 /* Increase the timeout period so that we can always do at least
6372 * one packet exchange */
6373 if (clock_Gt(&newTO, &peer->timeout)) {
6375 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u, ps %u)",
6376 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
6377 newTO.sec, newTO.usec, peer->smRtt, peer->packetSize));
6379 peer->timeout = newTO;
6382 /* Now, get an estimate for the transmit window size. */
6383 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6384 /* Now, convert to the number of full packets that could fit in a
6385 * reasonable fraction of that interval */
6386 minTime /= (peer->smRtt << 1);
6387 xferSize = minTime; /* (make a copy) */
6389 /* Now clamp the size to reasonable bounds. */
6392 else if (minTime > rx_Window)
6393 minTime = rx_Window;
6394 /* if (minTime != peer->maxWindow) {
6395 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6396 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6397 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6399 peer->maxWindow = minTime;
6400 elide... call->twind = minTime;
6404 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6405 * Discern this by calculating the timeout necessary for rx_Window
6407 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6408 /* calculate estimate for transmission interval in milliseconds */
6409 minTime = rx_Window * peer->smRtt;
6410 if (minTime < 1000) {
6411 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u, ps %u)",
6412 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6413 peer->timeout.usec, peer->smRtt, peer->packetSize));
6415 newTO.sec = 0; /* cut back on timeout by half a second */
6416 newTO.usec = 500000;
6417 clock_Sub(&peer->timeout, &newTO);
6422 } /* end of rxi_ComputeRate */
6423 #endif /* ADAPT_WINDOW */
6431 #define TRACE_OPTION_RX_DEBUG 16
6439 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6440 0, KEY_QUERY_VALUE, &parmKey);
6441 if (code != ERROR_SUCCESS)
6444 dummyLen = sizeof(TraceOption);
6445 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6446 (BYTE *) &TraceOption, &dummyLen);
6447 if (code == ERROR_SUCCESS) {
6448 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6450 RegCloseKey (parmKey);
6451 #endif /* AFS_NT40_ENV */
6456 rx_DebugOnOff(int on)
6460 rxdebug_active = on;
6466 rx_StatsOnOff(int on)
6469 rx_stats_active = on;
6474 /* Don't call this debugging routine directly; use dpf */
6476 rxi_DebugPrint(char *format, ...)
6485 va_start(ap, format);
6487 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6490 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6492 if (msg[len-1] != '\n') {
6496 OutputDebugString(msg);
6503 va_start(ap, format);
6505 clock_GetTime(&now);
6506 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
6507 (unsigned int)now.usec);
6508 vfprintf(rx_Log, format, ap);
6517 * This function is used to process the rx_stats structure that is local
6518 * to a process as well as an rx_stats structure received from a remote
6519 * process (via rxdebug). Therefore, it needs to do minimal version
6523 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6524 afs_int32 freePackets, char version)
6529 if (size != sizeof(struct rx_statistics)) {
6531 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
6532 size, sizeof(struct rx_statistics));
6535 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6538 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6539 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
6540 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6541 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6542 s->specialPktAllocFailures);
6544 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
6545 s->receivePktAllocFailures, s->sendPktAllocFailures,
6546 s->specialPktAllocFailures);
6550 " greedy %u, " "bogusReads %u (last from host %x), "
6551 "noPackets %u, " "noBuffers %u, " "selects %u, "
6552 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
6553 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6554 s->selects, s->sendSelects);
6556 fprintf(file, " packets read: ");
6557 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6558 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
6560 fprintf(file, "\n");
6563 " other read counters: data %u, " "ack %u, " "dup %u "
6564 "spurious %u " "dally %u\n", s->dataPacketsRead,
6565 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6566 s->ignorePacketDally);
6568 fprintf(file, " packets sent: ");
6569 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6570 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
6572 fprintf(file, "\n");
6575 " other send counters: ack %u, " "data %u (not resends), "
6576 "resends %u, " "pushed %u, " "acked&ignored %u\n",
6577 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6578 s->dataPacketsPushed, s->ignoreAckedPacket);
6581 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
6582 s->netSendFailures, (int)s->fatalErrors);
6584 if (s->nRttSamples) {
6585 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6586 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6588 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6589 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6593 " %d server connections, " "%d client connections, "
6594 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6595 s->nServerConns, s->nClientConns, s->nPeerStructs,
6596 s->nCallStructs, s->nFreeCallStructs);
6598 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6599 fprintf(file, " %d clock updates\n", clock_nUpdates);
6602 fprintf(file, "ERROR: compiled without RXDEBUG\n");
6606 /* for backward compatibility */
6608 rx_PrintStats(FILE * file)
6610 MUTEX_ENTER(&rx_stats_mutex);
6611 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6613 MUTEX_EXIT(&rx_stats_mutex);
6617 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6619 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
6620 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6621 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6624 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6625 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6626 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6629 " Packet size %d, " "max in packet skew %d, "
6630 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6631 (int)peer->outPacketSkew);
6635 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
6637 * This mutex protects the following static variables:
6641 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
6642 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
6644 #define LOCK_RX_DEBUG
6645 #define UNLOCK_RX_DEBUG
6646 #endif /* AFS_PTHREAD_ENV */
6650 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6651 u_char type, void *inputData, size_t inputLength,
6652 void *outputData, size_t outputLength)
6654 static afs_int32 counter = 100;
6655 time_t waitTime, waitCount, startTime;
6656 struct rx_header theader;
6659 struct timeval tv_now, tv_wake, tv_delta;
6660 struct sockaddr_in taddr, faddr;
6669 startTime = time(0);
6675 tp = &tbuffer[sizeof(struct rx_header)];
6676 taddr.sin_family = AF_INET;
6677 taddr.sin_port = remotePort;
6678 taddr.sin_addr.s_addr = remoteAddr;
6679 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6680 taddr.sin_len = sizeof(struct sockaddr_in);
6683 memset(&theader, 0, sizeof(theader));
6684 theader.epoch = htonl(999);
6686 theader.callNumber = htonl(counter);
6689 theader.type = type;
6690 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6691 theader.serviceId = 0;
6693 memcpy(tbuffer, &theader, sizeof(theader));
6694 memcpy(tp, inputData, inputLength);
6696 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6697 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6699 /* see if there's a packet available */
6700 gettimeofday(&tv_wake,0);
6701 tv_wake.tv_sec += waitTime;
6704 FD_SET(socket, &imask);
6705 tv_delta.tv_sec = tv_wake.tv_sec;
6706 tv_delta.tv_usec = tv_wake.tv_usec;
6707 gettimeofday(&tv_now, 0);
6709 if (tv_delta.tv_usec < tv_now.tv_usec) {
6711 tv_delta.tv_usec += 1000000;
6714 tv_delta.tv_usec -= tv_now.tv_usec;
6716 if (tv_delta.tv_sec < tv_now.tv_sec) {
6720 tv_delta.tv_sec -= tv_now.tv_sec;
6723 code = select(0, &imask, 0, 0, &tv_delta);
6724 #else /* AFS_NT40_ENV */
6725 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6726 #endif /* AFS_NT40_ENV */
6727 if (code == 1 && FD_ISSET(socket, &imask)) {
6728 /* now receive a packet */
6729 faddrLen = sizeof(struct sockaddr_in);
6731 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6732 (struct sockaddr *)&faddr, &faddrLen);
6735 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6736 if (counter == ntohl(theader.callNumber))
6744 /* see if we've timed out */
6752 code -= sizeof(struct rx_header);
6753 if (code > outputLength)
6754 code = outputLength;
6755 memcpy(outputData, tp, code);
6758 #endif /* RXDEBUG */
6761 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6762 afs_uint16 remotePort, struct rx_debugStats * stat,
6763 afs_uint32 * supportedValues)
6769 struct rx_debugIn in;
6771 *supportedValues = 0;
6772 in.type = htonl(RX_DEBUGI_GETSTATS);
6775 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6776 &in, sizeof(in), stat, sizeof(*stat));
6779 * If the call was successful, fixup the version and indicate
6780 * what contents of the stat structure are valid.
6781 * Also do net to host conversion of fields here.
6785 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6786 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6788 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6789 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6791 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6792 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6794 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6795 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6797 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6798 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6800 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6801 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6803 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6804 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6806 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6807 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6809 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6810 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6812 stat->nFreePackets = ntohl(stat->nFreePackets);
6813 stat->packetReclaims = ntohl(stat->packetReclaims);
6814 stat->callsExecuted = ntohl(stat->callsExecuted);
6815 stat->nWaiting = ntohl(stat->nWaiting);
6816 stat->idleThreads = ntohl(stat->idleThreads);
6817 stat->nWaited = ntohl(stat->nWaited);
6818 stat->nPackets = ntohl(stat->nPackets);
6825 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6826 afs_uint16 remotePort, struct rx_statistics * stat,
6827 afs_uint32 * supportedValues)
6833 struct rx_debugIn in;
6834 afs_int32 *lp = (afs_int32 *) stat;
6838 * supportedValues is currently unused, but added to allow future
6839 * versioning of this function.
6842 *supportedValues = 0;
6843 in.type = htonl(RX_DEBUGI_RXSTATS);
6845 memset(stat, 0, sizeof(*stat));
6847 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6848 &in, sizeof(in), stat, sizeof(*stat));
6853 * Do net to host conversion here
6856 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6865 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6866 afs_uint16 remotePort, size_t version_length,
6871 return MakeDebugCall(socket, remoteAddr, remotePort,
6872 RX_PACKET_TYPE_VERSION, a, 1, version,
6880 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6881 afs_uint16 remotePort, afs_int32 * nextConnection,
6882 int allConnections, afs_uint32 debugSupportedValues,
6883 struct rx_debugConn * conn,
6884 afs_uint32 * supportedValues)
6890 struct rx_debugIn in;
6894 * supportedValues is currently unused, but added to allow future
6895 * versioning of this function.
6898 *supportedValues = 0;
6899 if (allConnections) {
6900 in.type = htonl(RX_DEBUGI_GETALLCONN);
6902 in.type = htonl(RX_DEBUGI_GETCONN);
6904 in.index = htonl(*nextConnection);
6905 memset(conn, 0, sizeof(*conn));
6907 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6908 &in, sizeof(in), conn, sizeof(*conn));
6911 *nextConnection += 1;
6914 * Convert old connection format to new structure.
6917 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6918 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6919 #define MOVEvL(a) (conn->a = vL->a)
6921 /* any old or unrecognized version... */
6922 for (i = 0; i < RX_MAXCALLS; i++) {
6923 MOVEvL(callState[i]);
6924 MOVEvL(callMode[i]);
6925 MOVEvL(callFlags[i]);
6926 MOVEvL(callOther[i]);
6928 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6929 MOVEvL(secStats.type);
6930 MOVEvL(secStats.level);
6931 MOVEvL(secStats.flags);
6932 MOVEvL(secStats.expires);
6933 MOVEvL(secStats.packetsReceived);
6934 MOVEvL(secStats.packetsSent);
6935 MOVEvL(secStats.bytesReceived);
6936 MOVEvL(secStats.bytesSent);
6941 * Do net to host conversion here
6943 * I don't convert host or port since we are most likely
6944 * going to want these in NBO.
6946 conn->cid = ntohl(conn->cid);
6947 conn->serial = ntohl(conn->serial);
6948 for (i = 0; i < RX_MAXCALLS; i++) {
6949 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6951 conn->error = ntohl(conn->error);
6952 conn->secStats.flags = ntohl(conn->secStats.flags);
6953 conn->secStats.expires = ntohl(conn->secStats.expires);
6954 conn->secStats.packetsReceived =
6955 ntohl(conn->secStats.packetsReceived);
6956 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6957 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6958 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6959 conn->epoch = ntohl(conn->epoch);
6960 conn->natMTU = ntohl(conn->natMTU);
6967 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6968 afs_uint16 remotePort, afs_int32 * nextPeer,
6969 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6970 afs_uint32 * supportedValues)
6976 struct rx_debugIn in;
6979 * supportedValues is currently unused, but added to allow future
6980 * versioning of this function.
6983 *supportedValues = 0;
6984 in.type = htonl(RX_DEBUGI_GETPEER);
6985 in.index = htonl(*nextPeer);
6986 memset(peer, 0, sizeof(*peer));
6988 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6989 &in, sizeof(in), peer, sizeof(*peer));
6995 * Do net to host conversion here
6997 * I don't convert host or port since we are most likely
6998 * going to want these in NBO.
7000 peer->ifMTU = ntohs(peer->ifMTU);
7001 peer->idleWhen = ntohl(peer->idleWhen);
7002 peer->refCount = ntohs(peer->refCount);
7003 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7004 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7005 peer->rtt = ntohl(peer->rtt);
7006 peer->rtt_dev = ntohl(peer->rtt_dev);
7007 peer->timeout.sec = ntohl(peer->timeout.sec);
7008 peer->timeout.usec = ntohl(peer->timeout.usec);
7009 peer->nSent = ntohl(peer->nSent);
7010 peer->reSends = ntohl(peer->reSends);
7011 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7012 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7013 peer->rateFlag = ntohl(peer->rateFlag);
7014 peer->natMTU = ntohs(peer->natMTU);
7015 peer->maxMTU = ntohs(peer->maxMTU);
7016 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7017 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7018 peer->MTU = ntohs(peer->MTU);
7019 peer->cwind = ntohs(peer->cwind);
7020 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7021 peer->congestSeq = ntohs(peer->congestSeq);
7022 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7023 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7024 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7025 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7032 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7033 struct rx_debugPeer * peerStats)
7036 afs_int32 error = 1; /* default to "did not succeed" */
7037 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7039 MUTEX_ENTER(&rx_peerHashTable_lock);
7040 for(tp = rx_peerHashTable[hashValue];
7041 tp != NULL; tp = tp->next) {
7042 if (tp->host == peerHost)
7049 peerStats->host = tp->host;
7050 peerStats->port = tp->port;
7051 peerStats->ifMTU = tp->ifMTU;
7052 peerStats->idleWhen = tp->idleWhen;
7053 peerStats->refCount = tp->refCount;
7054 peerStats->burstSize = tp->burstSize;
7055 peerStats->burst = tp->burst;
7056 peerStats->burstWait.sec = tp->burstWait.sec;
7057 peerStats->burstWait.usec = tp->burstWait.usec;
7058 peerStats->rtt = tp->rtt;
7059 peerStats->rtt_dev = tp->rtt_dev;
7060 peerStats->timeout.sec = tp->timeout.sec;
7061 peerStats->timeout.usec = tp->timeout.usec;
7062 peerStats->nSent = tp->nSent;
7063 peerStats->reSends = tp->reSends;
7064 peerStats->inPacketSkew = tp->inPacketSkew;
7065 peerStats->outPacketSkew = tp->outPacketSkew;
7066 peerStats->rateFlag = tp->rateFlag;
7067 peerStats->natMTU = tp->natMTU;
7068 peerStats->maxMTU = tp->maxMTU;
7069 peerStats->maxDgramPackets = tp->maxDgramPackets;
7070 peerStats->ifDgramPackets = tp->ifDgramPackets;
7071 peerStats->MTU = tp->MTU;
7072 peerStats->cwind = tp->cwind;
7073 peerStats->nDgramPackets = tp->nDgramPackets;
7074 peerStats->congestSeq = tp->congestSeq;
7075 peerStats->bytesSent.high = tp->bytesSent.high;
7076 peerStats->bytesSent.low = tp->bytesSent.low;
7077 peerStats->bytesReceived.high = tp->bytesReceived.high;
7078 peerStats->bytesReceived.low = tp->bytesReceived.low;
7080 MUTEX_EXIT(&rx_peerHashTable_lock);
7088 struct rx_serverQueueEntry *np;
7091 struct rx_call *call;
7092 struct rx_serverQueueEntry *sq;
7096 if (rxinit_status == 1) {
7098 return; /* Already shutdown. */
7102 #ifndef AFS_PTHREAD_ENV
7103 FD_ZERO(&rx_selectMask);
7104 #endif /* AFS_PTHREAD_ENV */
7105 rxi_dataQuota = RX_MAX_QUOTA;
7106 #ifndef AFS_PTHREAD_ENV
7108 #endif /* AFS_PTHREAD_ENV */
7111 #ifndef AFS_PTHREAD_ENV
7112 #ifndef AFS_USE_GETTIMEOFDAY
7114 #endif /* AFS_USE_GETTIMEOFDAY */
7115 #endif /* AFS_PTHREAD_ENV */
7117 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7118 call = queue_First(&rx_freeCallQueue, rx_call);
7120 rxi_Free(call, sizeof(struct rx_call));
7123 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7124 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7130 struct rx_peer **peer_ptr, **peer_end;
7131 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7132 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7134 struct rx_peer *peer, *next;
7135 for (peer = *peer_ptr; peer; peer = next) {
7136 rx_interface_stat_p rpc_stat, nrpc_stat;
7139 (&peer->rpcStats, rpc_stat, nrpc_stat,
7140 rx_interface_stat)) {
7141 unsigned int num_funcs;
7144 queue_Remove(&rpc_stat->queue_header);
7145 queue_Remove(&rpc_stat->all_peers);
7146 num_funcs = rpc_stat->stats[0].func_total;
7148 sizeof(rx_interface_stat_t) +
7149 rpc_stat->stats[0].func_total *
7150 sizeof(rx_function_entry_v1_t);
7152 rxi_Free(rpc_stat, space);
7153 MUTEX_ENTER(&rx_rpc_stats);
7154 rxi_rpc_peer_stat_cnt -= num_funcs;
7155 MUTEX_EXIT(&rx_rpc_stats);
7159 if (rx_stats_active)
7160 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7164 for (i = 0; i < RX_MAX_SERVICES; i++) {
7166 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7168 for (i = 0; i < rx_hashTableSize; i++) {
7169 struct rx_connection *tc, *ntc;
7170 MUTEX_ENTER(&rx_connHashTable_lock);
7171 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7173 for (j = 0; j < RX_MAXCALLS; j++) {
7175 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7178 rxi_Free(tc, sizeof(*tc));
7180 MUTEX_EXIT(&rx_connHashTable_lock);
7183 MUTEX_ENTER(&freeSQEList_lock);
7185 while ((np = rx_FreeSQEList)) {
7186 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7187 MUTEX_DESTROY(&np->lock);
7188 rxi_Free(np, sizeof(*np));
7191 MUTEX_EXIT(&freeSQEList_lock);
7192 MUTEX_DESTROY(&freeSQEList_lock);
7193 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7194 MUTEX_DESTROY(&rx_connHashTable_lock);
7195 MUTEX_DESTROY(&rx_peerHashTable_lock);
7196 MUTEX_DESTROY(&rx_serverPool_lock);
7198 osi_Free(rx_connHashTable,
7199 rx_hashTableSize * sizeof(struct rx_connection *));
7200 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7202 UNPIN(rx_connHashTable,
7203 rx_hashTableSize * sizeof(struct rx_connection *));
7204 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7206 rxi_FreeAllPackets();
7208 MUTEX_ENTER(&rx_quota_mutex);
7209 rxi_dataQuota = RX_MAX_QUOTA;
7210 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7211 MUTEX_EXIT(&rx_quota_mutex);
7216 #ifdef RX_ENABLE_LOCKS
7218 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7220 if (!MUTEX_ISMINE(lockaddr))
7221 osi_Panic("Lock not held: %s", msg);
7223 #endif /* RX_ENABLE_LOCKS */
7228 * Routines to implement connection specific data.
7232 rx_KeyCreate(rx_destructor_t rtn)
7235 MUTEX_ENTER(&rxi_keyCreate_lock);
7236 key = rxi_keyCreate_counter++;
7237 rxi_keyCreate_destructor = (rx_destructor_t *)
7238 realloc((void *)rxi_keyCreate_destructor,
7239 (key + 1) * sizeof(rx_destructor_t));
7240 rxi_keyCreate_destructor[key] = rtn;
7241 MUTEX_EXIT(&rxi_keyCreate_lock);
7246 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7249 MUTEX_ENTER(&conn->conn_data_lock);
7250 if (!conn->specific) {
7251 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7252 for (i = 0; i < key; i++)
7253 conn->specific[i] = NULL;
7254 conn->nSpecific = key + 1;
7255 conn->specific[key] = ptr;
7256 } else if (key >= conn->nSpecific) {
7257 conn->specific = (void **)
7258 realloc(conn->specific, (key + 1) * sizeof(void *));
7259 for (i = conn->nSpecific; i < key; i++)
7260 conn->specific[i] = NULL;
7261 conn->nSpecific = key + 1;
7262 conn->specific[key] = ptr;
7264 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7265 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7266 conn->specific[key] = ptr;
7268 MUTEX_EXIT(&conn->conn_data_lock);
7272 rx_GetSpecific(struct rx_connection *conn, int key)
7275 MUTEX_ENTER(&conn->conn_data_lock);
7276 if (key >= conn->nSpecific)
7279 ptr = conn->specific[key];
7280 MUTEX_EXIT(&conn->conn_data_lock);
7284 #endif /* !KERNEL */
7287 * processStats is a queue used to store the statistics for the local
7288 * process. Its contents are similar to the contents of the rpcStats
7289 * queue on a rx_peer structure, but the actual data stored within
7290 * this queue contains totals across the lifetime of the process (assuming
7291 * the stats have not been reset) - unlike the per peer structures
7292 * which can come and go based upon the peer lifetime.
7295 static struct rx_queue processStats = { &processStats, &processStats };
7298 * peerStats is a queue used to store the statistics for all peer structs.
7299 * Its contents are the union of all the peer rpcStats queues.
7302 static struct rx_queue peerStats = { &peerStats, &peerStats };
7305 * rxi_monitor_processStats is used to turn process wide stat collection
7309 static int rxi_monitor_processStats = 0;
7312 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7315 static int rxi_monitor_peerStats = 0;
7318 * rxi_AddRpcStat - given all of the information for a particular rpc
7319 * call, create (if needed) and update the stat totals for the rpc.
7323 * IN stats - the queue of stats that will be updated with the new value
7325 * IN rxInterface - a unique number that identifies the rpc interface
7327 * IN currentFunc - the index of the function being invoked
7329 * IN totalFunc - the total number of functions in this interface
7331 * IN queueTime - the amount of time this function waited for a thread
7333 * IN execTime - the amount of time this function invocation took to execute
7335 * IN bytesSent - the number bytes sent by this invocation
7337 * IN bytesRcvd - the number bytes received by this invocation
7339 * IN isServer - if true, this invocation was made to a server
7341 * IN remoteHost - the ip address of the remote host
7343 * IN remotePort - the port of the remote host
7345 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7347 * INOUT counter - if a new stats structure is allocated, the counter will
7348 * be updated with the new number of allocated stat structures
7356 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7357 afs_uint32 currentFunc, afs_uint32 totalFunc,
7358 struct clock *queueTime, struct clock *execTime,
7359 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7360 afs_uint32 remoteHost, afs_uint32 remotePort,
7361 int addToPeerList, unsigned int *counter)
7364 rx_interface_stat_p rpc_stat, nrpc_stat;
7367 * See if there's already a structure for this interface
7370 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7371 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7372 && (rpc_stat->stats[0].remote_is_server == isServer))
7377 * Didn't find a match so allocate a new structure and add it to the
7381 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7382 || (rpc_stat->stats[0].interfaceId != rxInterface)
7383 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7388 sizeof(rx_interface_stat_t) +
7389 totalFunc * sizeof(rx_function_entry_v1_t);
7391 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7392 if (rpc_stat == NULL) {
7396 *counter += totalFunc;
7397 for (i = 0; i < totalFunc; i++) {
7398 rpc_stat->stats[i].remote_peer = remoteHost;
7399 rpc_stat->stats[i].remote_port = remotePort;
7400 rpc_stat->stats[i].remote_is_server = isServer;
7401 rpc_stat->stats[i].interfaceId = rxInterface;
7402 rpc_stat->stats[i].func_total = totalFunc;
7403 rpc_stat->stats[i].func_index = i;
7404 hzero(rpc_stat->stats[i].invocations);
7405 hzero(rpc_stat->stats[i].bytes_sent);
7406 hzero(rpc_stat->stats[i].bytes_rcvd);
7407 rpc_stat->stats[i].queue_time_sum.sec = 0;
7408 rpc_stat->stats[i].queue_time_sum.usec = 0;
7409 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7410 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7411 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7412 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7413 rpc_stat->stats[i].queue_time_max.sec = 0;
7414 rpc_stat->stats[i].queue_time_max.usec = 0;
7415 rpc_stat->stats[i].execution_time_sum.sec = 0;
7416 rpc_stat->stats[i].execution_time_sum.usec = 0;
7417 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7418 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7419 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7420 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7421 rpc_stat->stats[i].execution_time_max.sec = 0;
7422 rpc_stat->stats[i].execution_time_max.usec = 0;
7424 queue_Prepend(stats, rpc_stat);
7425 if (addToPeerList) {
7426 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7431 * Increment the stats for this function
7434 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7435 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7436 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7437 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7438 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7439 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7440 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7442 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7443 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7445 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7446 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7448 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7449 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7451 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7452 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7460 * rx_IncrementTimeAndCount - increment the times and count for a particular
7465 * IN peer - the peer who invoked the rpc
7467 * IN rxInterface - a unique number that identifies the rpc interface
7469 * IN currentFunc - the index of the function being invoked
7471 * IN totalFunc - the total number of functions in this interface
7473 * IN queueTime - the amount of time this function waited for a thread
7475 * IN execTime - the amount of time this function invocation took to execute
7477 * IN bytesSent - the number bytes sent by this invocation
7479 * IN bytesRcvd - the number bytes received by this invocation
7481 * IN isServer - if true, this invocation was made to a server
7489 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7490 afs_uint32 currentFunc, afs_uint32 totalFunc,
7491 struct clock *queueTime, struct clock *execTime,
7492 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7496 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7499 MUTEX_ENTER(&rx_rpc_stats);
7500 MUTEX_ENTER(&peer->peer_lock);
7502 if (rxi_monitor_peerStats) {
7503 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7504 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7505 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7508 if (rxi_monitor_processStats) {
7509 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7510 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7511 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7514 MUTEX_EXIT(&peer->peer_lock);
7515 MUTEX_EXIT(&rx_rpc_stats);
7520 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7524 * IN callerVersion - the rpc stat version of the caller.
7526 * IN count - the number of entries to marshall.
7528 * IN stats - pointer to stats to be marshalled.
7530 * OUT ptr - Where to store the marshalled data.
7537 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7538 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7544 * We only support the first version
7546 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7547 *(ptr++) = stats->remote_peer;
7548 *(ptr++) = stats->remote_port;
7549 *(ptr++) = stats->remote_is_server;
7550 *(ptr++) = stats->interfaceId;
7551 *(ptr++) = stats->func_total;
7552 *(ptr++) = stats->func_index;
7553 *(ptr++) = hgethi(stats->invocations);
7554 *(ptr++) = hgetlo(stats->invocations);
7555 *(ptr++) = hgethi(stats->bytes_sent);
7556 *(ptr++) = hgetlo(stats->bytes_sent);
7557 *(ptr++) = hgethi(stats->bytes_rcvd);
7558 *(ptr++) = hgetlo(stats->bytes_rcvd);
7559 *(ptr++) = stats->queue_time_sum.sec;
7560 *(ptr++) = stats->queue_time_sum.usec;
7561 *(ptr++) = stats->queue_time_sum_sqr.sec;
7562 *(ptr++) = stats->queue_time_sum_sqr.usec;
7563 *(ptr++) = stats->queue_time_min.sec;
7564 *(ptr++) = stats->queue_time_min.usec;
7565 *(ptr++) = stats->queue_time_max.sec;
7566 *(ptr++) = stats->queue_time_max.usec;
7567 *(ptr++) = stats->execution_time_sum.sec;
7568 *(ptr++) = stats->execution_time_sum.usec;
7569 *(ptr++) = stats->execution_time_sum_sqr.sec;
7570 *(ptr++) = stats->execution_time_sum_sqr.usec;
7571 *(ptr++) = stats->execution_time_min.sec;
7572 *(ptr++) = stats->execution_time_min.usec;
7573 *(ptr++) = stats->execution_time_max.sec;
7574 *(ptr++) = stats->execution_time_max.usec;
7580 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7585 * IN callerVersion - the rpc stat version of the caller
7587 * OUT myVersion - the rpc stat version of this function
7589 * OUT clock_sec - local time seconds
7591 * OUT clock_usec - local time microseconds
7593 * OUT allocSize - the number of bytes allocated to contain stats
7595 * OUT statCount - the number stats retrieved from this process.
7597 * OUT stats - the actual stats retrieved from this process.
7601 * Returns void. If successful, stats will != NULL.
7605 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7606 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7607 size_t * allocSize, afs_uint32 * statCount,
7608 afs_uint32 ** stats)
7618 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7621 * Check to see if stats are enabled
7624 MUTEX_ENTER(&rx_rpc_stats);
7625 if (!rxi_monitor_processStats) {
7626 MUTEX_EXIT(&rx_rpc_stats);
7630 clock_GetTime(&now);
7631 *clock_sec = now.sec;
7632 *clock_usec = now.usec;
7635 * Allocate the space based upon the caller version
7637 * If the client is at an older version than we are,
7638 * we return the statistic data in the older data format, but
7639 * we still return our version number so the client knows we
7640 * are maintaining more data than it can retrieve.
7643 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7644 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7645 *statCount = rxi_rpc_process_stat_cnt;
7648 * This can't happen yet, but in the future version changes
7649 * can be handled by adding additional code here
7653 if (space > (size_t) 0) {
7655 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7658 rx_interface_stat_p rpc_stat, nrpc_stat;
7662 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7664 * Copy the data based upon the caller version
7666 rx_MarshallProcessRPCStats(callerVersion,
7667 rpc_stat->stats[0].func_total,
7668 rpc_stat->stats, &ptr);
7674 MUTEX_EXIT(&rx_rpc_stats);
7679 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7683 * IN callerVersion - the rpc stat version of the caller
7685 * OUT myVersion - the rpc stat version of this function
7687 * OUT clock_sec - local time seconds
7689 * OUT clock_usec - local time microseconds
7691 * OUT allocSize - the number of bytes allocated to contain stats
7693 * OUT statCount - the number of stats retrieved from the individual
7696 * OUT stats - the actual stats retrieved from the individual peer structures.
7700 * Returns void. If successful, stats will != NULL.
7704 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7705 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7706 size_t * allocSize, afs_uint32 * statCount,
7707 afs_uint32 ** stats)
7717 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7720 * Check to see if stats are enabled
7723 MUTEX_ENTER(&rx_rpc_stats);
7724 if (!rxi_monitor_peerStats) {
7725 MUTEX_EXIT(&rx_rpc_stats);
7729 clock_GetTime(&now);
7730 *clock_sec = now.sec;
7731 *clock_usec = now.usec;
7734 * Allocate the space based upon the caller version
7736 * If the client is at an older version than we are,
7737 * we return the statistic data in the older data format, but
7738 * we still return our version number so the client knows we
7739 * are maintaining more data than it can retrieve.
7742 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7743 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7744 *statCount = rxi_rpc_peer_stat_cnt;
7747 * This can't happen yet, but in the future version changes
7748 * can be handled by adding additional code here
7752 if (space > (size_t) 0) {
7754 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7757 rx_interface_stat_p rpc_stat, nrpc_stat;
7761 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7763 * We have to fix the offset of rpc_stat since we are
7764 * keeping this structure on two rx_queues. The rx_queue
7765 * package assumes that the rx_queue member is the first
7766 * member of the structure. That is, rx_queue assumes that
7767 * any one item is only on one queue at a time. We are
7768 * breaking that assumption and so we have to do a little
7769 * math to fix our pointers.
7772 fix_offset = (char *)rpc_stat;
7773 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7774 rpc_stat = (rx_interface_stat_p) fix_offset;
7777 * Copy the data based upon the caller version
7779 rx_MarshallProcessRPCStats(callerVersion,
7780 rpc_stat->stats[0].func_total,
7781 rpc_stat->stats, &ptr);
7787 MUTEX_EXIT(&rx_rpc_stats);
7792 * rx_FreeRPCStats - free memory allocated by
7793 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7797 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7798 * rx_RetrievePeerRPCStats
7800 * IN allocSize - the number of bytes in stats.
7808 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7810 rxi_Free(stats, allocSize);
7814 * rx_queryProcessRPCStats - see if process rpc stat collection is
7815 * currently enabled.
7821 * Returns 0 if stats are not enabled != 0 otherwise
7825 rx_queryProcessRPCStats(void)
7828 MUTEX_ENTER(&rx_rpc_stats);
7829 rc = rxi_monitor_processStats;
7830 MUTEX_EXIT(&rx_rpc_stats);
7835 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7841 * Returns 0 if stats are not enabled != 0 otherwise
7845 rx_queryPeerRPCStats(void)
7848 MUTEX_ENTER(&rx_rpc_stats);
7849 rc = rxi_monitor_peerStats;
7850 MUTEX_EXIT(&rx_rpc_stats);
7855 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7865 rx_enableProcessRPCStats(void)
7867 MUTEX_ENTER(&rx_rpc_stats);
7868 rx_enable_stats = 1;
7869 rxi_monitor_processStats = 1;
7870 MUTEX_EXIT(&rx_rpc_stats);
7874 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7884 rx_enablePeerRPCStats(void)
7886 MUTEX_ENTER(&rx_rpc_stats);
7887 rx_enable_stats = 1;
7888 rxi_monitor_peerStats = 1;
7889 MUTEX_EXIT(&rx_rpc_stats);
7893 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7903 rx_disableProcessRPCStats(void)
7905 rx_interface_stat_p rpc_stat, nrpc_stat;
7908 MUTEX_ENTER(&rx_rpc_stats);
7911 * Turn off process statistics and if peer stats is also off, turn
7915 rxi_monitor_processStats = 0;
7916 if (rxi_monitor_peerStats == 0) {
7917 rx_enable_stats = 0;
7920 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7921 unsigned int num_funcs = 0;
7924 queue_Remove(rpc_stat);
7925 num_funcs = rpc_stat->stats[0].func_total;
7927 sizeof(rx_interface_stat_t) +
7928 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7930 rxi_Free(rpc_stat, space);
7931 rxi_rpc_process_stat_cnt -= num_funcs;
7933 MUTEX_EXIT(&rx_rpc_stats);
7937 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7947 rx_disablePeerRPCStats(void)
7949 struct rx_peer **peer_ptr, **peer_end;
7952 MUTEX_ENTER(&rx_rpc_stats);
7955 * Turn off peer statistics and if process stats is also off, turn
7959 rxi_monitor_peerStats = 0;
7960 if (rxi_monitor_processStats == 0) {
7961 rx_enable_stats = 0;
7964 MUTEX_ENTER(&rx_peerHashTable_lock);
7965 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7966 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7968 struct rx_peer *peer, *next, *prev;
7969 for (prev = peer = *peer_ptr; peer; peer = next) {
7971 code = MUTEX_TRYENTER(&peer->peer_lock);
7973 rx_interface_stat_p rpc_stat, nrpc_stat;
7976 (&peer->rpcStats, rpc_stat, nrpc_stat,
7977 rx_interface_stat)) {
7978 unsigned int num_funcs = 0;
7981 queue_Remove(&rpc_stat->queue_header);
7982 queue_Remove(&rpc_stat->all_peers);
7983 num_funcs = rpc_stat->stats[0].func_total;
7985 sizeof(rx_interface_stat_t) +
7986 rpc_stat->stats[0].func_total *
7987 sizeof(rx_function_entry_v1_t);
7989 rxi_Free(rpc_stat, space);
7990 rxi_rpc_peer_stat_cnt -= num_funcs;
7992 MUTEX_EXIT(&peer->peer_lock);
7993 if (prev == *peer_ptr) {
8003 MUTEX_EXIT(&rx_peerHashTable_lock);
8004 MUTEX_EXIT(&rx_rpc_stats);
8008 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8013 * IN clearFlag - flag indicating which stats to clear
8021 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8023 rx_interface_stat_p rpc_stat, nrpc_stat;
8025 MUTEX_ENTER(&rx_rpc_stats);
8027 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8028 unsigned int num_funcs = 0, i;
8029 num_funcs = rpc_stat->stats[0].func_total;
8030 for (i = 0; i < num_funcs; i++) {
8031 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8032 hzero(rpc_stat->stats[i].invocations);
8034 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8035 hzero(rpc_stat->stats[i].bytes_sent);
8037 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8038 hzero(rpc_stat->stats[i].bytes_rcvd);
8040 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8041 rpc_stat->stats[i].queue_time_sum.sec = 0;
8042 rpc_stat->stats[i].queue_time_sum.usec = 0;
8044 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8045 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8046 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8048 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8049 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8050 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8052 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8053 rpc_stat->stats[i].queue_time_max.sec = 0;
8054 rpc_stat->stats[i].queue_time_max.usec = 0;
8056 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8057 rpc_stat->stats[i].execution_time_sum.sec = 0;
8058 rpc_stat->stats[i].execution_time_sum.usec = 0;
8060 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8061 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8062 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8064 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8065 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8066 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8068 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8069 rpc_stat->stats[i].execution_time_max.sec = 0;
8070 rpc_stat->stats[i].execution_time_max.usec = 0;
8075 MUTEX_EXIT(&rx_rpc_stats);
8079 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8084 * IN clearFlag - flag indicating which stats to clear
8092 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8094 rx_interface_stat_p rpc_stat, nrpc_stat;
8096 MUTEX_ENTER(&rx_rpc_stats);
8098 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8099 unsigned int num_funcs = 0, i;
8102 * We have to fix the offset of rpc_stat since we are
8103 * keeping this structure on two rx_queues. The rx_queue
8104 * package assumes that the rx_queue member is the first
8105 * member of the structure. That is, rx_queue assumes that
8106 * any one item is only on one queue at a time. We are
8107 * breaking that assumption and so we have to do a little
8108 * math to fix our pointers.
8111 fix_offset = (char *)rpc_stat;
8112 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8113 rpc_stat = (rx_interface_stat_p) fix_offset;
8115 num_funcs = rpc_stat->stats[0].func_total;
8116 for (i = 0; i < num_funcs; i++) {
8117 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8118 hzero(rpc_stat->stats[i].invocations);
8120 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8121 hzero(rpc_stat->stats[i].bytes_sent);
8123 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8124 hzero(rpc_stat->stats[i].bytes_rcvd);
8126 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8127 rpc_stat->stats[i].queue_time_sum.sec = 0;
8128 rpc_stat->stats[i].queue_time_sum.usec = 0;
8130 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8131 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8132 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8134 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8135 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8136 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8138 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8139 rpc_stat->stats[i].queue_time_max.sec = 0;
8140 rpc_stat->stats[i].queue_time_max.usec = 0;
8142 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8143 rpc_stat->stats[i].execution_time_sum.sec = 0;
8144 rpc_stat->stats[i].execution_time_sum.usec = 0;
8146 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8147 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8148 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8150 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8151 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8152 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8154 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8155 rpc_stat->stats[i].execution_time_max.sec = 0;
8156 rpc_stat->stats[i].execution_time_max.usec = 0;
8161 MUTEX_EXIT(&rx_rpc_stats);
8165 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8166 * is authorized to enable/disable/clear RX statistics.
8168 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8171 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8173 rxi_rxstat_userok = proc;
8177 rx_RxStatUserOk(struct rx_call *call)
8179 if (!rxi_rxstat_userok)
8181 return rxi_rxstat_userok(call);
8186 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8187 * function in the MSVC runtime DLL (msvcrt.dll).
8189 * Note: the system serializes calls to this function.
8192 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8193 DWORD reason, /* reason function is being called */
8194 LPVOID reserved) /* reserved for future use */
8197 case DLL_PROCESS_ATTACH:
8198 /* library is being attached to a process */
8202 case DLL_PROCESS_DETACH:
8209 #endif /* AFS_NT40_ENV */
8212 int rx_DumpCalls(FILE *outputFile, char *cookie)
8214 #ifdef RXDEBUG_PACKET
8215 #ifdef KDUMP_RX_LOCK
8216 struct rx_call_rx_lock *c;
8223 #define RXDPRINTF sprintf
8224 #define RXDPRINTOUT output
8226 #define RXDPRINTF fprintf
8227 #define RXDPRINTOUT outputFile
8230 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8232 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8235 for (c = rx_allCallsp; c; c = c->allNextp) {
8236 u_short rqc, tqc, iovqc;
8237 struct rx_packet *p, *np;
8239 MUTEX_ENTER(&c->lock);
8240 queue_Count(&c->rq, p, np, rx_packet, rqc);
8241 queue_Count(&c->tq, p, np, rx_packet, tqc);
8242 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8244 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, "
8245 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8246 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8247 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8248 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8249 #ifdef RX_ENABLE_LOCKS
8252 #ifdef RX_REFCOUNT_CHECK
8253 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8254 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8257 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,
8258 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8259 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8260 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8261 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8262 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8263 #ifdef RX_ENABLE_LOCKS
8264 , (afs_uint32)c->refCount
8266 #ifdef RX_REFCOUNT_CHECK
8267 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8270 MUTEX_EXIT(&c->lock);
8273 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8276 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8278 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8280 #endif /* RXDEBUG_PACKET */