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"
59 #endif /* AFS_OSF_ENV */
61 #include "afs/sysincludes.h"
62 #include "afsincludes.h"
65 #include "rx_kmutex.h"
66 #include "rx_kernel.h"
70 #include "rx_globals.h"
72 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
73 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
74 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
76 extern afs_int32 afs_termState;
78 #include "sys/lockl.h"
79 #include "sys/lock_def.h"
80 #endif /* AFS_AIX41_ENV */
81 # include "rxgen_consts.h"
83 # include <sys/types.h>
93 # include <afs/afsutil.h>
94 # include <WINNT\afsreg.h>
96 # include <sys/socket.h>
97 # include <sys/file.h>
99 # include <sys/stat.h>
100 # include <netinet/in.h>
101 # include <sys/time.h>
104 # include "rx_user.h"
105 # include "rx_clock.h"
106 # include "rx_queue.h"
107 # include "rx_globals.h"
108 # include "rx_trace.h"
109 # include <afs/rxgen_consts.h>
113 #ifdef AFS_PTHREAD_ENV
115 int (*registerProgram) (pid_t, char *) = 0;
116 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
119 int (*registerProgram) (PROCESS, char *) = 0;
120 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
124 /* Local static routines */
125 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
126 #ifdef RX_ENABLE_LOCKS
127 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
130 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
132 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
133 afs_int32 rxi_start_in_error;
135 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
138 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
139 * currently allocated within rx. This number is used to allocate the
140 * memory required to return the statistics when queried.
141 * Protected by the rx_rpc_stats mutex.
144 static unsigned int rxi_rpc_peer_stat_cnt;
147 * rxi_rpc_process_stat_cnt counts the total number of local process stat
148 * structures currently allocated within rx. The number is used to allocate
149 * the memory required to return the statistics when queried.
150 * Protected by the rx_rpc_stats mutex.
153 static unsigned int rxi_rpc_process_stat_cnt;
155 #if !defined(offsetof)
156 #include <stddef.h> /* for definition of offsetof() */
159 #ifdef AFS_PTHREAD_ENV
163 * Use procedural initialization of mutexes/condition variables
167 extern afs_kmutex_t rx_stats_mutex;
168 extern afs_kmutex_t rx_waiting_mutex;
169 extern afs_kmutex_t rx_quota_mutex;
170 extern afs_kmutex_t rx_pthread_mutex;
171 extern afs_kmutex_t rx_packets_mutex;
172 extern afs_kmutex_t des_init_mutex;
173 extern afs_kmutex_t des_random_mutex;
174 extern afs_kmutex_t rx_clock_mutex;
175 extern afs_kmutex_t rxi_connCacheMutex;
176 extern afs_kmutex_t rx_event_mutex;
177 extern afs_kmutex_t osi_malloc_mutex;
178 extern afs_kmutex_t event_handler_mutex;
179 extern afs_kmutex_t listener_mutex;
180 extern afs_kmutex_t rx_if_init_mutex;
181 extern afs_kmutex_t rx_if_mutex;
182 extern afs_kmutex_t rxkad_client_uid_mutex;
183 extern afs_kmutex_t rxkad_random_mutex;
185 extern afs_kcondvar_t rx_event_handler_cond;
186 extern afs_kcondvar_t rx_listener_cond;
188 static afs_kmutex_t epoch_mutex;
189 static afs_kmutex_t rx_init_mutex;
190 static afs_kmutex_t rx_debug_mutex;
191 static afs_kmutex_t rx_rpc_stats;
194 rxi_InitPthread(void)
196 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_waiting_mutex, "waiting", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
217 assert(pthread_cond_init
218 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
219 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
221 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
222 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
224 rxkad_global_stats_init();
226 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
228 #ifdef RX_ENABLE_LOCKS
231 #endif /* RX_LOCKS_DB */
232 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
233 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
235 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
237 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
239 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
241 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
242 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
243 #endif /* RX_ENABLE_LOCKS */
246 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
247 #define INIT_PTHREAD_LOCKS \
248 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
250 * The rx_stats_mutex mutex protects the following global variables:
251 * rxi_lowConnRefCount
252 * rxi_lowPeerRefCount
261 * The rx_quota_mutex mutex protects the following global variables:
269 * The rx_freePktQ_lock protects the following global variables:
274 * The rx_packets_mutex mutex protects the following global variables:
282 * The rx_pthread_mutex mutex protects the following global variables:
286 #define INIT_PTHREAD_LOCKS
290 /* Variables for handling the minProcs implementation. availProcs gives the
291 * number of threads available in the pool at this moment (not counting dudes
292 * executing right now). totalMin gives the total number of procs required
293 * for handling all minProcs requests. minDeficit is a dynamic variable
294 * tracking the # of procs required to satisfy all of the remaining minProcs
296 * For fine grain locking to work, the quota check and the reservation of
297 * a server thread has to come while rxi_availProcs and rxi_minDeficit
298 * are locked. To this end, the code has been modified under #ifdef
299 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
300 * same time. A new function, ReturnToServerPool() returns the allocation.
302 * A call can be on several queue's (but only one at a time). When
303 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
304 * that no one else is touching the queue. To this end, we store the address
305 * of the queue lock in the call structure (under the call lock) when we
306 * put the call on a queue, and we clear the call_queue_lock when the
307 * call is removed from a queue (once the call lock has been obtained).
308 * This allows rxi_ResetCall to safely synchronize with others wishing
309 * to manipulate the queue.
312 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
313 static afs_kmutex_t rx_rpc_stats;
314 void rxi_StartUnlocked(struct rxevent *event, void *call,
315 void *arg1, int istack);
318 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
319 ** pretty good that the next packet coming in is from the same connection
320 ** as the last packet, since we're send multiple packets in a transmit window.
322 struct rx_connection *rxLastConn = 0;
324 #ifdef RX_ENABLE_LOCKS
325 /* The locking hierarchy for rx fine grain locking is composed of these
328 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
329 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
330 * call->lock - locks call data fields.
331 * These are independent of each other:
332 * rx_freeCallQueue_lock
337 * serverQueueEntry->lock
338 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
340 * peer->lock - locks peer data fields.
341 * conn_data_lock - that more than one thread is not updating a conn data
342 * field at the same time.
350 * Do we need a lock to protect the peer field in the conn structure?
351 * conn->peer was previously a constant for all intents and so has no
352 * lock protecting this field. The multihomed client delta introduced
353 * a RX code change : change the peer field in the connection structure
354 * to that remote interface from which the last packet for this
355 * connection was sent out. This may become an issue if further changes
358 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
359 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
361 /* rxdb_fileID is used to identify the lock location, along with line#. */
362 static int rxdb_fileID = RXDB_FILE_RX;
363 #endif /* RX_LOCKS_DB */
364 #else /* RX_ENABLE_LOCKS */
365 #define SET_CALL_QUEUE_LOCK(C, L)
366 #define CLEAR_CALL_QUEUE_LOCK(C)
367 #endif /* RX_ENABLE_LOCKS */
368 struct rx_serverQueueEntry *rx_waitForPacket = 0;
369 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
371 /* ------------Exported Interfaces------------- */
373 /* This function allows rxkad to set the epoch to a suitably random number
374 * which rx_NewConnection will use in the future. The principle purpose is to
375 * get rxnull connections to use the same epoch as the rxkad connections do, at
376 * least once the first rxkad connection is established. This is important now
377 * that the host/port addresses aren't used in FindConnection: the uniqueness
378 * of epoch/cid matters and the start time won't do. */
380 #ifdef AFS_PTHREAD_ENV
382 * This mutex protects the following global variables:
386 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
387 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
391 #endif /* AFS_PTHREAD_ENV */
394 rx_SetEpoch(afs_uint32 epoch)
401 /* Initialize rx. A port number may be mentioned, in which case this
402 * becomes the default port number for any service installed later.
403 * If 0 is provided for the port number, a random port will be chosen
404 * by the kernel. Whether this will ever overlap anything in
405 * /etc/services is anybody's guess... Returns 0 on success, -1 on
410 int rxinit_status = 1;
411 #ifdef AFS_PTHREAD_ENV
413 * This mutex protects the following global variables:
417 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
418 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
421 #define UNLOCK_RX_INIT
425 rx_InitHost(u_int host, u_int port)
432 char *htable, *ptable;
439 if (rxinit_status == 0) {
440 tmp_status = rxinit_status;
442 return tmp_status; /* Already started; return previous error code. */
448 if (afs_winsockInit() < 0)
454 * Initialize anything necessary to provide a non-premptive threading
457 rxi_InitializeThreadSupport();
460 /* Allocate and initialize a socket for client and perhaps server
463 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
464 if (rx_socket == OSI_NULLSOCKET) {
468 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
471 #endif /* RX_LOCKS_DB */
472 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_waiting_mutex, "rx_waiting_mutex", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
477 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
478 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
479 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
480 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
482 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
484 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
486 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
488 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
489 #if defined(AFS_HPUX110_ENV)
491 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
492 #endif /* AFS_HPUX110_ENV */
493 #endif /* RX_ENABLE_LOCKS && KERNEL */
496 rx_connDeadTime = 12;
497 rx_tranquil = 0; /* reset flag */
498 memset(&rx_stats, 0, sizeof(struct rx_statistics));
500 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
501 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
502 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
503 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
504 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
505 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
507 /* Malloc up a bunch of packets & buffers */
509 queue_Init(&rx_freePacketQueue);
510 rxi_NeedMorePackets = FALSE;
511 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
513 /* enforce a minimum number of allocated packets */
514 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
515 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
517 /* allocate the initial free packet pool */
518 #ifdef RX_ENABLE_TSFPQ
519 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
520 #else /* RX_ENABLE_TSFPQ */
521 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
522 #endif /* RX_ENABLE_TSFPQ */
529 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
530 tv.tv_sec = clock_now.sec;
531 tv.tv_usec = clock_now.usec;
532 srand((unsigned int)tv.tv_usec);
539 #if defined(KERNEL) && !defined(UKERNEL)
540 /* Really, this should never happen in a real kernel */
543 struct sockaddr_in addr;
545 int addrlen = sizeof(addr);
547 socklen_t addrlen = sizeof(addr);
549 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
553 rx_port = addr.sin_port;
556 rx_stats.minRtt.sec = 9999999;
558 rx_SetEpoch(tv.tv_sec | 0x80000000);
560 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
561 * will provide a randomer value. */
563 MUTEX_ENTER(&rx_quota_mutex);
564 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
565 MUTEX_EXIT(&rx_quota_mutex);
566 /* *Slightly* random start time for the cid. This is just to help
567 * out with the hashing function at the peer */
568 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
569 rx_connHashTable = (struct rx_connection **)htable;
570 rx_peerHashTable = (struct rx_peer **)ptable;
572 rx_lastAckDelay.sec = 0;
573 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
574 rx_hardAckDelay.sec = 0;
575 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
576 rx_softAckDelay.sec = 0;
577 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
579 rxevent_Init(20, rxi_ReScheduleEvents);
581 /* Initialize various global queues */
582 queue_Init(&rx_idleServerQueue);
583 queue_Init(&rx_incomingCallQueue);
584 queue_Init(&rx_freeCallQueue);
586 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
587 /* Initialize our list of usable IP addresses. */
591 /* Start listener process (exact function is dependent on the
592 * implementation environment--kernel or user space) */
596 tmp_status = rxinit_status = 0;
604 return rx_InitHost(htonl(INADDR_ANY), port);
607 /* called with unincremented nRequestsRunning to see if it is OK to start
608 * a new thread in this service. Could be "no" for two reasons: over the
609 * max quota, or would prevent others from reaching their min quota.
611 #ifdef RX_ENABLE_LOCKS
612 /* This verion of QuotaOK reserves quota if it's ok while the
613 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
616 QuotaOK(struct rx_service *aservice)
618 /* check if over max quota */
619 if (aservice->nRequestsRunning >= aservice->maxProcs) {
623 /* under min quota, we're OK */
624 /* otherwise, can use only if there are enough to allow everyone
625 * to go to their min quota after this guy starts.
628 MUTEX_ENTER(&rx_quota_mutex);
629 if ((aservice->nRequestsRunning < aservice->minProcs)
630 || (rxi_availProcs > rxi_minDeficit)) {
631 aservice->nRequestsRunning++;
632 /* just started call in minProcs pool, need fewer to maintain
634 if (aservice->nRequestsRunning <= aservice->minProcs)
637 MUTEX_EXIT(&rx_quota_mutex);
640 MUTEX_EXIT(&rx_quota_mutex);
646 ReturnToServerPool(struct rx_service *aservice)
648 aservice->nRequestsRunning--;
649 MUTEX_ENTER(&rx_quota_mutex);
650 if (aservice->nRequestsRunning < aservice->minProcs)
653 MUTEX_EXIT(&rx_quota_mutex);
656 #else /* RX_ENABLE_LOCKS */
658 QuotaOK(struct rx_service *aservice)
661 /* under min quota, we're OK */
662 if (aservice->nRequestsRunning < aservice->minProcs)
665 /* check if over max quota */
666 if (aservice->nRequestsRunning >= aservice->maxProcs)
669 /* otherwise, can use only if there are enough to allow everyone
670 * to go to their min quota after this guy starts.
672 MUTEX_ENTER(&rx_quota_mutex);
673 if (rxi_availProcs > rxi_minDeficit)
675 MUTEX_EXIT(&rx_quota_mutex);
678 #endif /* RX_ENABLE_LOCKS */
681 /* Called by rx_StartServer to start up lwp's to service calls.
682 NExistingProcs gives the number of procs already existing, and which
683 therefore needn't be created. */
685 rxi_StartServerProcs(int nExistingProcs)
687 struct rx_service *service;
692 /* For each service, reserve N processes, where N is the "minimum"
693 * number of processes that MUST be able to execute a request in parallel,
694 * at any time, for that process. Also compute the maximum difference
695 * between any service's maximum number of processes that can run
696 * (i.e. the maximum number that ever will be run, and a guarantee
697 * that this number will run if other services aren't running), and its
698 * minimum number. The result is the extra number of processes that
699 * we need in order to provide the latter guarantee */
700 for (i = 0; i < RX_MAX_SERVICES; i++) {
702 service = rx_services[i];
703 if (service == (struct rx_service *)0)
705 nProcs += service->minProcs;
706 diff = service->maxProcs - service->minProcs;
710 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
711 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
712 for (i = 0; i < nProcs; i++) {
713 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
719 /* This routine is only required on Windows */
721 rx_StartClientThread(void)
723 #ifdef AFS_PTHREAD_ENV
725 pid = pthread_self();
726 #endif /* AFS_PTHREAD_ENV */
728 #endif /* AFS_NT40_ENV */
730 /* This routine must be called if any services are exported. If the
731 * donateMe flag is set, the calling process is donated to the server
734 rx_StartServer(int donateMe)
736 struct rx_service *service;
742 /* Start server processes, if necessary (exact function is dependent
743 * on the implementation environment--kernel or user space). DonateMe
744 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
745 * case, one less new proc will be created rx_StartServerProcs.
747 rxi_StartServerProcs(donateMe);
749 /* count up the # of threads in minProcs, and add set the min deficit to
750 * be that value, too.
752 for (i = 0; i < RX_MAX_SERVICES; i++) {
753 service = rx_services[i];
754 if (service == (struct rx_service *)0)
756 MUTEX_ENTER(&rx_quota_mutex);
757 rxi_totalMin += service->minProcs;
758 /* below works even if a thread is running, since minDeficit would
759 * still have been decremented and later re-incremented.
761 rxi_minDeficit += service->minProcs;
762 MUTEX_EXIT(&rx_quota_mutex);
765 /* Turn on reaping of idle server connections */
766 rxi_ReapConnections(NULL, NULL, NULL);
775 #ifdef AFS_PTHREAD_ENV
777 pid = afs_pointer_to_int(pthread_self());
778 #else /* AFS_PTHREAD_ENV */
780 LWP_CurrentProcess(&pid);
781 #endif /* AFS_PTHREAD_ENV */
783 sprintf(name, "srv_%d", ++nProcs);
785 (*registerProgram) (pid, name);
787 #endif /* AFS_NT40_ENV */
788 rx_ServerProc(NULL); /* Never returns */
790 #ifdef RX_ENABLE_TSFPQ
791 /* no use leaving packets around in this thread's local queue if
792 * it isn't getting donated to the server thread pool.
794 rxi_FlushLocalPacketsTSFPQ();
795 #endif /* RX_ENABLE_TSFPQ */
799 /* Create a new client connection to the specified service, using the
800 * specified security object to implement the security model for this
802 struct rx_connection *
803 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
804 struct rx_securityClass *securityObject,
805 int serviceSecurityIndex)
809 struct rx_connection *conn;
814 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
815 "serviceSecurityIndex %d)\n",
816 ntohl(shost), ntohs(sport), sservice, securityObject,
817 serviceSecurityIndex));
819 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
820 * the case of kmem_alloc? */
821 conn = rxi_AllocConnection();
822 #ifdef RX_ENABLE_LOCKS
823 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
824 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
825 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
828 MUTEX_ENTER(&rx_connHashTable_lock);
829 cid = (rx_nextCid += RX_MAXCALLS);
830 conn->type = RX_CLIENT_CONNECTION;
832 conn->epoch = rx_epoch;
833 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
834 conn->serviceId = sservice;
835 conn->securityObject = securityObject;
836 conn->securityData = (void *) 0;
837 conn->securityIndex = serviceSecurityIndex;
838 rx_SetConnDeadTime(conn, rx_connDeadTime);
839 rx_SetConnSecondsUntilNatPing(conn, 0);
840 conn->ackRate = RX_FAST_ACK_RATE;
842 conn->specific = NULL;
843 conn->challengeEvent = NULL;
844 conn->delayedAbortEvent = NULL;
845 conn->abortCount = 0;
847 for (i = 0; i < RX_MAXCALLS; i++) {
848 conn->twind[i] = rx_initSendWindow;
849 conn->rwind[i] = rx_initReceiveWindow;
852 RXS_NewConnection(securityObject, conn);
854 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
856 conn->refCount++; /* no lock required since only this thread knows... */
857 conn->next = rx_connHashTable[hashindex];
858 rx_connHashTable[hashindex] = conn;
860 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
861 MUTEX_EXIT(&rx_connHashTable_lock);
867 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
869 /* The idea is to set the dead time to a value that allows several
870 * keepalives to be dropped without timing out the connection. */
871 conn->secondsUntilDead = MAX(seconds, 6);
872 conn->secondsUntilPing = conn->secondsUntilDead / 6;
875 int rxi_lowPeerRefCount = 0;
876 int rxi_lowConnRefCount = 0;
879 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
880 * NOTE: must not be called with rx_connHashTable_lock held.
883 rxi_CleanupConnection(struct rx_connection *conn)
885 /* Notify the service exporter, if requested, that this connection
886 * is being destroyed */
887 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
888 (*conn->service->destroyConnProc) (conn);
890 /* Notify the security module that this connection is being destroyed */
891 RXS_DestroyConnection(conn->securityObject, conn);
893 /* If this is the last connection using the rx_peer struct, set its
894 * idle time to now. rxi_ReapConnections will reap it if it's still
895 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
897 MUTEX_ENTER(&rx_peerHashTable_lock);
898 if (conn->peer->refCount < 2) {
899 conn->peer->idleWhen = clock_Sec();
900 if (conn->peer->refCount < 1) {
901 conn->peer->refCount = 1;
902 if (rx_stats_active) {
903 MUTEX_ENTER(&rx_stats_mutex);
904 rxi_lowPeerRefCount++;
905 MUTEX_EXIT(&rx_stats_mutex);
909 conn->peer->refCount--;
910 MUTEX_EXIT(&rx_peerHashTable_lock);
914 if (conn->type == RX_SERVER_CONNECTION)
915 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
917 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
920 if (conn->specific) {
922 for (i = 0; i < conn->nSpecific; i++) {
923 if (conn->specific[i] && rxi_keyCreate_destructor[i])
924 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
925 conn->specific[i] = NULL;
927 free(conn->specific);
929 conn->specific = NULL;
933 MUTEX_DESTROY(&conn->conn_call_lock);
934 MUTEX_DESTROY(&conn->conn_data_lock);
935 CV_DESTROY(&conn->conn_call_cv);
937 rxi_FreeConnection(conn);
940 /* Destroy the specified connection */
942 rxi_DestroyConnection(struct rx_connection *conn)
944 MUTEX_ENTER(&rx_connHashTable_lock);
945 rxi_DestroyConnectionNoLock(conn);
946 /* conn should be at the head of the cleanup list */
947 if (conn == rx_connCleanup_list) {
948 rx_connCleanup_list = rx_connCleanup_list->next;
949 MUTEX_EXIT(&rx_connHashTable_lock);
950 rxi_CleanupConnection(conn);
952 #ifdef RX_ENABLE_LOCKS
954 MUTEX_EXIT(&rx_connHashTable_lock);
956 #endif /* RX_ENABLE_LOCKS */
960 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
962 struct rx_connection **conn_ptr;
964 struct rx_packet *packet;
971 MUTEX_ENTER(&conn->conn_data_lock);
972 if (conn->refCount > 0)
975 if (rx_stats_active) {
976 MUTEX_ENTER(&rx_stats_mutex);
977 rxi_lowConnRefCount++;
978 MUTEX_EXIT(&rx_stats_mutex);
982 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
983 /* Busy; wait till the last guy before proceeding */
984 MUTEX_EXIT(&conn->conn_data_lock);
989 /* If the client previously called rx_NewCall, but it is still
990 * waiting, treat this as a running call, and wait to destroy the
991 * connection later when the call completes. */
992 if ((conn->type == RX_CLIENT_CONNECTION)
993 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
994 conn->flags |= RX_CONN_DESTROY_ME;
995 MUTEX_EXIT(&conn->conn_data_lock);
999 MUTEX_EXIT(&conn->conn_data_lock);
1001 /* Check for extant references to this connection */
1002 for (i = 0; i < RX_MAXCALLS; i++) {
1003 struct rx_call *call = conn->call[i];
1006 if (conn->type == RX_CLIENT_CONNECTION) {
1007 MUTEX_ENTER(&call->lock);
1008 if (call->delayedAckEvent) {
1009 /* Push the final acknowledgment out now--there
1010 * won't be a subsequent call to acknowledge the
1011 * last reply packets */
1012 rxevent_Cancel(call->delayedAckEvent, call,
1013 RX_CALL_REFCOUNT_DELAY);
1014 if (call->state == RX_STATE_PRECALL
1015 || call->state == RX_STATE_ACTIVE) {
1016 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1018 rxi_AckAll(NULL, call, 0);
1021 MUTEX_EXIT(&call->lock);
1025 #ifdef RX_ENABLE_LOCKS
1027 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1028 MUTEX_EXIT(&conn->conn_data_lock);
1030 /* Someone is accessing a packet right now. */
1034 #endif /* RX_ENABLE_LOCKS */
1037 /* Don't destroy the connection if there are any call
1038 * structures still in use */
1039 MUTEX_ENTER(&conn->conn_data_lock);
1040 conn->flags |= RX_CONN_DESTROY_ME;
1041 MUTEX_EXIT(&conn->conn_data_lock);
1046 if (conn->natKeepAliveEvent) {
1047 rxi_NatKeepAliveOff(conn);
1050 if (conn->delayedAbortEvent) {
1051 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1052 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1054 MUTEX_ENTER(&conn->conn_data_lock);
1055 rxi_SendConnectionAbort(conn, packet, 0, 1);
1056 MUTEX_EXIT(&conn->conn_data_lock);
1057 rxi_FreePacket(packet);
1061 /* Remove from connection hash table before proceeding */
1063 &rx_connHashTable[CONN_HASH
1064 (peer->host, peer->port, conn->cid, conn->epoch,
1066 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1067 if (*conn_ptr == conn) {
1068 *conn_ptr = conn->next;
1072 /* if the conn that we are destroying was the last connection, then we
1073 * clear rxLastConn as well */
1074 if (rxLastConn == conn)
1077 /* Make sure the connection is completely reset before deleting it. */
1078 /* get rid of pending events that could zap us later */
1079 if (conn->challengeEvent)
1080 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1081 if (conn->checkReachEvent)
1082 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1083 if (conn->natKeepAliveEvent)
1084 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1086 /* Add the connection to the list of destroyed connections that
1087 * need to be cleaned up. This is necessary to avoid deadlocks
1088 * in the routines we call to inform others that this connection is
1089 * being destroyed. */
1090 conn->next = rx_connCleanup_list;
1091 rx_connCleanup_list = conn;
1094 /* Externally available version */
1096 rx_DestroyConnection(struct rx_connection *conn)
1101 rxi_DestroyConnection(conn);
1106 rx_GetConnection(struct rx_connection *conn)
1111 MUTEX_ENTER(&conn->conn_data_lock);
1113 MUTEX_EXIT(&conn->conn_data_lock);
1117 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1118 /* Wait for the transmit queue to no longer be busy.
1119 * requires the call->lock to be held */
1120 static void rxi_WaitforTQBusy(struct rx_call *call) {
1121 while (call->flags & RX_CALL_TQ_BUSY) {
1122 call->flags |= RX_CALL_TQ_WAIT;
1124 #ifdef RX_ENABLE_LOCKS
1125 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1126 CV_WAIT(&call->cv_tq, &call->lock);
1127 #else /* RX_ENABLE_LOCKS */
1128 osi_rxSleep(&call->tq);
1129 #endif /* RX_ENABLE_LOCKS */
1131 if (call->tqWaiters == 0) {
1132 call->flags &= ~RX_CALL_TQ_WAIT;
1138 /* Start a new rx remote procedure call, on the specified connection.
1139 * If wait is set to 1, wait for a free call channel; otherwise return
1140 * 0. Maxtime gives the maximum number of seconds this call may take,
1141 * after rx_NewCall returns. After this time interval, a call to any
1142 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1143 * For fine grain locking, we hold the conn_call_lock in order to
1144 * to ensure that we don't get signalle after we found a call in an active
1145 * state and before we go to sleep.
1148 rx_NewCall(struct rx_connection *conn)
1151 struct rx_call *call;
1152 struct clock queueTime;
1156 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1159 clock_GetTime(&queueTime);
1161 * Check if there are others waiting for a new call.
1162 * If so, let them go first to avoid starving them.
1163 * This is a fairly simple scheme, and might not be
1164 * a complete solution for large numbers of waiters.
1166 * makeCallWaiters keeps track of the number of
1167 * threads waiting to make calls and the
1168 * RX_CONN_MAKECALL_WAITING flag bit is used to
1169 * indicate that there are indeed calls waiting.
1170 * The flag is set when the waiter is incremented.
1171 * It is only cleared when makeCallWaiters is 0.
1172 * This prevents us from accidently destroying the
1173 * connection while it is potentially about to be used.
1175 MUTEX_ENTER(&conn->conn_call_lock);
1176 MUTEX_ENTER(&conn->conn_data_lock);
1177 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1178 conn->flags |= RX_CONN_MAKECALL_WAITING;
1179 conn->makeCallWaiters++;
1180 MUTEX_EXIT(&conn->conn_data_lock);
1182 #ifdef RX_ENABLE_LOCKS
1183 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1187 MUTEX_ENTER(&conn->conn_data_lock);
1188 conn->makeCallWaiters--;
1189 if (conn->makeCallWaiters == 0)
1190 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1193 /* We are now the active thread in rx_NewCall */
1194 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1195 MUTEX_EXIT(&conn->conn_data_lock);
1200 for (i = 0; i < RX_MAXCALLS; i++) {
1201 call = conn->call[i];
1203 if (call->state == RX_STATE_DALLY) {
1204 MUTEX_ENTER(&call->lock);
1205 if (call->state == RX_STATE_DALLY) {
1207 * We are setting the state to RX_STATE_RESET to
1208 * ensure that no one else will attempt to use this
1209 * call once we drop the conn->conn_call_lock and
1210 * call->lock. We must drop the conn->conn_call_lock
1211 * before calling rxi_ResetCall because the process
1212 * of clearing the transmit queue can block for an
1213 * extended period of time. If we block while holding
1214 * the conn->conn_call_lock, then all rx_EndCall
1215 * processing will block as well. This has a detrimental
1216 * effect on overall system performance.
1218 call->state = RX_STATE_RESET;
1219 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1220 MUTEX_EXIT(&conn->conn_call_lock);
1221 rxi_ResetCall(call, 0);
1222 (*call->callNumber)++;
1223 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1227 * If we failed to be able to safely obtain the
1228 * conn->conn_call_lock we will have to drop the
1229 * call->lock to avoid a deadlock. When the call->lock
1230 * is released the state of the call can change. If it
1231 * is no longer RX_STATE_RESET then some other thread is
1234 MUTEX_EXIT(&call->lock);
1235 MUTEX_ENTER(&conn->conn_call_lock);
1236 MUTEX_ENTER(&call->lock);
1238 if (call->state == RX_STATE_RESET)
1242 * If we get here it means that after dropping
1243 * the conn->conn_call_lock and call->lock that
1244 * the call is no longer ours. If we can't find
1245 * a free call in the remaining slots we should
1246 * not go immediately to RX_CONN_MAKECALL_WAITING
1247 * because by dropping the conn->conn_call_lock
1248 * we have given up synchronization with rx_EndCall.
1249 * Instead, cycle through one more time to see if
1250 * we can find a call that can call our own.
1252 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1255 MUTEX_EXIT(&call->lock);
1258 /* rxi_NewCall returns with mutex locked */
1259 call = rxi_NewCall(conn, i);
1260 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1264 if (i < RX_MAXCALLS) {
1270 MUTEX_ENTER(&conn->conn_data_lock);
1271 conn->flags |= RX_CONN_MAKECALL_WAITING;
1272 conn->makeCallWaiters++;
1273 MUTEX_EXIT(&conn->conn_data_lock);
1275 #ifdef RX_ENABLE_LOCKS
1276 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1280 MUTEX_ENTER(&conn->conn_data_lock);
1281 conn->makeCallWaiters--;
1282 if (conn->makeCallWaiters == 0)
1283 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1284 MUTEX_EXIT(&conn->conn_data_lock);
1286 /* Client is initially in send mode */
1287 call->state = RX_STATE_ACTIVE;
1288 call->error = conn->error;
1290 call->mode = RX_MODE_ERROR;
1292 call->mode = RX_MODE_SENDING;
1294 /* remember start time for call in case we have hard dead time limit */
1295 call->queueTime = queueTime;
1296 clock_GetTime(&call->startTime);
1297 hzero(call->bytesSent);
1298 hzero(call->bytesRcvd);
1300 /* Turn on busy protocol. */
1301 rxi_KeepAliveOn(call);
1303 /* Attempt MTU discovery */
1304 rxi_GrowMTUOn(call);
1307 * We are no longer the active thread in rx_NewCall
1309 MUTEX_ENTER(&conn->conn_data_lock);
1310 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1311 MUTEX_EXIT(&conn->conn_data_lock);
1314 * Wake up anyone else who might be giving us a chance to
1315 * run (see code above that avoids resource starvation).
1317 #ifdef RX_ENABLE_LOCKS
1318 CV_BROADCAST(&conn->conn_call_cv);
1322 MUTEX_EXIT(&conn->conn_call_lock);
1324 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1325 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1326 osi_Panic("rx_NewCall call about to be used without an empty tq");
1328 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1330 MUTEX_EXIT(&call->lock);
1333 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1338 rxi_HasActiveCalls(struct rx_connection *aconn)
1341 struct rx_call *tcall;
1345 for (i = 0; i < RX_MAXCALLS; i++) {
1346 if ((tcall = aconn->call[i])) {
1347 if ((tcall->state == RX_STATE_ACTIVE)
1348 || (tcall->state == RX_STATE_PRECALL)) {
1359 rxi_GetCallNumberVector(struct rx_connection *aconn,
1360 afs_int32 * aint32s)
1363 struct rx_call *tcall;
1367 for (i = 0; i < RX_MAXCALLS; i++) {
1368 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1369 aint32s[i] = aconn->callNumber[i] + 1;
1371 aint32s[i] = aconn->callNumber[i];
1378 rxi_SetCallNumberVector(struct rx_connection *aconn,
1379 afs_int32 * aint32s)
1382 struct rx_call *tcall;
1386 for (i = 0; i < RX_MAXCALLS; i++) {
1387 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1388 aconn->callNumber[i] = aint32s[i] - 1;
1390 aconn->callNumber[i] = aint32s[i];
1396 /* Advertise a new service. A service is named locally by a UDP port
1397 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1400 char *serviceName; Name for identification purposes (e.g. the
1401 service name might be used for probing for
1404 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1405 char *serviceName, struct rx_securityClass **securityObjects,
1406 int nSecurityObjects,
1407 afs_int32(*serviceProc) (struct rx_call * acall))
1409 osi_socket socket = OSI_NULLSOCKET;
1410 struct rx_service *tservice;
1416 if (serviceId == 0) {
1418 "rx_NewService: service id for service %s is not non-zero.\n",
1425 "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",
1433 tservice = rxi_AllocService();
1436 #ifdef RX_ENABLE_LOCKS
1437 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1440 for (i = 0; i < RX_MAX_SERVICES; i++) {
1441 struct rx_service *service = rx_services[i];
1443 if (port == service->servicePort && host == service->serviceHost) {
1444 if (service->serviceId == serviceId) {
1445 /* The identical service has already been
1446 * installed; if the caller was intending to
1447 * change the security classes used by this
1448 * service, he/she loses. */
1450 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1451 serviceName, serviceId, service->serviceName);
1453 rxi_FreeService(tservice);
1456 /* Different service, same port: re-use the socket
1457 * which is bound to the same port */
1458 socket = service->socket;
1461 if (socket == OSI_NULLSOCKET) {
1462 /* If we don't already have a socket (from another
1463 * service on same port) get a new one */
1464 socket = rxi_GetHostUDPSocket(host, port);
1465 if (socket == OSI_NULLSOCKET) {
1467 rxi_FreeService(tservice);
1472 service->socket = socket;
1473 service->serviceHost = host;
1474 service->servicePort = port;
1475 service->serviceId = serviceId;
1476 service->serviceName = serviceName;
1477 service->nSecurityObjects = nSecurityObjects;
1478 service->securityObjects = securityObjects;
1479 service->minProcs = 0;
1480 service->maxProcs = 1;
1481 service->idleDeadTime = 60;
1482 service->idleDeadErr = 0;
1483 service->connDeadTime = rx_connDeadTime;
1484 service->executeRequestProc = serviceProc;
1485 service->checkReach = 0;
1486 service->nSpecific = 0;
1487 service->specific = NULL;
1488 rx_services[i] = service; /* not visible until now */
1494 rxi_FreeService(tservice);
1495 (osi_Msg "rx_NewService: cannot support > %d services\n",
1500 /* Set configuration options for all of a service's security objects */
1503 rx_SetSecurityConfiguration(struct rx_service *service,
1504 rx_securityConfigVariables type,
1508 for (i = 0; i<service->nSecurityObjects; i++) {
1509 if (service->securityObjects[i]) {
1510 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1518 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1519 struct rx_securityClass **securityObjects, int nSecurityObjects,
1520 afs_int32(*serviceProc) (struct rx_call * acall))
1522 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1525 /* Generic request processing loop. This routine should be called
1526 * by the implementation dependent rx_ServerProc. If socketp is
1527 * non-null, it will be set to the file descriptor that this thread
1528 * is now listening on. If socketp is null, this routine will never
1531 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1533 struct rx_call *call;
1535 struct rx_service *tservice = NULL;
1542 call = rx_GetCall(threadID, tservice, socketp);
1543 if (socketp && *socketp != OSI_NULLSOCKET) {
1544 /* We are now a listener thread */
1549 /* if server is restarting( typically smooth shutdown) then do not
1550 * allow any new calls.
1553 if (rx_tranquil && (call != NULL)) {
1557 MUTEX_ENTER(&call->lock);
1559 rxi_CallError(call, RX_RESTARTING);
1560 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1562 MUTEX_EXIT(&call->lock);
1566 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1567 #ifdef RX_ENABLE_LOCKS
1569 #endif /* RX_ENABLE_LOCKS */
1570 afs_termState = AFSOP_STOP_AFS;
1571 afs_osi_Wakeup(&afs_termState);
1572 #ifdef RX_ENABLE_LOCKS
1574 #endif /* RX_ENABLE_LOCKS */
1579 tservice = call->conn->service;
1581 if (tservice->beforeProc)
1582 (*tservice->beforeProc) (call);
1584 code = call->conn->service->executeRequestProc(call);
1586 if (tservice->afterProc)
1587 (*tservice->afterProc) (call, code);
1589 rx_EndCall(call, code);
1590 if (rx_stats_active) {
1591 MUTEX_ENTER(&rx_stats_mutex);
1593 MUTEX_EXIT(&rx_stats_mutex);
1600 rx_WakeupServerProcs(void)
1602 struct rx_serverQueueEntry *np, *tqp;
1606 MUTEX_ENTER(&rx_serverPool_lock);
1608 #ifdef RX_ENABLE_LOCKS
1609 if (rx_waitForPacket)
1610 CV_BROADCAST(&rx_waitForPacket->cv);
1611 #else /* RX_ENABLE_LOCKS */
1612 if (rx_waitForPacket)
1613 osi_rxWakeup(rx_waitForPacket);
1614 #endif /* RX_ENABLE_LOCKS */
1615 MUTEX_ENTER(&freeSQEList_lock);
1616 for (np = rx_FreeSQEList; np; np = tqp) {
1617 tqp = *(struct rx_serverQueueEntry **)np;
1618 #ifdef RX_ENABLE_LOCKS
1619 CV_BROADCAST(&np->cv);
1620 #else /* RX_ENABLE_LOCKS */
1622 #endif /* RX_ENABLE_LOCKS */
1624 MUTEX_EXIT(&freeSQEList_lock);
1625 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1626 #ifdef RX_ENABLE_LOCKS
1627 CV_BROADCAST(&np->cv);
1628 #else /* RX_ENABLE_LOCKS */
1630 #endif /* RX_ENABLE_LOCKS */
1632 MUTEX_EXIT(&rx_serverPool_lock);
1637 * One thing that seems to happen is that all the server threads get
1638 * tied up on some empty or slow call, and then a whole bunch of calls
1639 * arrive at once, using up the packet pool, so now there are more
1640 * empty calls. The most critical resources here are server threads
1641 * and the free packet pool. The "doreclaim" code seems to help in
1642 * general. I think that eventually we arrive in this state: there
1643 * are lots of pending calls which do have all their packets present,
1644 * so they won't be reclaimed, are multi-packet calls, so they won't
1645 * be scheduled until later, and thus are tying up most of the free
1646 * packet pool for a very long time.
1648 * 1. schedule multi-packet calls if all the packets are present.
1649 * Probably CPU-bound operation, useful to return packets to pool.
1650 * Do what if there is a full window, but the last packet isn't here?
1651 * 3. preserve one thread which *only* runs "best" calls, otherwise
1652 * it sleeps and waits for that type of call.
1653 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1654 * the current dataquota business is badly broken. The quota isn't adjusted
1655 * to reflect how many packets are presently queued for a running call.
1656 * So, when we schedule a queued call with a full window of packets queued
1657 * up for it, that *should* free up a window full of packets for other 2d-class
1658 * calls to be able to use from the packet pool. But it doesn't.
1660 * NB. Most of the time, this code doesn't run -- since idle server threads
1661 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1662 * as a new call arrives.
1664 /* Sleep until a call arrives. Returns a pointer to the call, ready
1665 * for an rx_Read. */
1666 #ifdef RX_ENABLE_LOCKS
1668 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1670 struct rx_serverQueueEntry *sq;
1671 struct rx_call *call = (struct rx_call *)0;
1672 struct rx_service *service = NULL;
1675 MUTEX_ENTER(&freeSQEList_lock);
1677 if ((sq = rx_FreeSQEList)) {
1678 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1679 MUTEX_EXIT(&freeSQEList_lock);
1680 } else { /* otherwise allocate a new one and return that */
1681 MUTEX_EXIT(&freeSQEList_lock);
1682 sq = (struct rx_serverQueueEntry *)
1683 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1684 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1685 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1688 MUTEX_ENTER(&rx_serverPool_lock);
1689 if (cur_service != NULL) {
1690 ReturnToServerPool(cur_service);
1693 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1694 struct rx_call *tcall, *ncall, *choice2 = NULL;
1696 /* Scan for eligible incoming calls. A call is not eligible
1697 * if the maximum number of calls for its service type are
1698 * already executing */
1699 /* One thread will process calls FCFS (to prevent starvation),
1700 * while the other threads may run ahead looking for calls which
1701 * have all their input data available immediately. This helps
1702 * keep threads from blocking, waiting for data from the client. */
1703 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1704 service = tcall->conn->service;
1705 if (!QuotaOK(service)) {
1708 MUTEX_ENTER(&rx_pthread_mutex);
1709 if (tno == rxi_fcfs_thread_num
1710 || !tcall->queue_item_header.next) {
1711 MUTEX_EXIT(&rx_pthread_mutex);
1712 /* If we're the fcfs thread , then we'll just use
1713 * this call. If we haven't been able to find an optimal
1714 * choice, and we're at the end of the list, then use a
1715 * 2d choice if one has been identified. Otherwise... */
1716 call = (choice2 ? choice2 : tcall);
1717 service = call->conn->service;
1719 MUTEX_EXIT(&rx_pthread_mutex);
1720 if (!queue_IsEmpty(&tcall->rq)) {
1721 struct rx_packet *rp;
1722 rp = queue_First(&tcall->rq, rx_packet);
1723 if (rp->header.seq == 1) {
1725 || (rp->header.flags & RX_LAST_PACKET)) {
1727 } else if (rxi_2dchoice && !choice2
1728 && !(tcall->flags & RX_CALL_CLEARED)
1729 && (tcall->rprev > rxi_HardAckRate)) {
1739 ReturnToServerPool(service);
1746 MUTEX_EXIT(&rx_serverPool_lock);
1747 MUTEX_ENTER(&call->lock);
1749 if (call->flags & RX_CALL_WAIT_PROC) {
1750 call->flags &= ~RX_CALL_WAIT_PROC;
1751 MUTEX_ENTER(&rx_waiting_mutex);
1753 MUTEX_EXIT(&rx_waiting_mutex);
1756 if (call->state != RX_STATE_PRECALL || call->error) {
1757 MUTEX_EXIT(&call->lock);
1758 MUTEX_ENTER(&rx_serverPool_lock);
1759 ReturnToServerPool(service);
1764 if (queue_IsEmpty(&call->rq)
1765 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1766 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1768 CLEAR_CALL_QUEUE_LOCK(call);
1771 /* If there are no eligible incoming calls, add this process
1772 * to the idle server queue, to wait for one */
1776 *socketp = OSI_NULLSOCKET;
1778 sq->socketp = socketp;
1779 queue_Append(&rx_idleServerQueue, sq);
1780 #ifndef AFS_AIX41_ENV
1781 rx_waitForPacket = sq;
1783 rx_waitingForPacket = sq;
1784 #endif /* AFS_AIX41_ENV */
1786 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1788 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1789 MUTEX_EXIT(&rx_serverPool_lock);
1790 return (struct rx_call *)0;
1793 } while (!(call = sq->newcall)
1794 && !(socketp && *socketp != OSI_NULLSOCKET));
1795 MUTEX_EXIT(&rx_serverPool_lock);
1797 MUTEX_ENTER(&call->lock);
1803 MUTEX_ENTER(&freeSQEList_lock);
1804 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1805 rx_FreeSQEList = sq;
1806 MUTEX_EXIT(&freeSQEList_lock);
1809 clock_GetTime(&call->startTime);
1810 call->state = RX_STATE_ACTIVE;
1811 call->mode = RX_MODE_RECEIVING;
1812 #ifdef RX_KERNEL_TRACE
1813 if (ICL_SETACTIVE(afs_iclSetp)) {
1814 int glockOwner = ISAFS_GLOCK();
1817 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1818 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1825 rxi_calltrace(RX_CALL_START, call);
1826 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1827 call->conn->service->servicePort, call->conn->service->serviceId,
1830 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1831 MUTEX_EXIT(&call->lock);
1833 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1838 #else /* RX_ENABLE_LOCKS */
1840 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1842 struct rx_serverQueueEntry *sq;
1843 struct rx_call *call = (struct rx_call *)0, *choice2;
1844 struct rx_service *service = NULL;
1848 MUTEX_ENTER(&freeSQEList_lock);
1850 if ((sq = rx_FreeSQEList)) {
1851 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1852 MUTEX_EXIT(&freeSQEList_lock);
1853 } else { /* otherwise allocate a new one and return that */
1854 MUTEX_EXIT(&freeSQEList_lock);
1855 sq = (struct rx_serverQueueEntry *)
1856 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1857 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1858 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1860 MUTEX_ENTER(&sq->lock);
1862 if (cur_service != NULL) {
1863 cur_service->nRequestsRunning--;
1864 MUTEX_ENTER(&rx_quota_mutex);
1865 if (cur_service->nRequestsRunning < cur_service->minProcs)
1868 MUTEX_EXIT(&rx_quota_mutex);
1870 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1871 struct rx_call *tcall, *ncall;
1872 /* Scan for eligible incoming calls. A call is not eligible
1873 * if the maximum number of calls for its service type are
1874 * already executing */
1875 /* One thread will process calls FCFS (to prevent starvation),
1876 * while the other threads may run ahead looking for calls which
1877 * have all their input data available immediately. This helps
1878 * keep threads from blocking, waiting for data from the client. */
1879 choice2 = (struct rx_call *)0;
1880 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1881 service = tcall->conn->service;
1882 if (QuotaOK(service)) {
1883 MUTEX_ENTER(&rx_pthread_mutex);
1884 if (tno == rxi_fcfs_thread_num
1885 || !tcall->queue_item_header.next) {
1886 MUTEX_EXIT(&rx_pthread_mutex);
1887 /* If we're the fcfs thread, then we'll just use
1888 * this call. If we haven't been able to find an optimal
1889 * choice, and we're at the end of the list, then use a
1890 * 2d choice if one has been identified. Otherwise... */
1891 call = (choice2 ? choice2 : tcall);
1892 service = call->conn->service;
1894 MUTEX_EXIT(&rx_pthread_mutex);
1895 if (!queue_IsEmpty(&tcall->rq)) {
1896 struct rx_packet *rp;
1897 rp = queue_First(&tcall->rq, rx_packet);
1898 if (rp->header.seq == 1
1900 || (rp->header.flags & RX_LAST_PACKET))) {
1902 } else if (rxi_2dchoice && !choice2
1903 && !(tcall->flags & RX_CALL_CLEARED)
1904 && (tcall->rprev > rxi_HardAckRate)) {
1918 /* we can't schedule a call if there's no data!!! */
1919 /* send an ack if there's no data, if we're missing the
1920 * first packet, or we're missing something between first
1921 * and last -- there's a "hole" in the incoming data. */
1922 if (queue_IsEmpty(&call->rq)
1923 || queue_First(&call->rq, rx_packet)->header.seq != 1
1924 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1925 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1927 call->flags &= (~RX_CALL_WAIT_PROC);
1928 service->nRequestsRunning++;
1929 /* just started call in minProcs pool, need fewer to maintain
1931 MUTEX_ENTER(&rx_quota_mutex);
1932 if (service->nRequestsRunning <= service->minProcs)
1935 MUTEX_EXIT(&rx_quota_mutex);
1937 /* MUTEX_EXIT(&call->lock); */
1939 /* If there are no eligible incoming calls, add this process
1940 * to the idle server queue, to wait for one */
1943 *socketp = OSI_NULLSOCKET;
1945 sq->socketp = socketp;
1946 queue_Append(&rx_idleServerQueue, sq);
1950 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1952 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1953 return (struct rx_call *)0;
1956 } while (!(call = sq->newcall)
1957 && !(socketp && *socketp != OSI_NULLSOCKET));
1959 MUTEX_EXIT(&sq->lock);
1961 MUTEX_ENTER(&freeSQEList_lock);
1962 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1963 rx_FreeSQEList = sq;
1964 MUTEX_EXIT(&freeSQEList_lock);
1967 clock_GetTime(&call->startTime);
1968 call->state = RX_STATE_ACTIVE;
1969 call->mode = RX_MODE_RECEIVING;
1970 #ifdef RX_KERNEL_TRACE
1971 if (ICL_SETACTIVE(afs_iclSetp)) {
1972 int glockOwner = ISAFS_GLOCK();
1975 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1976 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1983 rxi_calltrace(RX_CALL_START, call);
1984 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
1985 call->conn->service->servicePort, call->conn->service->serviceId,
1988 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1995 #endif /* RX_ENABLE_LOCKS */
1999 /* Establish a procedure to be called when a packet arrives for a
2000 * call. This routine will be called at most once after each call,
2001 * and will also be called if there is an error condition on the or
2002 * the call is complete. Used by multi rx to build a selection
2003 * function which determines which of several calls is likely to be a
2004 * good one to read from.
2005 * NOTE: the way this is currently implemented it is probably only a
2006 * good idea to (1) use it immediately after a newcall (clients only)
2007 * and (2) only use it once. Other uses currently void your warranty
2010 rx_SetArrivalProc(struct rx_call *call,
2011 void (*proc) (struct rx_call * call,
2014 void * handle, int arg)
2016 call->arrivalProc = proc;
2017 call->arrivalProcHandle = handle;
2018 call->arrivalProcArg = arg;
2021 /* Call is finished (possibly prematurely). Return rc to the peer, if
2022 * appropriate, and return the final error code from the conversation
2026 rx_EndCall(struct rx_call *call, afs_int32 rc)
2028 struct rx_connection *conn = call->conn;
2032 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2033 call, rc, call->error, call->abortCode));
2036 MUTEX_ENTER(&call->lock);
2038 if (rc == 0 && call->error == 0) {
2039 call->abortCode = 0;
2040 call->abortCount = 0;
2043 call->arrivalProc = (void (*)())0;
2044 if (rc && call->error == 0) {
2045 rxi_CallError(call, rc);
2046 /* Send an abort message to the peer if this error code has
2047 * only just been set. If it was set previously, assume the
2048 * peer has already been sent the error code or will request it
2050 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2052 if (conn->type == RX_SERVER_CONNECTION) {
2053 /* Make sure reply or at least dummy reply is sent */
2054 if (call->mode == RX_MODE_RECEIVING) {
2055 rxi_WriteProc(call, 0, 0);
2057 if (call->mode == RX_MODE_SENDING) {
2058 rxi_FlushWrite(call);
2060 rxi_calltrace(RX_CALL_END, call);
2061 /* Call goes to hold state until reply packets are acknowledged */
2062 if (call->tfirst + call->nSoftAcked < call->tnext) {
2063 call->state = RX_STATE_HOLD;
2065 call->state = RX_STATE_DALLY;
2066 rxi_ClearTransmitQueue(call, 0);
2067 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2068 rxevent_Cancel(call->keepAliveEvent, call,
2069 RX_CALL_REFCOUNT_ALIVE);
2071 } else { /* Client connection */
2073 /* Make sure server receives input packets, in the case where
2074 * no reply arguments are expected */
2075 if ((call->mode == RX_MODE_SENDING)
2076 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2077 (void)rxi_ReadProc(call, &dummy, 1);
2080 /* If we had an outstanding delayed ack, be nice to the server
2081 * and force-send it now.
2083 if (call->delayedAckEvent) {
2084 rxevent_Cancel(call->delayedAckEvent, call,
2085 RX_CALL_REFCOUNT_DELAY);
2086 call->delayedAckEvent = NULL;
2087 rxi_SendDelayedAck(NULL, call, NULL);
2090 /* We need to release the call lock since it's lower than the
2091 * conn_call_lock and we don't want to hold the conn_call_lock
2092 * over the rx_ReadProc call. The conn_call_lock needs to be held
2093 * here for the case where rx_NewCall is perusing the calls on
2094 * the connection structure. We don't want to signal until
2095 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2096 * have checked this call, found it active and by the time it
2097 * goes to sleep, will have missed the signal.
2099 MUTEX_EXIT(&call->lock);
2100 MUTEX_ENTER(&conn->conn_call_lock);
2101 MUTEX_ENTER(&call->lock);
2102 MUTEX_ENTER(&conn->conn_data_lock);
2103 conn->flags |= RX_CONN_BUSY;
2104 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2105 MUTEX_EXIT(&conn->conn_data_lock);
2106 #ifdef RX_ENABLE_LOCKS
2107 CV_BROADCAST(&conn->conn_call_cv);
2112 #ifdef RX_ENABLE_LOCKS
2114 MUTEX_EXIT(&conn->conn_data_lock);
2116 #endif /* RX_ENABLE_LOCKS */
2117 call->state = RX_STATE_DALLY;
2119 error = call->error;
2121 /* currentPacket, nLeft, and NFree must be zeroed here, because
2122 * ResetCall cannot: ResetCall may be called at splnet(), in the
2123 * kernel version, and may interrupt the macros rx_Read or
2124 * rx_Write, which run at normal priority for efficiency. */
2125 if (call->currentPacket) {
2126 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2127 rxi_FreePacket(call->currentPacket);
2128 call->currentPacket = (struct rx_packet *)0;
2131 call->nLeft = call->nFree = call->curlen = 0;
2133 /* Free any packets from the last call to ReadvProc/WritevProc */
2134 #ifdef RXDEBUG_PACKET
2136 #endif /* RXDEBUG_PACKET */
2137 rxi_FreePackets(0, &call->iovq);
2139 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2140 MUTEX_EXIT(&call->lock);
2141 if (conn->type == RX_CLIENT_CONNECTION) {
2142 MUTEX_ENTER(&conn->conn_data_lock);
2143 conn->flags &= ~RX_CONN_BUSY;
2144 MUTEX_EXIT(&conn->conn_data_lock);
2145 MUTEX_EXIT(&conn->conn_call_lock);
2149 * Map errors to the local host's errno.h format.
2151 error = ntoh_syserr_conv(error);
2155 #if !defined(KERNEL)
2157 /* Call this routine when shutting down a server or client (especially
2158 * clients). This will allow Rx to gracefully garbage collect server
2159 * connections, and reduce the number of retries that a server might
2160 * make to a dead client.
2161 * This is not quite right, since some calls may still be ongoing and
2162 * we can't lock them to destroy them. */
2166 struct rx_connection **conn_ptr, **conn_end;
2170 if (rxinit_status == 1) {
2172 return; /* Already shutdown. */
2174 rxi_DeleteCachedConnections();
2175 if (rx_connHashTable) {
2176 MUTEX_ENTER(&rx_connHashTable_lock);
2177 for (conn_ptr = &rx_connHashTable[0], conn_end =
2178 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2180 struct rx_connection *conn, *next;
2181 for (conn = *conn_ptr; conn; conn = next) {
2183 if (conn->type == RX_CLIENT_CONNECTION) {
2184 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2186 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2187 #ifdef RX_ENABLE_LOCKS
2188 rxi_DestroyConnectionNoLock(conn);
2189 #else /* RX_ENABLE_LOCKS */
2190 rxi_DestroyConnection(conn);
2191 #endif /* RX_ENABLE_LOCKS */
2195 #ifdef RX_ENABLE_LOCKS
2196 while (rx_connCleanup_list) {
2197 struct rx_connection *conn;
2198 conn = rx_connCleanup_list;
2199 rx_connCleanup_list = rx_connCleanup_list->next;
2200 MUTEX_EXIT(&rx_connHashTable_lock);
2201 rxi_CleanupConnection(conn);
2202 MUTEX_ENTER(&rx_connHashTable_lock);
2204 MUTEX_EXIT(&rx_connHashTable_lock);
2205 #endif /* RX_ENABLE_LOCKS */
2210 afs_winsockCleanup();
2218 /* if we wakeup packet waiter too often, can get in loop with two
2219 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2221 rxi_PacketsUnWait(void)
2223 if (!rx_waitingForPackets) {
2227 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2228 return; /* still over quota */
2231 rx_waitingForPackets = 0;
2232 #ifdef RX_ENABLE_LOCKS
2233 CV_BROADCAST(&rx_waitingForPackets_cv);
2235 osi_rxWakeup(&rx_waitingForPackets);
2241 /* ------------------Internal interfaces------------------------- */
2243 /* Return this process's service structure for the
2244 * specified socket and service */
2246 rxi_FindService(osi_socket socket, u_short serviceId)
2248 struct rx_service **sp;
2249 for (sp = &rx_services[0]; *sp; sp++) {
2250 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2256 #ifdef RXDEBUG_PACKET
2257 #ifdef KDUMP_RX_LOCK
2258 static struct rx_call_rx_lock *rx_allCallsp = 0;
2260 static struct rx_call *rx_allCallsp = 0;
2262 #endif /* RXDEBUG_PACKET */
2264 /* Allocate a call structure, for the indicated channel of the
2265 * supplied connection. The mode and state of the call must be set by
2266 * the caller. Returns the call with mutex locked. */
2268 rxi_NewCall(struct rx_connection *conn, int channel)
2270 struct rx_call *call;
2271 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2272 struct rx_call *cp; /* Call pointer temp */
2273 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2274 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2276 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2278 /* Grab an existing call structure, or allocate a new one.
2279 * Existing call structures are assumed to have been left reset by
2281 MUTEX_ENTER(&rx_freeCallQueue_lock);
2283 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2285 * EXCEPT that the TQ might not yet be cleared out.
2286 * Skip over those with in-use TQs.
2289 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2290 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2296 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2297 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2298 call = queue_First(&rx_freeCallQueue, rx_call);
2299 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2301 if (rx_stats_active)
2302 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2303 MUTEX_EXIT(&rx_freeCallQueue_lock);
2304 MUTEX_ENTER(&call->lock);
2305 CLEAR_CALL_QUEUE_LOCK(call);
2306 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2307 /* Now, if TQ wasn't cleared earlier, do it now. */
2308 rxi_WaitforTQBusy(call);
2309 if (call->flags & RX_CALL_TQ_CLEARME) {
2310 rxi_ClearTransmitQueue(call, 1);
2311 /*queue_Init(&call->tq);*/
2313 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2314 /* Bind the call to its connection structure */
2316 rxi_ResetCall(call, 1);
2319 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2320 #ifdef RXDEBUG_PACKET
2321 call->allNextp = rx_allCallsp;
2322 rx_allCallsp = call;
2324 #endif /* RXDEBUG_PACKET */
2325 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2327 MUTEX_EXIT(&rx_freeCallQueue_lock);
2328 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2329 MUTEX_ENTER(&call->lock);
2330 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2331 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2332 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2334 /* Initialize once-only items */
2335 queue_Init(&call->tq);
2336 queue_Init(&call->rq);
2337 queue_Init(&call->iovq);
2338 #ifdef RXDEBUG_PACKET
2339 call->rqc = call->tqc = call->iovqc = 0;
2340 #endif /* RXDEBUG_PACKET */
2341 /* Bind the call to its connection structure (prereq for reset) */
2343 rxi_ResetCall(call, 1);
2345 call->channel = channel;
2346 call->callNumber = &conn->callNumber[channel];
2347 call->rwind = conn->rwind[channel];
2348 call->twind = conn->twind[channel];
2349 /* Note that the next expected call number is retained (in
2350 * conn->callNumber[i]), even if we reallocate the call structure
2352 conn->call[channel] = call;
2353 /* if the channel's never been used (== 0), we should start at 1, otherwise
2354 * the call number is valid from the last time this channel was used */
2355 if (*call->callNumber == 0)
2356 *call->callNumber = 1;
2361 /* A call has been inactive long enough that so we can throw away
2362 * state, including the call structure, which is placed on the call
2364 * Call is locked upon entry.
2365 * haveCTLock set if called from rxi_ReapConnections
2367 #ifdef RX_ENABLE_LOCKS
2369 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2370 #else /* RX_ENABLE_LOCKS */
2372 rxi_FreeCall(struct rx_call *call)
2373 #endif /* RX_ENABLE_LOCKS */
2375 int channel = call->channel;
2376 struct rx_connection *conn = call->conn;
2379 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2380 (*call->callNumber)++;
2381 rxi_ResetCall(call, 0);
2382 call->conn->call[channel] = (struct rx_call *)0;
2384 MUTEX_ENTER(&rx_freeCallQueue_lock);
2385 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2386 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2387 /* A call may be free even though its transmit queue is still in use.
2388 * Since we search the call list from head to tail, put busy calls at
2389 * the head of the list, and idle calls at the tail.
2391 if (call->flags & RX_CALL_TQ_BUSY)
2392 queue_Prepend(&rx_freeCallQueue, call);
2394 queue_Append(&rx_freeCallQueue, call);
2395 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2396 queue_Append(&rx_freeCallQueue, call);
2397 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2398 if (rx_stats_active)
2399 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2400 MUTEX_EXIT(&rx_freeCallQueue_lock);
2402 /* Destroy the connection if it was previously slated for
2403 * destruction, i.e. the Rx client code previously called
2404 * rx_DestroyConnection (client connections), or
2405 * rxi_ReapConnections called the same routine (server
2406 * connections). Only do this, however, if there are no
2407 * outstanding calls. Note that for fine grain locking, there appears
2408 * to be a deadlock in that rxi_FreeCall has a call locked and
2409 * DestroyConnectionNoLock locks each call in the conn. But note a
2410 * few lines up where we have removed this call from the conn.
2411 * If someone else destroys a connection, they either have no
2412 * call lock held or are going through this section of code.
2414 MUTEX_ENTER(&conn->conn_data_lock);
2415 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2417 MUTEX_EXIT(&conn->conn_data_lock);
2418 #ifdef RX_ENABLE_LOCKS
2420 rxi_DestroyConnectionNoLock(conn);
2422 rxi_DestroyConnection(conn);
2423 #else /* RX_ENABLE_LOCKS */
2424 rxi_DestroyConnection(conn);
2425 #endif /* RX_ENABLE_LOCKS */
2427 MUTEX_EXIT(&conn->conn_data_lock);
2431 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2433 rxi_Alloc(size_t size)
2437 if (rx_stats_active)
2438 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2441 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2442 afs_osi_Alloc_NoSleep(size);
2447 osi_Panic("rxi_Alloc error");
2453 rxi_Free(void *addr, size_t size)
2455 if (rx_stats_active)
2456 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2457 osi_Free(addr, size);
2461 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2463 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2464 struct rx_peer *next = NULL;
2468 MUTEX_ENTER(&rx_peerHashTable_lock);
2470 peer_ptr = &rx_peerHashTable[0];
2471 peer_end = &rx_peerHashTable[rx_hashTableSize];
2474 for ( ; peer_ptr < peer_end; peer_ptr++) {
2477 for ( ; peer; peer = next) {
2479 if (host == peer->host)
2484 hashIndex = PEER_HASH(host, port);
2485 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2486 if ((peer->host == host) && (peer->port == port))
2491 MUTEX_ENTER(&rx_peerHashTable_lock);
2496 MUTEX_EXIT(&rx_peerHashTable_lock);
2498 MUTEX_ENTER(&peer->peer_lock);
2499 /* We don't handle dropping below min, so don't */
2500 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2501 peer->ifMTU=MIN(mtu, peer->ifMTU);
2502 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2503 /* if we tweaked this down, need to tune our peer MTU too */
2504 peer->MTU = MIN(peer->MTU, peer->natMTU);
2505 /* if we discovered a sub-1500 mtu, degrade */
2506 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2507 peer->maxDgramPackets = 1;
2508 /* We no longer have valid peer packet information */
2509 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2510 peer->maxPacketSize = 0;
2511 MUTEX_EXIT(&peer->peer_lock);
2513 MUTEX_ENTER(&rx_peerHashTable_lock);
2515 if (host && !port) {
2517 /* pick up where we left off */
2521 MUTEX_EXIT(&rx_peerHashTable_lock);
2524 /* Find the peer process represented by the supplied (host,port)
2525 * combination. If there is no appropriate active peer structure, a
2526 * new one will be allocated and initialized
2527 * The origPeer, if set, is a pointer to a peer structure on which the
2528 * refcount will be be decremented. This is used to replace the peer
2529 * structure hanging off a connection structure */
2531 rxi_FindPeer(afs_uint32 host, u_short port,
2532 struct rx_peer *origPeer, int create)
2536 hashIndex = PEER_HASH(host, port);
2537 MUTEX_ENTER(&rx_peerHashTable_lock);
2538 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2539 if ((pp->host == host) && (pp->port == port))
2544 pp = rxi_AllocPeer(); /* This bzero's *pp */
2545 pp->host = host; /* set here or in InitPeerParams is zero */
2547 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2548 queue_Init(&pp->congestionQueue);
2549 queue_Init(&pp->rpcStats);
2550 pp->next = rx_peerHashTable[hashIndex];
2551 rx_peerHashTable[hashIndex] = pp;
2552 rxi_InitPeerParams(pp);
2553 if (rx_stats_active)
2554 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2561 origPeer->refCount--;
2562 MUTEX_EXIT(&rx_peerHashTable_lock);
2567 /* Find the connection at (host, port) started at epoch, and with the
2568 * given connection id. Creates the server connection if necessary.
2569 * The type specifies whether a client connection or a server
2570 * connection is desired. In both cases, (host, port) specify the
2571 * peer's (host, pair) pair. Client connections are not made
2572 * automatically by this routine. The parameter socket gives the
2573 * socket descriptor on which the packet was received. This is used,
2574 * in the case of server connections, to check that *new* connections
2575 * come via a valid (port, serviceId). Finally, the securityIndex
2576 * parameter must match the existing index for the connection. If a
2577 * server connection is created, it will be created using the supplied
2578 * index, if the index is valid for this service */
2579 struct rx_connection *
2580 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2581 u_short port, u_short serviceId, afs_uint32 cid,
2582 afs_uint32 epoch, int type, u_int securityIndex)
2584 int hashindex, flag, i;
2585 struct rx_connection *conn;
2586 hashindex = CONN_HASH(host, port, cid, epoch, type);
2587 MUTEX_ENTER(&rx_connHashTable_lock);
2588 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2589 rx_connHashTable[hashindex],
2592 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2593 && (epoch == conn->epoch)) {
2594 struct rx_peer *pp = conn->peer;
2595 if (securityIndex != conn->securityIndex) {
2596 /* this isn't supposed to happen, but someone could forge a packet
2597 * like this, and there seems to be some CM bug that makes this
2598 * happen from time to time -- in which case, the fileserver
2600 MUTEX_EXIT(&rx_connHashTable_lock);
2601 return (struct rx_connection *)0;
2603 if (pp->host == host && pp->port == port)
2605 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2607 /* So what happens when it's a callback connection? */
2608 if ( /*type == RX_CLIENT_CONNECTION && */
2609 (conn->epoch & 0x80000000))
2613 /* the connection rxLastConn that was used the last time is not the
2614 ** one we are looking for now. Hence, start searching in the hash */
2616 conn = rx_connHashTable[hashindex];
2621 struct rx_service *service;
2622 if (type == RX_CLIENT_CONNECTION) {
2623 MUTEX_EXIT(&rx_connHashTable_lock);
2624 return (struct rx_connection *)0;
2626 service = rxi_FindService(socket, serviceId);
2627 if (!service || (securityIndex >= service->nSecurityObjects)
2628 || (service->securityObjects[securityIndex] == 0)) {
2629 MUTEX_EXIT(&rx_connHashTable_lock);
2630 return (struct rx_connection *)0;
2632 conn = rxi_AllocConnection(); /* This bzero's the connection */
2633 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2634 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2635 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2636 conn->next = rx_connHashTable[hashindex];
2637 rx_connHashTable[hashindex] = conn;
2638 conn->peer = rxi_FindPeer(host, port, 0, 1);
2639 conn->type = RX_SERVER_CONNECTION;
2640 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2641 conn->epoch = epoch;
2642 conn->cid = cid & RX_CIDMASK;
2643 /* conn->serial = conn->lastSerial = 0; */
2644 /* conn->timeout = 0; */
2645 conn->ackRate = RX_FAST_ACK_RATE;
2646 conn->service = service;
2647 conn->serviceId = serviceId;
2648 conn->securityIndex = securityIndex;
2649 conn->securityObject = service->securityObjects[securityIndex];
2650 conn->nSpecific = 0;
2651 conn->specific = NULL;
2652 rx_SetConnDeadTime(conn, service->connDeadTime);
2653 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2654 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2655 for (i = 0; i < RX_MAXCALLS; i++) {
2656 conn->twind[i] = rx_initSendWindow;
2657 conn->rwind[i] = rx_initReceiveWindow;
2659 /* Notify security object of the new connection */
2660 RXS_NewConnection(conn->securityObject, conn);
2661 /* XXXX Connection timeout? */
2662 if (service->newConnProc)
2663 (*service->newConnProc) (conn);
2664 if (rx_stats_active)
2665 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2668 MUTEX_ENTER(&conn->conn_data_lock);
2670 MUTEX_EXIT(&conn->conn_data_lock);
2672 rxLastConn = conn; /* store this connection as the last conn used */
2673 MUTEX_EXIT(&rx_connHashTable_lock);
2677 /* There are two packet tracing routines available for testing and monitoring
2678 * Rx. One is called just after every packet is received and the other is
2679 * called just before every packet is sent. Received packets, have had their
2680 * headers decoded, and packets to be sent have not yet had their headers
2681 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2682 * containing the network address. Both can be modified. The return value, if
2683 * non-zero, indicates that the packet should be dropped. */
2685 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2686 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2688 /* A packet has been received off the interface. Np is the packet, socket is
2689 * the socket number it was received from (useful in determining which service
2690 * this packet corresponds to), and (host, port) reflect the host,port of the
2691 * sender. This call returns the packet to the caller if it is finished with
2692 * it, rather than de-allocating it, just as a small performance hack */
2695 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2696 afs_uint32 host, u_short port, int *tnop,
2697 struct rx_call **newcallp)
2699 struct rx_call *call;
2700 struct rx_connection *conn;
2702 afs_uint32 currentCallNumber;
2708 struct rx_packet *tnp;
2711 /* We don't print out the packet until now because (1) the time may not be
2712 * accurate enough until now in the lwp implementation (rx_Listener only gets
2713 * the time after the packet is read) and (2) from a protocol point of view,
2714 * this is the first time the packet has been seen */
2715 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2716 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2717 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2718 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2719 np->header.epoch, np->header.cid, np->header.callNumber,
2720 np->header.seq, np->header.flags, np));
2723 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2724 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2727 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2728 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2731 /* If an input tracer function is defined, call it with the packet and
2732 * network address. Note this function may modify its arguments. */
2733 if (rx_justReceived) {
2734 struct sockaddr_in addr;
2736 addr.sin_family = AF_INET;
2737 addr.sin_port = port;
2738 addr.sin_addr.s_addr = host;
2739 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2740 addr.sin_len = sizeof(addr);
2741 #endif /* AFS_OSF_ENV */
2742 drop = (*rx_justReceived) (np, &addr);
2743 /* drop packet if return value is non-zero */
2746 port = addr.sin_port; /* in case fcn changed addr */
2747 host = addr.sin_addr.s_addr;
2751 /* If packet was not sent by the client, then *we* must be the client */
2752 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2753 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2755 /* Find the connection (or fabricate one, if we're the server & if
2756 * necessary) associated with this packet */
2758 rxi_FindConnection(socket, host, port, np->header.serviceId,
2759 np->header.cid, np->header.epoch, type,
2760 np->header.securityIndex);
2763 /* If no connection found or fabricated, just ignore the packet.
2764 * (An argument could be made for sending an abort packet for
2769 MUTEX_ENTER(&conn->conn_data_lock);
2770 if (conn->maxSerial < np->header.serial)
2771 conn->maxSerial = np->header.serial;
2772 MUTEX_EXIT(&conn->conn_data_lock);
2774 /* If the connection is in an error state, send an abort packet and ignore
2775 * the incoming packet */
2777 /* Don't respond to an abort packet--we don't want loops! */
2778 MUTEX_ENTER(&conn->conn_data_lock);
2779 if (np->header.type != RX_PACKET_TYPE_ABORT)
2780 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2782 MUTEX_EXIT(&conn->conn_data_lock);
2786 /* Check for connection-only requests (i.e. not call specific). */
2787 if (np->header.callNumber == 0) {
2788 switch (np->header.type) {
2789 case RX_PACKET_TYPE_ABORT: {
2790 /* What if the supplied error is zero? */
2791 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2792 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2793 rxi_ConnectionError(conn, errcode);
2794 MUTEX_ENTER(&conn->conn_data_lock);
2796 MUTEX_EXIT(&conn->conn_data_lock);
2799 case RX_PACKET_TYPE_CHALLENGE:
2800 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2801 MUTEX_ENTER(&conn->conn_data_lock);
2803 MUTEX_EXIT(&conn->conn_data_lock);
2805 case RX_PACKET_TYPE_RESPONSE:
2806 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2807 MUTEX_ENTER(&conn->conn_data_lock);
2809 MUTEX_EXIT(&conn->conn_data_lock);
2811 case RX_PACKET_TYPE_PARAMS:
2812 case RX_PACKET_TYPE_PARAMS + 1:
2813 case RX_PACKET_TYPE_PARAMS + 2:
2814 /* ignore these packet types for now */
2815 MUTEX_ENTER(&conn->conn_data_lock);
2817 MUTEX_EXIT(&conn->conn_data_lock);
2822 /* Should not reach here, unless the peer is broken: send an
2824 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2825 MUTEX_ENTER(&conn->conn_data_lock);
2826 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2828 MUTEX_EXIT(&conn->conn_data_lock);
2833 channel = np->header.cid & RX_CHANNELMASK;
2834 call = conn->call[channel];
2835 #ifdef RX_ENABLE_LOCKS
2837 MUTEX_ENTER(&call->lock);
2838 /* Test to see if call struct is still attached to conn. */
2839 if (call != conn->call[channel]) {
2841 MUTEX_EXIT(&call->lock);
2842 if (type == RX_SERVER_CONNECTION) {
2843 call = conn->call[channel];
2844 /* If we started with no call attached and there is one now,
2845 * another thread is also running this routine and has gotten
2846 * the connection channel. We should drop this packet in the tests
2847 * below. If there was a call on this connection and it's now
2848 * gone, then we'll be making a new call below.
2849 * If there was previously a call and it's now different then
2850 * the old call was freed and another thread running this routine
2851 * has created a call on this channel. One of these two threads
2852 * has a packet for the old call and the code below handles those
2856 MUTEX_ENTER(&call->lock);
2858 /* This packet can't be for this call. If the new call address is
2859 * 0 then no call is running on this channel. If there is a call
2860 * then, since this is a client connection we're getting data for
2861 * it must be for the previous call.
2863 if (rx_stats_active)
2864 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2865 MUTEX_ENTER(&conn->conn_data_lock);
2867 MUTEX_EXIT(&conn->conn_data_lock);
2872 currentCallNumber = conn->callNumber[channel];
2874 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2875 if (np->header.callNumber < currentCallNumber) {
2876 if (rx_stats_active)
2877 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2878 #ifdef RX_ENABLE_LOCKS
2880 MUTEX_EXIT(&call->lock);
2882 MUTEX_ENTER(&conn->conn_data_lock);
2884 MUTEX_EXIT(&conn->conn_data_lock);
2888 MUTEX_ENTER(&conn->conn_call_lock);
2889 call = rxi_NewCall(conn, channel);
2890 MUTEX_EXIT(&conn->conn_call_lock);
2891 *call->callNumber = np->header.callNumber;
2893 if (np->header.callNumber == 0)
2894 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d",
2895 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2896 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2897 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2899 call->state = RX_STATE_PRECALL;
2900 clock_GetTime(&call->queueTime);
2901 hzero(call->bytesSent);
2902 hzero(call->bytesRcvd);
2904 * If the number of queued calls exceeds the overload
2905 * threshold then abort this call.
2907 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2908 struct rx_packet *tp;
2910 rxi_CallError(call, rx_BusyError);
2911 tp = rxi_SendCallAbort(call, np, 1, 0);
2912 MUTEX_EXIT(&call->lock);
2913 MUTEX_ENTER(&conn->conn_data_lock);
2915 MUTEX_EXIT(&conn->conn_data_lock);
2916 if (rx_stats_active)
2917 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2920 rxi_KeepAliveOn(call);
2921 } else if (np->header.callNumber != currentCallNumber) {
2922 /* Wait until the transmit queue is idle before deciding
2923 * whether to reset the current call. Chances are that the
2924 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2927 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2928 while ((call->state == RX_STATE_ACTIVE)
2929 && (call->flags & RX_CALL_TQ_BUSY)) {
2930 call->flags |= RX_CALL_TQ_WAIT;
2932 #ifdef RX_ENABLE_LOCKS
2933 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2934 CV_WAIT(&call->cv_tq, &call->lock);
2935 #else /* RX_ENABLE_LOCKS */
2936 osi_rxSleep(&call->tq);
2937 #endif /* RX_ENABLE_LOCKS */
2939 if (call->tqWaiters == 0)
2940 call->flags &= ~RX_CALL_TQ_WAIT;
2942 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2943 /* If the new call cannot be taken right now send a busy and set
2944 * the error condition in this call, so that it terminates as
2945 * quickly as possible */
2946 if (call->state == RX_STATE_ACTIVE) {
2947 struct rx_packet *tp;
2949 rxi_CallError(call, RX_CALL_DEAD);
2950 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2952 MUTEX_EXIT(&call->lock);
2953 MUTEX_ENTER(&conn->conn_data_lock);
2955 MUTEX_EXIT(&conn->conn_data_lock);
2958 rxi_ResetCall(call, 0);
2959 *call->callNumber = np->header.callNumber;
2961 if (np->header.callNumber == 0)
2962 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
2963 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2964 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2965 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
2967 call->state = RX_STATE_PRECALL;
2968 clock_GetTime(&call->queueTime);
2969 hzero(call->bytesSent);
2970 hzero(call->bytesRcvd);
2972 * If the number of queued calls exceeds the overload
2973 * threshold then abort this call.
2975 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2976 struct rx_packet *tp;
2978 rxi_CallError(call, rx_BusyError);
2979 tp = rxi_SendCallAbort(call, np, 1, 0);
2980 MUTEX_EXIT(&call->lock);
2981 MUTEX_ENTER(&conn->conn_data_lock);
2983 MUTEX_EXIT(&conn->conn_data_lock);
2984 if (rx_stats_active)
2985 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2988 rxi_KeepAliveOn(call);
2990 /* Continuing call; do nothing here. */
2992 } else { /* we're the client */
2993 /* Ignore all incoming acknowledgements for calls in DALLY state */
2994 if (call && (call->state == RX_STATE_DALLY)
2995 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2996 if (rx_stats_active)
2997 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2998 #ifdef RX_ENABLE_LOCKS
3000 MUTEX_EXIT(&call->lock);
3003 MUTEX_ENTER(&conn->conn_data_lock);
3005 MUTEX_EXIT(&conn->conn_data_lock);
3009 /* Ignore anything that's not relevant to the current call. If there
3010 * isn't a current call, then no packet is relevant. */
3011 if (!call || (np->header.callNumber != currentCallNumber)) {
3012 if (rx_stats_active)
3013 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
3014 #ifdef RX_ENABLE_LOCKS
3016 MUTEX_EXIT(&call->lock);
3019 MUTEX_ENTER(&conn->conn_data_lock);
3021 MUTEX_EXIT(&conn->conn_data_lock);
3024 /* If the service security object index stamped in the packet does not
3025 * match the connection's security index, ignore the packet */
3026 if (np->header.securityIndex != conn->securityIndex) {
3027 #ifdef RX_ENABLE_LOCKS
3028 MUTEX_EXIT(&call->lock);
3030 MUTEX_ENTER(&conn->conn_data_lock);
3032 MUTEX_EXIT(&conn->conn_data_lock);
3036 /* If we're receiving the response, then all transmit packets are
3037 * implicitly acknowledged. Get rid of them. */
3038 if (np->header.type == RX_PACKET_TYPE_DATA) {
3039 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3040 /* XXX Hack. Because we must release the global rx lock when
3041 * sending packets (osi_NetSend) we drop all acks while we're
3042 * traversing the tq in rxi_Start sending packets out because
3043 * packets may move to the freePacketQueue as result of being here!
3044 * So we drop these packets until we're safely out of the
3045 * traversing. Really ugly!
3046 * For fine grain RX locking, we set the acked field in the
3047 * packets and let rxi_Start remove them from the transmit queue.
3049 if (call->flags & RX_CALL_TQ_BUSY) {
3050 #ifdef RX_ENABLE_LOCKS
3051 rxi_SetAcksInTransmitQueue(call);
3054 return np; /* xmitting; drop packet */
3057 rxi_ClearTransmitQueue(call, 0);
3059 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3060 rxi_ClearTransmitQueue(call, 0);
3061 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3063 if (np->header.type == RX_PACKET_TYPE_ACK) {
3064 /* now check to see if this is an ack packet acknowledging that the
3065 * server actually *lost* some hard-acked data. If this happens we
3066 * ignore this packet, as it may indicate that the server restarted in
3067 * the middle of a call. It is also possible that this is an old ack
3068 * packet. We don't abort the connection in this case, because this
3069 * *might* just be an old ack packet. The right way to detect a server
3070 * restart in the midst of a call is to notice that the server epoch
3072 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3073 * XXX unacknowledged. I think that this is off-by-one, but
3074 * XXX I don't dare change it just yet, since it will
3075 * XXX interact badly with the server-restart detection
3076 * XXX code in receiveackpacket. */
3077 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3078 if (rx_stats_active)
3079 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
3080 MUTEX_EXIT(&call->lock);
3081 MUTEX_ENTER(&conn->conn_data_lock);
3083 MUTEX_EXIT(&conn->conn_data_lock);
3087 } /* else not a data packet */
3090 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3091 /* Set remote user defined status from packet */
3092 call->remoteStatus = np->header.userStatus;
3094 /* Note the gap between the expected next packet and the actual
3095 * packet that arrived, when the new packet has a smaller serial number
3096 * than expected. Rioses frequently reorder packets all by themselves,
3097 * so this will be quite important with very large window sizes.
3098 * Skew is checked against 0 here to avoid any dependence on the type of
3099 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3101 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3102 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3103 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3105 MUTEX_ENTER(&conn->conn_data_lock);
3106 skew = conn->lastSerial - np->header.serial;
3107 conn->lastSerial = np->header.serial;
3108 MUTEX_EXIT(&conn->conn_data_lock);
3110 struct rx_peer *peer;
3112 if (skew > peer->inPacketSkew) {
3113 dpf(("*** In skew changed from %d to %d\n",
3114 peer->inPacketSkew, skew));
3115 peer->inPacketSkew = skew;
3119 /* Now do packet type-specific processing */
3120 switch (np->header.type) {
3121 case RX_PACKET_TYPE_DATA:
3122 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3125 case RX_PACKET_TYPE_ACK:
3126 /* Respond immediately to ack packets requesting acknowledgement
3128 if (np->header.flags & RX_REQUEST_ACK) {
3130 (void)rxi_SendCallAbort(call, 0, 1, 0);
3132 (void)rxi_SendAck(call, 0, np->header.serial,
3133 RX_ACK_PING_RESPONSE, 1);
3135 np = rxi_ReceiveAckPacket(call, np, 1);
3137 case RX_PACKET_TYPE_ABORT: {
3138 /* An abort packet: reset the call, passing the error up to the user. */
3139 /* What if error is zero? */
3140 /* What if the error is -1? the application will treat it as a timeout. */
3141 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3142 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3143 rxi_CallError(call, errdata);
3144 MUTEX_EXIT(&call->lock);
3145 MUTEX_ENTER(&conn->conn_data_lock);
3147 MUTEX_EXIT(&conn->conn_data_lock);
3148 return np; /* xmitting; drop packet */
3150 case RX_PACKET_TYPE_BUSY:
3153 case RX_PACKET_TYPE_ACKALL:
3154 /* All packets acknowledged, so we can drop all packets previously
3155 * readied for sending */
3156 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3157 /* XXX Hack. We because we can't release the global rx lock when
3158 * sending packets (osi_NetSend) we drop all ack pkts while we're
3159 * traversing the tq in rxi_Start sending packets out because
3160 * packets may move to the freePacketQueue as result of being
3161 * here! So we drop these packets until we're safely out of the
3162 * traversing. Really ugly!
3163 * For fine grain RX locking, we set the acked field in the packets
3164 * and let rxi_Start remove the packets from the transmit queue.
3166 if (call->flags & RX_CALL_TQ_BUSY) {
3167 #ifdef RX_ENABLE_LOCKS
3168 rxi_SetAcksInTransmitQueue(call);
3170 #else /* RX_ENABLE_LOCKS */
3171 MUTEX_EXIT(&call->lock);
3172 MUTEX_ENTER(&conn->conn_data_lock);
3174 MUTEX_EXIT(&conn->conn_data_lock);
3175 return np; /* xmitting; drop packet */
3176 #endif /* RX_ENABLE_LOCKS */
3178 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3179 rxi_ClearTransmitQueue(call, 0);
3180 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3183 /* Should not reach here, unless the peer is broken: send an abort
3185 rxi_CallError(call, RX_PROTOCOL_ERROR);
3186 np = rxi_SendCallAbort(call, np, 1, 0);
3189 /* Note when this last legitimate packet was received, for keep-alive
3190 * processing. Note, we delay getting the time until now in the hope that
3191 * the packet will be delivered to the user before any get time is required
3192 * (if not, then the time won't actually be re-evaluated here). */
3193 call->lastReceiveTime = clock_Sec();
3194 MUTEX_EXIT(&call->lock);
3195 MUTEX_ENTER(&conn->conn_data_lock);
3197 MUTEX_EXIT(&conn->conn_data_lock);
3201 /* return true if this is an "interesting" connection from the point of view
3202 of someone trying to debug the system */
3204 rxi_IsConnInteresting(struct rx_connection *aconn)
3207 struct rx_call *tcall;
3209 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3212 for (i = 0; i < RX_MAXCALLS; i++) {
3213 tcall = aconn->call[i];
3215 if ((tcall->state == RX_STATE_PRECALL)
3216 || (tcall->state == RX_STATE_ACTIVE))
3218 if ((tcall->mode == RX_MODE_SENDING)
3219 || (tcall->mode == RX_MODE_RECEIVING))
3227 /* if this is one of the last few packets AND it wouldn't be used by the
3228 receiving call to immediately satisfy a read request, then drop it on
3229 the floor, since accepting it might prevent a lock-holding thread from
3230 making progress in its reading. If a call has been cleared while in
3231 the precall state then ignore all subsequent packets until the call
3232 is assigned to a thread. */
3235 TooLow(struct rx_packet *ap, struct rx_call *acall)
3239 MUTEX_ENTER(&rx_quota_mutex);
3240 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3241 && (acall->state == RX_STATE_PRECALL))
3242 || ((rx_nFreePackets < rxi_dataQuota + 2)
3243 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3244 && (acall->flags & RX_CALL_READER_WAIT)))) {
3247 MUTEX_EXIT(&rx_quota_mutex);
3253 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3255 struct rx_connection *conn = arg1;
3256 struct rx_call *acall = arg2;
3257 struct rx_call *call = acall;
3258 struct clock when, now;
3261 MUTEX_ENTER(&conn->conn_data_lock);
3262 conn->checkReachEvent = NULL;
3263 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3266 MUTEX_EXIT(&conn->conn_data_lock);
3270 MUTEX_ENTER(&conn->conn_call_lock);
3271 MUTEX_ENTER(&conn->conn_data_lock);
3272 for (i = 0; i < RX_MAXCALLS; i++) {
3273 struct rx_call *tc = conn->call[i];
3274 if (tc && tc->state == RX_STATE_PRECALL) {
3280 /* Indicate that rxi_CheckReachEvent is no longer running by
3281 * clearing the flag. Must be atomic under conn_data_lock to
3282 * avoid a new call slipping by: rxi_CheckConnReach holds
3283 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3285 conn->flags &= ~RX_CONN_ATTACHWAIT;
3286 MUTEX_EXIT(&conn->conn_data_lock);
3287 MUTEX_EXIT(&conn->conn_call_lock);
3292 MUTEX_ENTER(&call->lock);
3293 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3295 MUTEX_EXIT(&call->lock);
3297 clock_GetTime(&now);
3299 when.sec += RX_CHECKREACH_TIMEOUT;
3300 MUTEX_ENTER(&conn->conn_data_lock);
3301 if (!conn->checkReachEvent) {
3303 conn->checkReachEvent =
3304 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3307 MUTEX_EXIT(&conn->conn_data_lock);
3313 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3315 struct rx_service *service = conn->service;
3316 struct rx_peer *peer = conn->peer;
3317 afs_uint32 now, lastReach;
3319 if (service->checkReach == 0)
3323 MUTEX_ENTER(&peer->peer_lock);
3324 lastReach = peer->lastReachTime;
3325 MUTEX_EXIT(&peer->peer_lock);
3326 if (now - lastReach < RX_CHECKREACH_TTL)
3329 MUTEX_ENTER(&conn->conn_data_lock);
3330 if (conn->flags & RX_CONN_ATTACHWAIT) {
3331 MUTEX_EXIT(&conn->conn_data_lock);
3334 conn->flags |= RX_CONN_ATTACHWAIT;
3335 MUTEX_EXIT(&conn->conn_data_lock);
3336 if (!conn->checkReachEvent)
3337 rxi_CheckReachEvent(NULL, conn, call);
3342 /* try to attach call, if authentication is complete */
3344 TryAttach(struct rx_call *acall, osi_socket socket,
3345 int *tnop, struct rx_call **newcallp,
3348 struct rx_connection *conn = acall->conn;
3350 if (conn->type == RX_SERVER_CONNECTION
3351 && acall->state == RX_STATE_PRECALL) {
3352 /* Don't attach until we have any req'd. authentication. */
3353 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3354 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3355 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3356 /* Note: this does not necessarily succeed; there
3357 * may not any proc available
3360 rxi_ChallengeOn(acall->conn);
3365 /* A data packet has been received off the interface. This packet is
3366 * appropriate to the call (the call is in the right state, etc.). This
3367 * routine can return a packet to the caller, for re-use */
3370 rxi_ReceiveDataPacket(struct rx_call *call,
3371 struct rx_packet *np, int istack,
3372 osi_socket socket, afs_uint32 host, u_short port,
3373 int *tnop, struct rx_call **newcallp)
3375 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3380 afs_uint32 serial=0, flags=0;
3382 struct rx_packet *tnp;
3383 struct clock when, now;
3384 if (rx_stats_active)
3385 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3388 /* If there are no packet buffers, drop this new packet, unless we can find
3389 * packet buffers from inactive calls */
3391 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3392 MUTEX_ENTER(&rx_freePktQ_lock);
3393 rxi_NeedMorePackets = TRUE;
3394 MUTEX_EXIT(&rx_freePktQ_lock);
3395 if (rx_stats_active)
3396 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3397 call->rprev = np->header.serial;
3398 rxi_calltrace(RX_TRACE_DROP, call);
3399 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3401 rxi_ClearReceiveQueue(call);
3402 clock_GetTime(&now);
3404 clock_Add(&when, &rx_softAckDelay);
3405 if (!call->delayedAckEvent
3406 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3407 rxevent_Cancel(call->delayedAckEvent, call,
3408 RX_CALL_REFCOUNT_DELAY);
3409 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3410 call->delayedAckEvent =
3411 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3413 /* we've damaged this call already, might as well do it in. */
3419 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3420 * packet is one of several packets transmitted as a single
3421 * datagram. Do not send any soft or hard acks until all packets
3422 * in a jumbogram have been processed. Send negative acks right away.
3424 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3425 /* tnp is non-null when there are more packets in the
3426 * current jumbo gram */
3433 seq = np->header.seq;
3434 serial = np->header.serial;
3435 flags = np->header.flags;
3437 /* If the call is in an error state, send an abort message */
3439 return rxi_SendCallAbort(call, np, istack, 0);
3441 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3442 * AFS 3.5 jumbogram. */
3443 if (flags & RX_JUMBO_PACKET) {
3444 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3449 if (np->header.spare != 0) {
3450 MUTEX_ENTER(&call->conn->conn_data_lock);
3451 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3452 MUTEX_EXIT(&call->conn->conn_data_lock);
3455 /* The usual case is that this is the expected next packet */
3456 if (seq == call->rnext) {
3458 /* Check to make sure it is not a duplicate of one already queued */
3459 if (queue_IsNotEmpty(&call->rq)
3460 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3461 if (rx_stats_active)
3462 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3463 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3464 rxevent_Cancel(call->delayedAckEvent, call,
3465 RX_CALL_REFCOUNT_DELAY);
3466 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3472 /* It's the next packet. Stick it on the receive queue
3473 * for this call. Set newPackets to make sure we wake
3474 * the reader once all packets have been processed */
3475 np->flags |= RX_PKTFLAG_RQ;
3476 queue_Prepend(&call->rq, np);
3477 #ifdef RXDEBUG_PACKET
3479 #endif /* RXDEBUG_PACKET */
3481 np = NULL; /* We can't use this anymore */
3484 /* If an ack is requested then set a flag to make sure we
3485 * send an acknowledgement for this packet */
3486 if (flags & RX_REQUEST_ACK) {
3487 ackNeeded = RX_ACK_REQUESTED;
3490 /* Keep track of whether we have received the last packet */
3491 if (flags & RX_LAST_PACKET) {
3492 call->flags |= RX_CALL_HAVE_LAST;
3496 /* Check whether we have all of the packets for this call */
3497 if (call->flags & RX_CALL_HAVE_LAST) {
3498 afs_uint32 tseq; /* temporary sequence number */
3499 struct rx_packet *tp; /* Temporary packet pointer */
3500 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3502 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3503 if (tseq != tp->header.seq)
3505 if (tp->header.flags & RX_LAST_PACKET) {
3506 call->flags |= RX_CALL_RECEIVE_DONE;
3513 /* Provide asynchronous notification for those who want it
3514 * (e.g. multi rx) */
3515 if (call->arrivalProc) {
3516 (*call->arrivalProc) (call, call->arrivalProcHandle,
3517 call->arrivalProcArg);
3518 call->arrivalProc = (void (*)())0;
3521 /* Update last packet received */
3524 /* If there is no server process serving this call, grab
3525 * one, if available. We only need to do this once. If a
3526 * server thread is available, this thread becomes a server
3527 * thread and the server thread becomes a listener thread. */
3529 TryAttach(call, socket, tnop, newcallp, 0);
3532 /* This is not the expected next packet. */
3534 /* Determine whether this is a new or old packet, and if it's
3535 * a new one, whether it fits into the current receive window.
3536 * Also figure out whether the packet was delivered in sequence.
3537 * We use the prev variable to determine whether the new packet
3538 * is the successor of its immediate predecessor in the
3539 * receive queue, and the missing flag to determine whether
3540 * any of this packets predecessors are missing. */
3542 afs_uint32 prev; /* "Previous packet" sequence number */
3543 struct rx_packet *tp; /* Temporary packet pointer */
3544 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3545 int missing; /* Are any predecessors missing? */
3547 /* If the new packet's sequence number has been sent to the
3548 * application already, then this is a duplicate */
3549 if (seq < call->rnext) {
3550 if (rx_stats_active)
3551 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3552 rxevent_Cancel(call->delayedAckEvent, call,
3553 RX_CALL_REFCOUNT_DELAY);
3554 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3560 /* If the sequence number is greater than what can be
3561 * accomodated by the current window, then send a negative
3562 * acknowledge and drop the packet */
3563 if ((call->rnext + call->rwind) <= seq) {
3564 rxevent_Cancel(call->delayedAckEvent, call,
3565 RX_CALL_REFCOUNT_DELAY);
3566 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3573 /* Look for the packet in the queue of old received packets */
3574 for (prev = call->rnext - 1, missing =
3575 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3576 /*Check for duplicate packet */
3577 if (seq == tp->header.seq) {
3578 if (rx_stats_active)
3579 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3580 rxevent_Cancel(call->delayedAckEvent, call,
3581 RX_CALL_REFCOUNT_DELAY);
3582 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3588 /* If we find a higher sequence packet, break out and
3589 * insert the new packet here. */
3590 if (seq < tp->header.seq)
3592 /* Check for missing packet */
3593 if (tp->header.seq != prev + 1) {
3597 prev = tp->header.seq;
3600 /* Keep track of whether we have received the last packet. */
3601 if (flags & RX_LAST_PACKET) {
3602 call->flags |= RX_CALL_HAVE_LAST;
3605 /* It's within the window: add it to the the receive queue.
3606 * tp is left by the previous loop either pointing at the
3607 * packet before which to insert the new packet, or at the
3608 * queue head if the queue is empty or the packet should be
3610 np->flags |= RX_PKTFLAG_RQ;
3611 #ifdef RXDEBUG_PACKET
3613 #endif /* RXDEBUG_PACKET */
3614 queue_InsertBefore(tp, np);
3618 /* Check whether we have all of the packets for this call */
3619 if ((call->flags & RX_CALL_HAVE_LAST)
3620 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3621 afs_uint32 tseq; /* temporary sequence number */
3624 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3625 if (tseq != tp->header.seq)
3627 if (tp->header.flags & RX_LAST_PACKET) {
3628 call->flags |= RX_CALL_RECEIVE_DONE;
3635 /* We need to send an ack of the packet is out of sequence,
3636 * or if an ack was requested by the peer. */
3637 if (seq != prev + 1 || missing) {
3638 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3639 } else if (flags & RX_REQUEST_ACK) {
3640 ackNeeded = RX_ACK_REQUESTED;
3643 /* Acknowledge the last packet for each call */
3644 if (flags & RX_LAST_PACKET) {
3655 * If the receiver is waiting for an iovec, fill the iovec
3656 * using the data from the receive queue */
3657 if (call->flags & RX_CALL_IOVEC_WAIT) {
3658 didHardAck = rxi_FillReadVec(call, serial);
3659 /* the call may have been aborted */
3668 /* Wakeup the reader if any */
3669 if ((call->flags & RX_CALL_READER_WAIT)
3670 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3671 || (call->iovNext >= call->iovMax)
3672 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3673 call->flags &= ~RX_CALL_READER_WAIT;
3674 #ifdef RX_ENABLE_LOCKS
3675 CV_BROADCAST(&call->cv_rq);
3677 osi_rxWakeup(&call->rq);
3683 * Send an ack when requested by the peer, or once every
3684 * rxi_SoftAckRate packets until the last packet has been
3685 * received. Always send a soft ack for the last packet in
3686 * the server's reply. */
3688 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3689 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3690 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3691 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3692 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3693 } else if (call->nSoftAcks) {
3694 clock_GetTime(&now);
3696 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3697 clock_Add(&when, &rx_lastAckDelay);
3699 clock_Add(&when, &rx_softAckDelay);
3701 if (!call->delayedAckEvent
3702 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3703 rxevent_Cancel(call->delayedAckEvent, call,
3704 RX_CALL_REFCOUNT_DELAY);
3705 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3706 call->delayedAckEvent =
3707 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3709 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3710 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3717 static void rxi_ComputeRate();
3721 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3723 struct rx_peer *peer = conn->peer;
3725 MUTEX_ENTER(&peer->peer_lock);
3726 peer->lastReachTime = clock_Sec();
3727 MUTEX_EXIT(&peer->peer_lock);
3729 MUTEX_ENTER(&conn->conn_data_lock);
3730 if (conn->flags & RX_CONN_ATTACHWAIT) {
3733 conn->flags &= ~RX_CONN_ATTACHWAIT;
3734 MUTEX_EXIT(&conn->conn_data_lock);
3736 for (i = 0; i < RX_MAXCALLS; i++) {
3737 struct rx_call *call = conn->call[i];
3740 MUTEX_ENTER(&call->lock);
3741 /* tnop can be null if newcallp is null */
3742 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3744 MUTEX_EXIT(&call->lock);
3748 MUTEX_EXIT(&conn->conn_data_lock);
3751 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3753 rx_ack_reason(int reason)
3756 case RX_ACK_REQUESTED:
3758 case RX_ACK_DUPLICATE:
3760 case RX_ACK_OUT_OF_SEQUENCE:
3762 case RX_ACK_EXCEEDS_WINDOW:
3764 case RX_ACK_NOSPACE:
3768 case RX_ACK_PING_RESPONSE:
3781 /* rxi_ComputePeerNetStats
3783 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3784 * estimates (like RTT and throughput) based on ack packets. Caller
3785 * must ensure that the packet in question is the right one (i.e.
3786 * serial number matches).
3789 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3790 struct rx_ackPacket *ap, struct rx_packet *np)
3792 struct rx_peer *peer = call->conn->peer;
3794 /* Use RTT if not delayed by client and
3795 * ignore packets that were retransmitted. */
3796 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3797 ap->reason != RX_ACK_DELAY &&
3798 clock_Eq(&p->timeSent, &p->firstSent))
3799 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3801 rxi_ComputeRate(peer, call, p, np, ap->reason);
3805 /* The real smarts of the whole thing. */
3807 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3810 struct rx_ackPacket *ap;
3812 struct rx_packet *tp;
3813 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3814 struct rx_connection *conn = call->conn;
3815 struct rx_peer *peer = conn->peer;
3818 /* because there are CM's that are bogus, sending weird values for this. */
3819 afs_uint32 skew = 0;
3825 int newAckCount = 0;
3826 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3827 int pktsize = 0; /* Set if we need to update the peer mtu */
3829 if (rx_stats_active)
3830 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3831 ap = (struct rx_ackPacket *)rx_DataOf(np);
3832 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3834 return np; /* truncated ack packet */
3836 /* depends on ack packet struct */
3837 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3838 first = ntohl(ap->firstPacket);
3839 serial = ntohl(ap->serial);
3840 /* temporarily disabled -- needs to degrade over time
3841 * skew = ntohs(ap->maxSkew); */
3843 /* Ignore ack packets received out of order */
3844 if (first < call->tfirst) {
3848 if (np->header.flags & RX_SLOW_START_OK) {
3849 call->flags |= RX_CALL_SLOW_START_OK;
3852 if (ap->reason == RX_ACK_PING_RESPONSE)
3853 rxi_UpdatePeerReach(conn, call);
3855 if (conn->lastPacketSizeSeq) {
3856 MUTEX_ENTER(&conn->conn_data_lock);
3857 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
3858 pktsize = conn->lastPacketSize;
3859 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
3861 MUTEX_EXIT(&conn->conn_data_lock);
3863 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
3864 MUTEX_ENTER(&conn->conn_data_lock);
3865 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
3866 /* process mtu ping ack */
3867 pktsize = conn->lastPingSize;
3868 conn->lastPingSizeSer = conn->lastPingSize = 0;
3870 MUTEX_EXIT(&conn->conn_data_lock);
3874 MUTEX_ENTER(&peer->peer_lock);
3876 * Start somewhere. Can't assume we can send what we can receive,
3877 * but we are clearly receiving.
3879 if (!peer->maxPacketSize)
3880 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
3882 if (pktsize > peer->maxPacketSize) {
3883 peer->maxPacketSize = pktsize;
3884 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
3885 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
3886 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
3887 rxi_ScheduleGrowMTUEvent(call, 1);
3890 MUTEX_EXIT(&peer->peer_lock);
3895 if (rxdebug_active) {
3899 len = _snprintf(msg, sizeof(msg),
3900 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3901 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3902 ntohl(ap->serial), ntohl(ap->previousPacket),
3903 (unsigned int)np->header.seq, (unsigned int)skew,
3904 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3908 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3909 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3913 OutputDebugString(msg);
3915 #else /* AFS_NT40_ENV */
3918 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3919 ap->reason, ntohl(ap->previousPacket),
3920 (unsigned int)np->header.seq, (unsigned int)serial,
3921 (unsigned int)skew, ntohl(ap->firstPacket));
3924 for (offset = 0; offset < nAcks; offset++)
3925 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3930 #endif /* AFS_NT40_ENV */
3933 /* Update the outgoing packet skew value to the latest value of
3934 * the peer's incoming packet skew value. The ack packet, of
3935 * course, could arrive out of order, but that won't affect things
3937 MUTEX_ENTER(&peer->peer_lock);
3938 peer->outPacketSkew = skew;
3940 /* Check for packets that no longer need to be transmitted, and
3941 * discard them. This only applies to packets positively
3942 * acknowledged as having been sent to the peer's upper level.
3943 * All other packets must be retained. So only packets with
3944 * sequence numbers < ap->firstPacket are candidates. */
3945 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3946 if (tp->header.seq >= first)
3948 call->tfirst = tp->header.seq + 1;
3949 rxi_ComputePeerNetStats(call, tp, ap, np);
3950 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3953 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3954 /* XXX Hack. Because we have to release the global rx lock when sending
3955 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3956 * in rxi_Start sending packets out because packets may move to the
3957 * freePacketQueue as result of being here! So we drop these packets until
3958 * we're safely out of the traversing. Really ugly!
3959 * To make it even uglier, if we're using fine grain locking, we can
3960 * set the ack bits in the packets and have rxi_Start remove the packets
3961 * when it's done transmitting.
3963 if (call->flags & RX_CALL_TQ_BUSY) {
3964 #ifdef RX_ENABLE_LOCKS
3965 tp->flags |= RX_PKTFLAG_ACKED;
3966 call->flags |= RX_CALL_TQ_SOME_ACKED;
3967 #else /* RX_ENABLE_LOCKS */
3969 #endif /* RX_ENABLE_LOCKS */
3971 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3974 tp->flags &= ~RX_PKTFLAG_TQ;
3975 #ifdef RXDEBUG_PACKET
3977 #endif /* RXDEBUG_PACKET */
3978 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3983 /* Give rate detector a chance to respond to ping requests */
3984 if (ap->reason == RX_ACK_PING_RESPONSE) {
3985 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3989 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3991 /* Now go through explicit acks/nacks and record the results in
3992 * the waiting packets. These are packets that can't be released
3993 * yet, even with a positive acknowledge. This positive
3994 * acknowledge only means the packet has been received by the
3995 * peer, not that it will be retained long enough to be sent to
3996 * the peer's upper level. In addition, reset the transmit timers
3997 * of any missing packets (those packets that must be missing
3998 * because this packet was out of sequence) */
4000 call->nSoftAcked = 0;
4001 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4002 /* Update round trip time if the ack was stimulated on receipt
4004 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4005 #ifdef RX_ENABLE_LOCKS
4006 if (tp->header.seq >= first)
4007 #endif /* RX_ENABLE_LOCKS */
4008 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4009 rxi_ComputePeerNetStats(call, tp, ap, np);
4011 /* Set the acknowledge flag per packet based on the
4012 * information in the ack packet. An acknowlegded packet can
4013 * be downgraded when the server has discarded a packet it
4014 * soacked previously, or when an ack packet is received
4015 * out of sequence. */
4016 if (tp->header.seq < first) {
4017 /* Implicit ack information */
4018 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4021 tp->flags |= RX_PKTFLAG_ACKED;
4022 } else if (tp->header.seq < first + nAcks) {
4023 /* Explicit ack information: set it in the packet appropriately */
4024 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4025 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4027 tp->flags |= RX_PKTFLAG_ACKED;
4034 } else /* RX_ACK_TYPE_NACK */ {
4035 tp->flags &= ~RX_PKTFLAG_ACKED;
4039 tp->flags &= ~RX_PKTFLAG_ACKED;
4044 * Following the suggestion of Phil Kern, we back off the peer's
4045 * timeout value for future packets until a successful response
4046 * is received for an initial transmission.
4048 if (missing && !backedOff) {
4049 struct clock c = peer->timeout;
4050 struct clock max_to = {3, 0};
4052 clock_Add(&peer->timeout, &c);
4053 if (clock_Gt(&peer->timeout, &max_to))
4054 peer->timeout = max_to;
4058 /* If packet isn't yet acked, and it has been transmitted at least
4059 * once, reset retransmit time using latest timeout
4060 * ie, this should readjust the retransmit timer for all outstanding
4061 * packets... So we don't just retransmit when we should know better*/
4063 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4064 tp->retryTime = tp->timeSent;
4065 clock_Add(&tp->retryTime, &peer->timeout);
4066 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4067 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4071 /* If the window has been extended by this acknowledge packet,
4072 * then wakeup a sender waiting in alloc for window space, or try
4073 * sending packets now, if he's been sitting on packets due to
4074 * lack of window space */
4075 if (call->tnext < (call->tfirst + call->twind)) {
4076 #ifdef RX_ENABLE_LOCKS
4077 CV_SIGNAL(&call->cv_twind);
4079 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4080 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4081 osi_rxWakeup(&call->twind);
4084 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4085 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4089 /* if the ack packet has a receivelen field hanging off it,
4090 * update our state */
4091 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4094 /* If the ack packet has a "recommended" size that is less than
4095 * what I am using now, reduce my size to match */
4096 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4097 (int)sizeof(afs_int32), &tSize);
4098 tSize = (afs_uint32) ntohl(tSize);
4099 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4101 /* Get the maximum packet size to send to this peer */
4102 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4104 tSize = (afs_uint32) ntohl(tSize);
4105 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4106 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4108 /* sanity check - peer might have restarted with different params.
4109 * If peer says "send less", dammit, send less... Peer should never
4110 * be unable to accept packets of the size that prior AFS versions would
4111 * send without asking. */
4112 if (peer->maxMTU != tSize) {
4113 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4115 peer->maxMTU = tSize;
4116 peer->MTU = MIN(tSize, peer->MTU);
4117 call->MTU = MIN(call->MTU, tSize);
4120 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4123 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4124 (int)sizeof(afs_int32), &tSize);
4125 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4126 if (tSize < call->twind) { /* smaller than our send */
4127 call->twind = tSize; /* window, we must send less... */
4128 call->ssthresh = MIN(call->twind, call->ssthresh);
4129 call->conn->twind[call->channel] = call->twind;
4132 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4133 * network MTU confused with the loopback MTU. Calculate the
4134 * maximum MTU here for use in the slow start code below.
4136 /* Did peer restart with older RX version? */
4137 if (peer->maxDgramPackets > 1) {
4138 peer->maxDgramPackets = 1;
4140 } else if (np->length >=
4141 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4144 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4145 sizeof(afs_int32), &tSize);
4146 tSize = (afs_uint32) ntohl(tSize);
4148 * As of AFS 3.5 we set the send window to match the receive window.
4150 if (tSize < call->twind) {
4151 call->twind = tSize;
4152 call->conn->twind[call->channel] = call->twind;
4153 call->ssthresh = MIN(call->twind, call->ssthresh);
4154 } else if (tSize > call->twind) {
4155 call->twind = tSize;
4156 call->conn->twind[call->channel] = call->twind;
4160 * As of AFS 3.5, a jumbogram is more than one fixed size
4161 * packet transmitted in a single UDP datagram. If the remote
4162 * MTU is smaller than our local MTU then never send a datagram
4163 * larger than the natural MTU.
4166 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4167 (int)sizeof(afs_int32), &tSize);
4168 maxDgramPackets = (afs_uint32) ntohl(tSize);
4169 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4171 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4172 maxDgramPackets = MIN(maxDgramPackets, tSize);
4173 if (maxDgramPackets > 1) {
4174 peer->maxDgramPackets = maxDgramPackets;
4175 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4177 peer->maxDgramPackets = 1;
4178 call->MTU = peer->natMTU;
4180 } else if (peer->maxDgramPackets > 1) {
4181 /* Restarted with lower version of RX */
4182 peer->maxDgramPackets = 1;
4184 } else if (peer->maxDgramPackets > 1
4185 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4186 /* Restarted with lower version of RX */
4187 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4188 peer->natMTU = OLD_MAX_PACKET_SIZE;
4189 peer->MTU = OLD_MAX_PACKET_SIZE;
4190 peer->maxDgramPackets = 1;
4191 peer->nDgramPackets = 1;
4193 call->MTU = OLD_MAX_PACKET_SIZE;
4198 * Calculate how many datagrams were successfully received after
4199 * the first missing packet and adjust the negative ack counter
4204 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4205 if (call->nNacks < nNacked) {
4206 call->nNacks = nNacked;
4209 call->nAcks += newAckCount;
4213 if (call->flags & RX_CALL_FAST_RECOVER) {
4215 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4217 call->flags &= ~RX_CALL_FAST_RECOVER;
4218 call->cwind = call->nextCwind;
4219 call->nextCwind = 0;
4222 call->nCwindAcks = 0;
4223 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4224 /* Three negative acks in a row trigger congestion recovery */
4225 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4226 MUTEX_EXIT(&peer->peer_lock);
4227 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4228 /* someone else is waiting to start recovery */
4231 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4232 rxi_WaitforTQBusy(call);
4233 MUTEX_ENTER(&peer->peer_lock);
4234 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4235 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4236 call->flags |= RX_CALL_FAST_RECOVER;
4237 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4239 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4240 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4241 call->nextCwind = call->ssthresh;
4244 peer->MTU = call->MTU;
4245 peer->cwind = call->nextCwind;
4246 peer->nDgramPackets = call->nDgramPackets;
4248 call->congestSeq = peer->congestSeq;
4249 /* Reset the resend times on the packets that were nacked
4250 * so we will retransmit as soon as the window permits*/
4251 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4253 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4254 clock_Zero(&tp->retryTime);
4256 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4261 /* If cwind is smaller than ssthresh, then increase
4262 * the window one packet for each ack we receive (exponential
4264 * If cwind is greater than or equal to ssthresh then increase
4265 * the congestion window by one packet for each cwind acks we
4266 * receive (linear growth). */
4267 if (call->cwind < call->ssthresh) {
4269 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4270 call->nCwindAcks = 0;
4272 call->nCwindAcks += newAckCount;
4273 if (call->nCwindAcks >= call->cwind) {
4274 call->nCwindAcks = 0;
4275 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4279 * If we have received several acknowledgements in a row then
4280 * it is time to increase the size of our datagrams
4282 if ((int)call->nAcks > rx_nDgramThreshold) {
4283 if (peer->maxDgramPackets > 1) {
4284 if (call->nDgramPackets < peer->maxDgramPackets) {
4285 call->nDgramPackets++;
4287 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4288 } else if (call->MTU < peer->maxMTU) {
4289 /* don't upgrade if we can't handle it */
4290 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4291 call->MTU = peer->ifMTU;
4293 call->MTU += peer->natMTU;
4294 call->MTU = MIN(call->MTU, peer->maxMTU);
4301 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4303 /* Servers need to hold the call until all response packets have
4304 * been acknowledged. Soft acks are good enough since clients
4305 * are not allowed to clear their receive queues. */
4306 if (call->state == RX_STATE_HOLD
4307 && call->tfirst + call->nSoftAcked >= call->tnext) {
4308 call->state = RX_STATE_DALLY;
4309 rxi_ClearTransmitQueue(call, 0);
4310 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4311 } else if (!queue_IsEmpty(&call->tq)) {
4312 rxi_Start(0, call, 0, istack);
4317 /* Received a response to a challenge packet */
4319 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4320 struct rx_packet *np, int istack)
4324 /* Ignore the packet if we're the client */
4325 if (conn->type == RX_CLIENT_CONNECTION)
4328 /* If already authenticated, ignore the packet (it's probably a retry) */
4329 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4332 /* Otherwise, have the security object evaluate the response packet */
4333 error = RXS_CheckResponse(conn->securityObject, conn, np);
4335 /* If the response is invalid, reset the connection, sending
4336 * an abort to the peer */
4340 rxi_ConnectionError(conn, error);
4341 MUTEX_ENTER(&conn->conn_data_lock);
4342 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4343 MUTEX_EXIT(&conn->conn_data_lock);
4346 /* If the response is valid, any calls waiting to attach
4347 * servers can now do so */
4350 for (i = 0; i < RX_MAXCALLS; i++) {
4351 struct rx_call *call = conn->call[i];
4353 MUTEX_ENTER(&call->lock);
4354 if (call->state == RX_STATE_PRECALL)
4355 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4356 /* tnop can be null if newcallp is null */
4357 MUTEX_EXIT(&call->lock);
4361 /* Update the peer reachability information, just in case
4362 * some calls went into attach-wait while we were waiting
4363 * for authentication..
4365 rxi_UpdatePeerReach(conn, NULL);
4370 /* A client has received an authentication challenge: the security
4371 * object is asked to cough up a respectable response packet to send
4372 * back to the server. The server is responsible for retrying the
4373 * challenge if it fails to get a response. */
4376 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4377 struct rx_packet *np, int istack)
4381 /* Ignore the challenge if we're the server */
4382 if (conn->type == RX_SERVER_CONNECTION)
4385 /* Ignore the challenge if the connection is otherwise idle; someone's
4386 * trying to use us as an oracle. */
4387 if (!rxi_HasActiveCalls(conn))
4390 /* Send the security object the challenge packet. It is expected to fill
4391 * in the response. */
4392 error = RXS_GetResponse(conn->securityObject, conn, np);
4394 /* If the security object is unable to return a valid response, reset the
4395 * connection and send an abort to the peer. Otherwise send the response
4396 * packet to the peer connection. */
4398 rxi_ConnectionError(conn, error);
4399 MUTEX_ENTER(&conn->conn_data_lock);
4400 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4401 MUTEX_EXIT(&conn->conn_data_lock);
4403 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4404 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4410 /* Find an available server process to service the current request in
4411 * the given call structure. If one isn't available, queue up this
4412 * call so it eventually gets one */
4414 rxi_AttachServerProc(struct rx_call *call,
4415 osi_socket socket, int *tnop,
4416 struct rx_call **newcallp)
4418 struct rx_serverQueueEntry *sq;
4419 struct rx_service *service = call->conn->service;
4422 /* May already be attached */
4423 if (call->state == RX_STATE_ACTIVE)
4426 MUTEX_ENTER(&rx_serverPool_lock);
4428 haveQuota = QuotaOK(service);
4429 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4430 /* If there are no processes available to service this call,
4431 * put the call on the incoming call queue (unless it's
4432 * already on the queue).
4434 #ifdef RX_ENABLE_LOCKS
4436 ReturnToServerPool(service);
4437 #endif /* RX_ENABLE_LOCKS */
4439 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4440 call->flags |= RX_CALL_WAIT_PROC;
4441 MUTEX_ENTER(&rx_waiting_mutex);
4444 MUTEX_EXIT(&rx_waiting_mutex);
4445 rxi_calltrace(RX_CALL_ARRIVAL, call);
4446 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4447 queue_Append(&rx_incomingCallQueue, call);
4450 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4452 /* If hot threads are enabled, and both newcallp and sq->socketp
4453 * are non-null, then this thread will process the call, and the
4454 * idle server thread will start listening on this threads socket.
4457 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4460 *sq->socketp = socket;
4461 clock_GetTime(&call->startTime);
4462 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4466 if (call->flags & RX_CALL_WAIT_PROC) {
4467 /* Conservative: I don't think this should happen */
4468 call->flags &= ~RX_CALL_WAIT_PROC;
4469 if (queue_IsOnQueue(call)) {
4472 MUTEX_ENTER(&rx_waiting_mutex);
4474 MUTEX_EXIT(&rx_waiting_mutex);
4477 call->state = RX_STATE_ACTIVE;
4478 call->mode = RX_MODE_RECEIVING;
4479 #ifdef RX_KERNEL_TRACE
4481 int glockOwner = ISAFS_GLOCK();
4484 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4485 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4491 if (call->flags & RX_CALL_CLEARED) {
4492 /* send an ack now to start the packet flow up again */
4493 call->flags &= ~RX_CALL_CLEARED;
4494 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4496 #ifdef RX_ENABLE_LOCKS
4499 service->nRequestsRunning++;
4500 MUTEX_ENTER(&rx_quota_mutex);
4501 if (service->nRequestsRunning <= service->minProcs)
4504 MUTEX_EXIT(&rx_quota_mutex);
4508 MUTEX_EXIT(&rx_serverPool_lock);
4511 /* Delay the sending of an acknowledge event for a short while, while
4512 * a new call is being prepared (in the case of a client) or a reply
4513 * is being prepared (in the case of a server). Rather than sending
4514 * an ack packet, an ACKALL packet is sent. */
4516 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4518 #ifdef RX_ENABLE_LOCKS
4520 MUTEX_ENTER(&call->lock);
4521 call->delayedAckEvent = NULL;
4522 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4524 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4525 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4527 MUTEX_EXIT(&call->lock);
4528 #else /* RX_ENABLE_LOCKS */
4530 call->delayedAckEvent = NULL;
4531 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4532 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4533 #endif /* RX_ENABLE_LOCKS */
4537 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4539 struct rx_call *call = arg1;
4540 #ifdef RX_ENABLE_LOCKS
4542 MUTEX_ENTER(&call->lock);
4543 if (event == call->delayedAckEvent)
4544 call->delayedAckEvent = NULL;
4545 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4547 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4549 MUTEX_EXIT(&call->lock);
4550 #else /* RX_ENABLE_LOCKS */
4552 call->delayedAckEvent = NULL;
4553 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4554 #endif /* RX_ENABLE_LOCKS */
4558 #ifdef RX_ENABLE_LOCKS
4559 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4560 * clearing them out.
4563 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4565 struct rx_packet *p, *tp;
4568 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4569 p->flags |= RX_PKTFLAG_ACKED;
4573 call->flags |= RX_CALL_TQ_CLEARME;
4574 call->flags |= RX_CALL_TQ_SOME_ACKED;
4577 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4578 call->tfirst = call->tnext;
4579 call->nSoftAcked = 0;
4581 if (call->flags & RX_CALL_FAST_RECOVER) {
4582 call->flags &= ~RX_CALL_FAST_RECOVER;
4583 call->cwind = call->nextCwind;
4584 call->nextCwind = 0;
4587 CV_SIGNAL(&call->cv_twind);
4589 #endif /* RX_ENABLE_LOCKS */
4591 /* Clear out the transmit queue for the current call (all packets have
4592 * been received by peer) */
4594 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4596 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4597 struct rx_packet *p, *tp;
4599 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4601 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4602 p->flags |= RX_PKTFLAG_ACKED;
4606 call->flags |= RX_CALL_TQ_CLEARME;
4607 call->flags |= RX_CALL_TQ_SOME_ACKED;
4610 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4611 #ifdef RXDEBUG_PACKET
4613 #endif /* RXDEBUG_PACKET */
4614 rxi_FreePackets(0, &call->tq);
4615 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
4616 #ifdef RX_ENABLE_LOCKS
4617 CV_BROADCAST(&call->cv_tq);
4618 #else /* RX_ENABLE_LOCKS */
4619 osi_rxWakeup(&call->tq);
4620 #endif /* RX_ENABLE_LOCKS */
4622 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4623 call->flags &= ~RX_CALL_TQ_CLEARME;
4625 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4627 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4628 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4629 call->nSoftAcked = 0;
4631 if (call->flags & RX_CALL_FAST_RECOVER) {
4632 call->flags &= ~RX_CALL_FAST_RECOVER;
4633 call->cwind = call->nextCwind;
4635 #ifdef RX_ENABLE_LOCKS
4636 CV_SIGNAL(&call->cv_twind);
4638 osi_rxWakeup(&call->twind);
4643 rxi_ClearReceiveQueue(struct rx_call *call)
4645 if (queue_IsNotEmpty(&call->rq)) {
4648 count = rxi_FreePackets(0, &call->rq);
4649 rx_packetReclaims += count;
4650 #ifdef RXDEBUG_PACKET
4652 if ( call->rqc != 0 )
4653 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0", call, call->rqc));
4655 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4657 if (call->state == RX_STATE_PRECALL) {
4658 call->flags |= RX_CALL_CLEARED;
4662 /* Send an abort packet for the specified call */
4664 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4665 int istack, int force)
4668 struct clock when, now;
4673 /* Clients should never delay abort messages */
4674 if (rx_IsClientConn(call->conn))
4677 if (call->abortCode != call->error) {
4678 call->abortCode = call->error;
4679 call->abortCount = 0;
4682 if (force || rxi_callAbortThreshhold == 0
4683 || call->abortCount < rxi_callAbortThreshhold) {
4684 if (call->delayedAbortEvent) {
4685 rxevent_Cancel(call->delayedAbortEvent, call,
4686 RX_CALL_REFCOUNT_ABORT);
4688 error = htonl(call->error);
4691 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4692 (char *)&error, sizeof(error), istack);
4693 } else if (!call->delayedAbortEvent) {
4694 clock_GetTime(&now);
4696 clock_Addmsec(&when, rxi_callAbortDelay);
4697 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4698 call->delayedAbortEvent =
4699 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4704 /* Send an abort packet for the specified connection. Packet is an
4705 * optional pointer to a packet that can be used to send the abort.
4706 * Once the number of abort messages reaches the threshhold, an
4707 * event is scheduled to send the abort. Setting the force flag
4708 * overrides sending delayed abort messages.
4710 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4711 * to send the abort packet.
4714 rxi_SendConnectionAbort(struct rx_connection *conn,
4715 struct rx_packet *packet, int istack, int force)
4718 struct clock when, now;
4723 /* Clients should never delay abort messages */
4724 if (rx_IsClientConn(conn))
4727 if (force || rxi_connAbortThreshhold == 0
4728 || conn->abortCount < rxi_connAbortThreshhold) {
4729 if (conn->delayedAbortEvent) {
4730 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4732 error = htonl(conn->error);
4734 MUTEX_EXIT(&conn->conn_data_lock);
4736 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4737 RX_PACKET_TYPE_ABORT, (char *)&error,
4738 sizeof(error), istack);
4739 MUTEX_ENTER(&conn->conn_data_lock);
4740 } else if (!conn->delayedAbortEvent) {
4741 clock_GetTime(&now);
4743 clock_Addmsec(&when, rxi_connAbortDelay);
4744 conn->delayedAbortEvent =
4745 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4750 /* Associate an error all of the calls owned by a connection. Called
4751 * with error non-zero. This is only for really fatal things, like
4752 * bad authentication responses. The connection itself is set in
4753 * error at this point, so that future packets received will be
4756 rxi_ConnectionError(struct rx_connection *conn,
4762 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d", conn, error));
4764 MUTEX_ENTER(&conn->conn_data_lock);
4765 if (conn->challengeEvent)
4766 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4767 if (conn->natKeepAliveEvent)
4768 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
4769 if (conn->checkReachEvent) {
4770 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4771 conn->checkReachEvent = 0;
4772 conn->flags &= ~RX_CONN_ATTACHWAIT;
4775 MUTEX_EXIT(&conn->conn_data_lock);
4776 for (i = 0; i < RX_MAXCALLS; i++) {
4777 struct rx_call *call = conn->call[i];
4779 MUTEX_ENTER(&call->lock);
4780 rxi_CallError(call, error);
4781 MUTEX_EXIT(&call->lock);
4784 conn->error = error;
4785 if (rx_stats_active)
4786 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4791 rxi_CallError(struct rx_call *call, afs_int32 error)
4794 osirx_AssertMine(&call->lock, "rxi_CallError");
4796 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d", call, error, call->error));
4798 error = call->error;
4800 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4801 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4802 rxi_ResetCall(call, 0);
4805 rxi_ResetCall(call, 0);
4807 call->error = error;
4808 call->mode = RX_MODE_ERROR;
4811 /* Reset various fields in a call structure, and wakeup waiting
4812 * processes. Some fields aren't changed: state & mode are not
4813 * touched (these must be set by the caller), and bufptr, nLeft, and
4814 * nFree are not reset, since these fields are manipulated by
4815 * unprotected macros, and may only be reset by non-interrupting code.
4818 /* this code requires that call->conn be set properly as a pre-condition. */
4819 #endif /* ADAPT_WINDOW */
4822 rxi_ResetCall(struct rx_call *call, int newcall)
4825 struct rx_peer *peer;
4826 struct rx_packet *packet;
4828 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4830 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
4832 /* Notify anyone who is waiting for asynchronous packet arrival */
4833 if (call->arrivalProc) {
4834 (*call->arrivalProc) (call, call->arrivalProcHandle,
4835 call->arrivalProcArg);
4836 call->arrivalProc = (void (*)())0;
4839 if (call->delayedAbortEvent) {
4840 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4841 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4843 rxi_SendCallAbort(call, packet, 0, 1);
4844 rxi_FreePacket(packet);
4849 * Update the peer with the congestion information in this call
4850 * so other calls on this connection can pick up where this call
4851 * left off. If the congestion sequence numbers don't match then
4852 * another call experienced a retransmission.
4854 peer = call->conn->peer;
4855 MUTEX_ENTER(&peer->peer_lock);
4857 if (call->congestSeq == peer->congestSeq) {
4858 peer->cwind = MAX(peer->cwind, call->cwind);
4859 peer->MTU = MAX(peer->MTU, call->MTU);
4860 peer->nDgramPackets =
4861 MAX(peer->nDgramPackets, call->nDgramPackets);
4864 call->abortCode = 0;
4865 call->abortCount = 0;
4867 if (peer->maxDgramPackets > 1) {
4868 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4870 call->MTU = peer->MTU;
4872 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4873 call->ssthresh = rx_maxSendWindow;
4874 call->nDgramPackets = peer->nDgramPackets;
4875 call->congestSeq = peer->congestSeq;
4876 MUTEX_EXIT(&peer->peer_lock);
4878 flags = call->flags;
4879 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4880 rxi_WaitforTQBusy(call);
4881 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4883 rxi_ClearTransmitQueue(call, 1);
4884 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4885 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4889 rxi_ClearReceiveQueue(call);
4890 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4892 if (call->currentPacket) {
4893 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4894 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4895 queue_Prepend(&call->iovq, call->currentPacket);
4896 #ifdef RXDEBUG_PACKET
4898 #endif /* RXDEBUG_PACKET */
4899 call->currentPacket = (struct rx_packet *)0;
4901 call->curlen = call->nLeft = call->nFree = 0;
4903 #ifdef RXDEBUG_PACKET
4906 rxi_FreePackets(0, &call->iovq);
4909 call->twind = call->conn->twind[call->channel];
4910 call->rwind = call->conn->rwind[call->channel];
4911 call->nSoftAcked = 0;
4912 call->nextCwind = 0;
4915 call->nCwindAcks = 0;
4916 call->nSoftAcks = 0;
4917 call->nHardAcks = 0;
4919 call->tfirst = call->rnext = call->tnext = 1;
4921 call->lastAcked = 0;
4922 call->localStatus = call->remoteStatus = 0;
4924 if (flags & RX_CALL_READER_WAIT) {
4925 #ifdef RX_ENABLE_LOCKS
4926 CV_BROADCAST(&call->cv_rq);
4928 osi_rxWakeup(&call->rq);
4931 if (flags & RX_CALL_WAIT_PACKETS) {
4932 MUTEX_ENTER(&rx_freePktQ_lock);
4933 rxi_PacketsUnWait(); /* XXX */
4934 MUTEX_EXIT(&rx_freePktQ_lock);
4936 #ifdef RX_ENABLE_LOCKS
4937 CV_SIGNAL(&call->cv_twind);
4939 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4940 osi_rxWakeup(&call->twind);
4943 #ifdef RX_ENABLE_LOCKS
4944 /* The following ensures that we don't mess with any queue while some
4945 * other thread might also be doing so. The call_queue_lock field is
4946 * is only modified under the call lock. If the call is in the process
4947 * of being removed from a queue, the call is not locked until the
4948 * the queue lock is dropped and only then is the call_queue_lock field
4949 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4950 * Note that any other routine which removes a call from a queue has to
4951 * obtain the queue lock before examing the queue and removing the call.
4953 if (call->call_queue_lock) {
4954 MUTEX_ENTER(call->call_queue_lock);
4955 if (queue_IsOnQueue(call)) {
4957 if (flags & RX_CALL_WAIT_PROC) {
4959 MUTEX_ENTER(&rx_waiting_mutex);
4961 MUTEX_EXIT(&rx_waiting_mutex);
4964 MUTEX_EXIT(call->call_queue_lock);
4965 CLEAR_CALL_QUEUE_LOCK(call);
4967 #else /* RX_ENABLE_LOCKS */
4968 if (queue_IsOnQueue(call)) {
4970 if (flags & RX_CALL_WAIT_PROC)
4973 #endif /* RX_ENABLE_LOCKS */
4975 rxi_KeepAliveOff(call);
4976 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4979 /* Send an acknowledge for the indicated packet (seq,serial) of the
4980 * indicated call, for the indicated reason (reason). This
4981 * acknowledge will specifically acknowledge receiving the packet, and
4982 * will also specify which other packets for this call have been
4983 * received. This routine returns the packet that was used to the
4984 * caller. The caller is responsible for freeing it or re-using it.
4985 * This acknowledgement also returns the highest sequence number
4986 * actually read out by the higher level to the sender; the sender
4987 * promises to keep around packets that have not been read by the
4988 * higher level yet (unless, of course, the sender decides to abort
4989 * the call altogether). Any of p, seq, serial, pflags, or reason may
4990 * be set to zero without ill effect. That is, if they are zero, they
4991 * will not convey any information.
4992 * NOW there is a trailer field, after the ack where it will safely be
4993 * ignored by mundanes, which indicates the maximum size packet this
4994 * host can swallow. */
4996 struct rx_packet *optionalPacket; use to send ack (or null)
4997 int seq; Sequence number of the packet we are acking
4998 int serial; Serial number of the packet
4999 int pflags; Flags field from packet header
5000 int reason; Reason an acknowledge was prompted
5004 rxi_SendAck(struct rx_call *call,
5005 struct rx_packet *optionalPacket, int serial, int reason,
5008 struct rx_ackPacket *ap;
5009 struct rx_packet *rqp;
5010 struct rx_packet *nxp; /* For queue_Scan */
5011 struct rx_packet *p;
5014 afs_uint32 padbytes = 0;
5015 #ifdef RX_ENABLE_TSFPQ
5016 struct rx_ts_info_t * rx_ts_info;
5020 * Open the receive window once a thread starts reading packets
5022 if (call->rnext > 1) {
5023 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5026 /* Don't attempt to grow MTU if this is a critical ping */
5027 if (reason == RX_ACK_MTU) {
5028 /* keep track of per-call attempts, if we're over max, do in small
5029 * otherwise in larger? set a size to increment by, decrease
5032 if (call->conn->peer->maxPacketSize &&
5033 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5035 padbytes = call->conn->peer->maxPacketSize+16;
5037 padbytes = call->conn->peer->maxMTU + 128;
5039 /* do always try a minimum size ping */
5040 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5042 /* subtract the ack payload */
5043 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5044 reason = RX_ACK_PING;
5047 call->nHardAcks = 0;
5048 call->nSoftAcks = 0;
5049 if (call->rnext > call->lastAcked)
5050 call->lastAcked = call->rnext;
5054 rx_computelen(p, p->length); /* reset length, you never know */
5055 } /* where that's been... */
5056 #ifdef RX_ENABLE_TSFPQ
5058 RX_TS_INFO_GET(rx_ts_info);
5059 if ((p = rx_ts_info->local_special_packet)) {
5060 rx_computelen(p, p->length);
5061 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5062 rx_ts_info->local_special_packet = p;
5063 } else { /* We won't send the ack, but don't panic. */
5064 return optionalPacket;
5068 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5069 /* We won't send the ack, but don't panic. */
5070 return optionalPacket;
5075 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5078 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5079 #ifndef RX_ENABLE_TSFPQ
5080 if (!optionalPacket)
5083 return optionalPacket;
5085 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5086 if (rx_Contiguous(p) < templ) {
5087 #ifndef RX_ENABLE_TSFPQ
5088 if (!optionalPacket)
5091 return optionalPacket;
5096 /* MTUXXX failing to send an ack is very serious. We should */
5097 /* try as hard as possible to send even a partial ack; it's */
5098 /* better than nothing. */
5099 ap = (struct rx_ackPacket *)rx_DataOf(p);
5100 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5101 ap->reason = reason;
5103 /* The skew computation used to be bogus, I think it's better now. */
5104 /* We should start paying attention to skew. XXX */
5105 ap->serial = htonl(serial);
5106 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5108 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5109 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5111 /* No fear of running out of ack packet here because there can only be at most
5112 * one window full of unacknowledged packets. The window size must be constrained
5113 * to be less than the maximum ack size, of course. Also, an ack should always
5114 * fit into a single packet -- it should not ever be fragmented. */
5115 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5116 if (!rqp || !call->rq.next
5117 || (rqp->header.seq > (call->rnext + call->rwind))) {
5118 #ifndef RX_ENABLE_TSFPQ
5119 if (!optionalPacket)
5122 rxi_CallError(call, RX_CALL_DEAD);
5123 return optionalPacket;
5126 while (rqp->header.seq > call->rnext + offset)
5127 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5128 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5130 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5131 #ifndef RX_ENABLE_TSFPQ
5132 if (!optionalPacket)
5135 rxi_CallError(call, RX_CALL_DEAD);
5136 return optionalPacket;
5141 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5143 /* these are new for AFS 3.3 */
5144 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5145 templ = htonl(templ);
5146 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5147 templ = htonl(call->conn->peer->ifMTU);
5148 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5149 sizeof(afs_int32), &templ);
5151 /* new for AFS 3.4 */
5152 templ = htonl(call->rwind);
5153 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5154 sizeof(afs_int32), &templ);
5156 /* new for AFS 3.5 */
5157 templ = htonl(call->conn->peer->ifDgramPackets);
5158 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5159 sizeof(afs_int32), &templ);
5161 p->header.serviceId = call->conn->serviceId;
5162 p->header.cid = (call->conn->cid | call->channel);
5163 p->header.callNumber = *call->callNumber;
5165 p->header.securityIndex = call->conn->securityIndex;
5166 p->header.epoch = call->conn->epoch;
5167 p->header.type = RX_PACKET_TYPE_ACK;
5168 p->header.flags = RX_SLOW_START_OK;
5169 if (reason == RX_ACK_PING) {
5170 p->header.flags |= RX_REQUEST_ACK;
5172 clock_GetTime(&call->pingRequestTime);
5175 p->length = padbytes +
5176 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5179 /* not fast but we can potentially use this if truncated
5180 * fragments are delivered to figure out the mtu.
5182 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5183 sizeof(afs_int32), sizeof(afs_int32),
5187 if (call->conn->type == RX_CLIENT_CONNECTION)
5188 p->header.flags |= RX_CLIENT_INITIATED;
5192 if (rxdebug_active) {
5196 len = _snprintf(msg, sizeof(msg),
5197 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5198 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5199 ntohl(ap->serial), ntohl(ap->previousPacket),
5200 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5201 ap->nAcks, ntohs(ap->bufferSpace) );
5205 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5206 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5210 OutputDebugString(msg);
5212 #else /* AFS_NT40_ENV */
5214 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5215 ap->reason, ntohl(ap->previousPacket),
5216 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5218 for (offset = 0; offset < ap->nAcks; offset++)
5219 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5224 #endif /* AFS_NT40_ENV */
5227 int i, nbytes = p->length;
5229 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5230 if (nbytes <= p->wirevec[i].iov_len) {
5233 savelen = p->wirevec[i].iov_len;
5235 p->wirevec[i].iov_len = nbytes;
5237 rxi_Send(call, p, istack);
5238 p->wirevec[i].iov_len = savelen;
5242 nbytes -= p->wirevec[i].iov_len;
5245 if (rx_stats_active)
5246 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5247 #ifndef RX_ENABLE_TSFPQ
5248 if (!optionalPacket)
5251 return optionalPacket; /* Return packet for re-use by caller */
5254 /* Send all of the packets in the list in single datagram */
5256 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5257 int istack, int moreFlag, struct clock *now,
5258 struct clock *retryTime, int resending)
5263 struct rx_connection *conn = call->conn;
5264 struct rx_peer *peer = conn->peer;
5266 MUTEX_ENTER(&peer->peer_lock);
5269 peer->reSends += len;
5270 if (rx_stats_active)
5271 rx_MutexAdd(rx_stats.dataPacketsSent, len, rx_stats_mutex);
5272 MUTEX_EXIT(&peer->peer_lock);
5274 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5278 /* Set the packet flags and schedule the resend events */
5279 /* Only request an ack for the last packet in the list */
5280 for (i = 0; i < len; i++) {
5281 list[i]->retryTime = *retryTime;
5282 if (list[i]->header.serial) {
5283 /* Exponentially backoff retry times */
5284 if (list[i]->backoff < MAXBACKOFF) {
5285 /* so it can't stay == 0 */
5286 list[i]->backoff = (list[i]->backoff << 1) + 1;
5289 clock_Addmsec(&(list[i]->retryTime),
5290 ((afs_uint32) list[i]->backoff) << 8);
5293 /* Wait a little extra for the ack on the last packet */
5294 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5295 clock_Addmsec(&(list[i]->retryTime), 400);
5298 /* Record the time sent */
5299 list[i]->timeSent = *now;
5301 /* Ask for an ack on retransmitted packets, on every other packet
5302 * if the peer doesn't support slow start. Ask for an ack on every
5303 * packet until the congestion window reaches the ack rate. */
5304 if (list[i]->header.serial) {
5306 if (rx_stats_active)
5307 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5309 /* improved RTO calculation- not Karn */
5310 list[i]->firstSent = *now;
5311 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5312 || (!(call->flags & RX_CALL_SLOW_START_OK)
5313 && (list[i]->header.seq & 1)))) {
5318 /* Tag this packet as not being the last in this group,
5319 * for the receiver's benefit */
5320 if (i < len - 1 || moreFlag) {
5321 list[i]->header.flags |= RX_MORE_PACKETS;
5324 /* Install the new retransmit time for the packet, and
5325 * record the time sent */
5326 list[i]->timeSent = *now;
5330 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5333 /* Since we're about to send a data packet to the peer, it's
5334 * safe to nuke any scheduled end-of-packets ack */
5335 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5337 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5338 MUTEX_EXIT(&call->lock);
5340 rxi_SendPacketList(call, conn, list, len, istack);
5342 rxi_SendPacket(call, conn, list[0], istack);
5344 MUTEX_ENTER(&call->lock);
5345 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5347 /* Update last send time for this call (for keep-alive
5348 * processing), and for the connection (so that we can discover
5349 * idle connections) */
5350 conn->lastSendTime = call->lastSendTime = clock_Sec();
5351 /* Let a set of retransmits trigger an idle timeout */
5353 call->lastSendData = call->lastSendTime;
5356 /* When sending packets we need to follow these rules:
5357 * 1. Never send more than maxDgramPackets in a jumbogram.
5358 * 2. Never send a packet with more than two iovecs in a jumbogram.
5359 * 3. Never send a retransmitted packet in a jumbogram.
5360 * 4. Never send more than cwind/4 packets in a jumbogram
5361 * We always keep the last list we should have sent so we
5362 * can set the RX_MORE_PACKETS flags correctly.
5365 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5366 int istack, struct clock *now, struct clock *retryTime,
5369 int i, cnt, lastCnt = 0;
5370 struct rx_packet **listP, **lastP = 0;
5371 struct rx_peer *peer = call->conn->peer;
5372 int morePackets = 0;
5374 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5375 /* Does the current packet force us to flush the current list? */
5377 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5378 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5380 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5382 /* If the call enters an error state stop sending, or if
5383 * we entered congestion recovery mode, stop sending */
5384 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5392 /* Add the current packet to the list if it hasn't been acked.
5393 * Otherwise adjust the list pointer to skip the current packet. */
5394 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5396 /* Do we need to flush the list? */
5397 if (cnt >= (int)peer->maxDgramPackets
5398 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5399 || list[i]->header.serial
5400 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5402 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5403 retryTime, resending);
5404 /* If the call enters an error state stop sending, or if
5405 * we entered congestion recovery mode, stop sending */
5407 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5412 listP = &list[i + 1];
5417 osi_Panic("rxi_SendList error");
5419 listP = &list[i + 1];
5423 /* Send the whole list when the call is in receive mode, when
5424 * the call is in eof mode, when we are in fast recovery mode,
5425 * and when we have the last packet */
5426 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5427 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5428 || (call->flags & RX_CALL_FAST_RECOVER)) {
5429 /* Check for the case where the current list contains
5430 * an acked packet. Since we always send retransmissions
5431 * in a separate packet, we only need to check the first
5432 * packet in the list */
5433 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5437 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5438 retryTime, resending);
5439 /* If the call enters an error state stop sending, or if
5440 * we entered congestion recovery mode, stop sending */
5441 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5445 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5448 } else if (lastCnt > 0) {
5449 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5454 #ifdef RX_ENABLE_LOCKS
5455 /* Call rxi_Start, below, but with the call lock held. */
5457 rxi_StartUnlocked(struct rxevent *event,
5458 void *arg0, void *arg1, int istack)
5460 struct rx_call *call = arg0;
5462 MUTEX_ENTER(&call->lock);
5463 rxi_Start(event, call, arg1, istack);
5464 MUTEX_EXIT(&call->lock);
5466 #endif /* RX_ENABLE_LOCKS */
5468 /* This routine is called when new packets are readied for
5469 * transmission and when retransmission may be necessary, or when the
5470 * transmission window or burst count are favourable. This should be
5471 * better optimized for new packets, the usual case, now that we've
5472 * got rid of queues of send packets. XXXXXXXXXXX */
5474 rxi_Start(struct rxevent *event,
5475 void *arg0, void *arg1, int istack)
5477 struct rx_call *call = arg0;
5479 struct rx_packet *p;
5480 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5481 struct rx_peer *peer = call->conn->peer;
5482 struct clock now, usenow, retryTime;
5486 struct rx_packet **xmitList;
5489 /* If rxi_Start is being called as a result of a resend event,
5490 * then make sure that the event pointer is removed from the call
5491 * structure, since there is no longer a per-call retransmission
5493 if (event && event == call->resendEvent) {
5494 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5495 call->resendEvent = NULL;
5497 if (queue_IsEmpty(&call->tq)) {
5501 /* Timeouts trigger congestion recovery */
5502 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5503 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5504 /* someone else is waiting to start recovery */
5507 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5508 rxi_WaitforTQBusy(call);
5509 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5510 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5511 call->flags |= RX_CALL_FAST_RECOVER;
5512 if (peer->maxDgramPackets > 1) {
5513 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5515 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5517 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5518 call->nDgramPackets = 1;
5520 call->nextCwind = 1;
5523 MUTEX_ENTER(&peer->peer_lock);
5524 peer->MTU = call->MTU;
5525 peer->cwind = call->cwind;
5526 peer->nDgramPackets = 1;
5528 call->congestSeq = peer->congestSeq;
5529 MUTEX_EXIT(&peer->peer_lock);
5530 /* Clear retry times on packets. Otherwise, it's possible for
5531 * some packets in the queue to force resends at rates faster
5532 * than recovery rates.
5534 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5535 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5536 clock_Zero(&p->retryTime);
5541 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5542 if (rx_stats_active)
5543 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5548 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5549 /* Get clock to compute the re-transmit time for any packets
5550 * in this burst. Note, if we back off, it's reasonable to
5551 * back off all of the packets in the same manner, even if
5552 * some of them have been retransmitted more times than more
5554 * Do a dance to avoid blocking after setting now. */
5555 MUTEX_ENTER(&peer->peer_lock);
5556 retryTime = peer->timeout;
5557 MUTEX_EXIT(&peer->peer_lock);
5558 clock_GetTime(&now);
5559 clock_Add(&retryTime, &now);
5561 /* Send (or resend) any packets that need it, subject to
5562 * window restrictions and congestion burst control
5563 * restrictions. Ask for an ack on the last packet sent in
5564 * this burst. For now, we're relying upon the window being
5565 * considerably bigger than the largest number of packets that
5566 * are typically sent at once by one initial call to
5567 * rxi_Start. This is probably bogus (perhaps we should ask
5568 * for an ack when we're half way through the current
5569 * window?). Also, for non file transfer applications, this
5570 * may end up asking for an ack for every packet. Bogus. XXXX
5573 * But check whether we're here recursively, and let the other guy
5576 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5577 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5578 call->flags |= RX_CALL_TQ_BUSY;
5580 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5582 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5583 call->flags &= ~RX_CALL_NEED_START;
5584 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5586 maxXmitPackets = MIN(call->twind, call->cwind);
5587 xmitList = (struct rx_packet **)
5588 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5589 /* XXXX else we must drop any mtx we hold */
5590 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5592 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5594 if (xmitList == NULL)
5595 osi_Panic("rxi_Start, failed to allocate xmit list");
5596 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5597 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5598 /* We shouldn't be sending packets if a thread is waiting
5599 * to initiate congestion recovery */
5600 dpf(("call %d waiting to initiate fast recovery\n",
5601 *(call->callNumber)));
5605 && (call->flags & RX_CALL_FAST_RECOVER)) {
5606 /* Only send one packet during fast recovery */
5607 dpf(("call %d restricted to one packet per send during fast recovery\n",
5608 *(call->callNumber)));
5611 if ((p->flags & RX_PKTFLAG_FREE)
5612 || (!queue_IsEnd(&call->tq, nxp)
5613 && (nxp->flags & RX_PKTFLAG_FREE))
5614 || (p == (struct rx_packet *)&rx_freePacketQueue)
5615 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5616 osi_Panic("rxi_Start: xmit queue clobbered");
5618 if (p->flags & RX_PKTFLAG_ACKED) {
5619 /* Since we may block, don't trust this */
5620 usenow.sec = usenow.usec = 0;
5621 if (rx_stats_active)
5622 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5623 continue; /* Ignore this packet if it has been acknowledged */
5626 /* Turn off all flags except these ones, which are the same
5627 * on each transmission */
5628 p->header.flags &= RX_PRESET_FLAGS;
5630 if (p->header.seq >=
5631 call->tfirst + MIN((int)call->twind,
5632 (int)(call->nSoftAcked +
5634 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5635 /* Note: if we're waiting for more window space, we can
5636 * still send retransmits; hence we don't return here, but
5637 * break out to schedule a retransmit event */
5638 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5639 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5644 /* Transmit the packet if it needs to be sent. */
5645 if (!clock_Lt(&now, &p->retryTime)) {
5646 if (nXmitPackets == maxXmitPackets) {
5647 rxi_SendXmitList(call, xmitList, nXmitPackets,
5648 istack, &now, &retryTime,
5650 osi_Free(xmitList, maxXmitPackets *
5651 sizeof(struct rx_packet *));
5654 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u nextRetry %u.%06u\n",
5655 *(call->callNumber), p,
5657 p->retryTime.sec, p->retryTime.usec,
5658 retryTime.sec, retryTime.usec));
5659 xmitList[nXmitPackets++] = p;
5663 /* xmitList now hold pointers to all of the packets that are
5664 * ready to send. Now we loop to send the packets */
5665 if (nXmitPackets > 0) {
5666 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5667 &now, &retryTime, resending);
5670 maxXmitPackets * sizeof(struct rx_packet *));
5672 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5674 * TQ references no longer protected by this flag; they must remain
5675 * protected by the global lock.
5677 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5678 call->flags &= ~RX_CALL_TQ_BUSY;
5679 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5680 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5681 call, call->tqWaiters, call->flags));
5682 #ifdef RX_ENABLE_LOCKS
5683 osirx_AssertMine(&call->lock, "rxi_Start start");
5684 CV_BROADCAST(&call->cv_tq);
5685 #else /* RX_ENABLE_LOCKS */
5686 osi_rxWakeup(&call->tq);
5687 #endif /* RX_ENABLE_LOCKS */
5692 /* We went into the error state while sending packets. Now is
5693 * the time to reset the call. This will also inform the using
5694 * process that the call is in an error state.
5696 if (rx_stats_active)
5697 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5698 call->flags &= ~RX_CALL_TQ_BUSY;
5699 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5700 dpf(("call error %d while xmit %p has %d waiters and flags %d\n",
5701 call->error, call, call->tqWaiters, call->flags));
5702 #ifdef RX_ENABLE_LOCKS
5703 osirx_AssertMine(&call->lock, "rxi_Start middle");
5704 CV_BROADCAST(&call->cv_tq);
5705 #else /* RX_ENABLE_LOCKS */
5706 osi_rxWakeup(&call->tq);
5707 #endif /* RX_ENABLE_LOCKS */
5709 rxi_CallError(call, call->error);
5712 #ifdef RX_ENABLE_LOCKS
5713 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5715 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5716 /* Some packets have received acks. If they all have, we can clear
5717 * the transmit queue.
5720 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5721 if (p->header.seq < call->tfirst
5722 && (p->flags & RX_PKTFLAG_ACKED)) {
5724 p->flags &= ~RX_PKTFLAG_TQ;
5725 #ifdef RXDEBUG_PACKET
5733 call->flags |= RX_CALL_TQ_CLEARME;
5735 #endif /* RX_ENABLE_LOCKS */
5736 /* Don't bother doing retransmits if the TQ is cleared. */
5737 if (call->flags & RX_CALL_TQ_CLEARME) {
5738 rxi_ClearTransmitQueue(call, 1);
5740 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5743 /* Always post a resend event, if there is anything in the
5744 * queue, and resend is possible. There should be at least
5745 * one unacknowledged packet in the queue ... otherwise none
5746 * of these packets should be on the queue in the first place.
5748 if (call->resendEvent) {
5749 /* Cancel the existing event and post a new one */
5750 rxevent_Cancel(call->resendEvent, call,
5751 RX_CALL_REFCOUNT_RESEND);
5754 /* The retry time is the retry time on the first unacknowledged
5755 * packet inside the current window */
5757 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5758 /* Don't set timers for packets outside the window */
5759 if (p->header.seq >= call->tfirst + call->twind) {
5763 if (!(p->flags & RX_PKTFLAG_ACKED)
5764 && !clock_IsZero(&p->retryTime)) {
5766 retryTime = p->retryTime;
5771 /* Post a new event to re-run rxi_Start when retries may be needed */
5772 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5773 #ifdef RX_ENABLE_LOCKS
5774 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5776 rxevent_PostNow2(&retryTime, &usenow,
5778 (void *)call, 0, istack);
5779 #else /* RX_ENABLE_LOCKS */
5781 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5782 (void *)call, 0, istack);
5783 #endif /* RX_ENABLE_LOCKS */
5786 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5787 } while (call->flags & RX_CALL_NEED_START);
5789 * TQ references no longer protected by this flag; they must remain
5790 * protected by the global lock.
5792 call->flags &= ~RX_CALL_TQ_BUSY;
5793 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5794 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5795 call, call->tqWaiters, call->flags));
5796 #ifdef RX_ENABLE_LOCKS
5797 osirx_AssertMine(&call->lock, "rxi_Start end");
5798 CV_BROADCAST(&call->cv_tq);
5799 #else /* RX_ENABLE_LOCKS */
5800 osi_rxWakeup(&call->tq);
5801 #endif /* RX_ENABLE_LOCKS */
5804 call->flags |= RX_CALL_NEED_START;
5806 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5808 if (call->resendEvent) {
5809 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5814 /* Also adjusts the keep alive parameters for the call, to reflect
5815 * that we have just sent a packet (so keep alives aren't sent
5818 rxi_Send(struct rx_call *call, struct rx_packet *p,
5821 struct rx_connection *conn = call->conn;
5823 /* Stamp each packet with the user supplied status */
5824 p->header.userStatus = call->localStatus;
5826 /* Allow the security object controlling this call's security to
5827 * make any last-minute changes to the packet */
5828 RXS_SendPacket(conn->securityObject, call, p);
5830 /* Since we're about to send SOME sort of packet to the peer, it's
5831 * safe to nuke any scheduled end-of-packets ack */
5832 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5834 /* Actually send the packet, filling in more connection-specific fields */
5835 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5836 MUTEX_EXIT(&call->lock);
5837 rxi_SendPacket(call, conn, p, istack);
5838 MUTEX_ENTER(&call->lock);
5839 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5841 /* Update last send time for this call (for keep-alive
5842 * processing), and for the connection (so that we can discover
5843 * idle connections) */
5844 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5845 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
5846 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
5848 conn->lastSendTime = call->lastSendTime = clock_Sec();
5849 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
5850 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5851 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
5852 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
5853 RX_ACK_PING_RESPONSE)))
5854 call->lastSendData = call->lastSendTime;
5858 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5859 * that things are fine. Also called periodically to guarantee that nothing
5860 * falls through the cracks (e.g. (error + dally) connections have keepalive
5861 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5863 * haveCTLock Set if calling from rxi_ReapConnections
5865 #ifdef RX_ENABLE_LOCKS
5867 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5868 #else /* RX_ENABLE_LOCKS */
5870 rxi_CheckCall(struct rx_call *call)
5871 #endif /* RX_ENABLE_LOCKS */
5873 struct rx_connection *conn = call->conn;
5875 afs_uint32 deadTime;
5879 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5880 if (call->flags & RX_CALL_TQ_BUSY) {
5881 /* Call is active and will be reset by rxi_Start if it's
5882 * in an error state.
5887 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5889 (((afs_uint32) conn->secondsUntilDead << 10) +
5890 ((afs_uint32) conn->peer->rtt >> 3) +
5891 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5893 /* These are computed to the second (+- 1 second). But that's
5894 * good enough for these values, which should be a significant
5895 * number of seconds. */
5896 if (now > (call->lastReceiveTime + deadTime)) {
5897 if (call->state == RX_STATE_ACTIVE) {
5899 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5901 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5902 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5903 ip_stack_t *ipst = ns->netstack_ip;
5905 ire = ire_cache_lookup(conn->peer->host
5906 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5908 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5910 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5917 if (ire && ire->ire_max_frag > 0)
5918 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
5920 #if defined(GLOBAL_NETSTACKID)
5924 #endif /* ADAPT_PMTU */
5925 cerror = RX_CALL_DEAD;
5928 #ifdef RX_ENABLE_LOCKS
5929 /* Cancel pending events */
5930 rxevent_Cancel(call->delayedAckEvent, call,
5931 RX_CALL_REFCOUNT_DELAY);
5932 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5933 rxevent_Cancel(call->keepAliveEvent, call,
5934 RX_CALL_REFCOUNT_ALIVE);
5935 if (call->refCount == 0) {
5936 rxi_FreeCall(call, haveCTLock);
5940 #else /* RX_ENABLE_LOCKS */
5943 #endif /* RX_ENABLE_LOCKS */
5945 /* Non-active calls are destroyed if they are not responding
5946 * to pings; active calls are simply flagged in error, so the
5947 * attached process can die reasonably gracefully. */
5949 /* see if we have a non-activity timeout */
5950 if (call->startWait && conn->idleDeadTime
5951 && ((call->startWait + conn->idleDeadTime) < now) &&
5952 (call->flags & RX_CALL_READER_WAIT)) {
5953 if (call->state == RX_STATE_ACTIVE) {
5954 cerror = RX_CALL_TIMEOUT;
5958 if (call->lastSendData && conn->idleDeadTime && (conn->idleDeadErr != 0)
5959 && ((call->lastSendData + conn->idleDeadTime) < now)) {
5960 if (call->state == RX_STATE_ACTIVE) {
5961 cerror = conn->idleDeadErr;
5965 /* see if we have a hard timeout */
5966 if (conn->hardDeadTime
5967 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5968 if (call->state == RX_STATE_ACTIVE)
5969 rxi_CallError(call, RX_CALL_TIMEOUT);
5974 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT) {
5975 int oldMTU = conn->peer->ifMTU;
5977 /* if we thought we could send more, perhaps things got worse */
5978 if (call->conn->peer->maxPacketSize > conn->lastPacketSize)
5979 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
5980 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
5981 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
5983 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
5985 /* minimum capped in SetPeerMtu */
5986 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
5989 conn->lastPacketSize = 0;
5991 /* needed so ResetCall doesn't clobber us. */
5992 call->MTU = conn->peer->ifMTU;
5994 /* if we never succeeded, let the error pass out as-is */
5995 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
5996 cerror = conn->msgsizeRetryErr;
5999 rxi_CallError(call, cerror);
6004 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6006 struct rx_connection *conn = arg1;
6007 struct rx_header theader;
6009 struct sockaddr_in taddr;
6012 struct iovec tmpiov[2];
6015 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6018 tp = &tbuffer[sizeof(struct rx_header)];
6019 taddr.sin_family = AF_INET;
6020 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6021 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6022 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6023 taddr.sin_len = sizeof(struct sockaddr_in);
6025 memset(&theader, 0, sizeof(theader));
6026 theader.epoch = htonl(999);
6028 theader.callNumber = 0;
6031 theader.type = RX_PACKET_TYPE_VERSION;
6032 theader.flags = RX_LAST_PACKET;
6033 theader.serviceId = 0;
6035 memcpy(tbuffer, &theader, sizeof(theader));
6036 memcpy(tp, &a, sizeof(a));
6037 tmpiov[0].iov_base = tbuffer;
6038 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6040 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6042 MUTEX_ENTER(&conn->conn_data_lock);
6043 /* Only reschedule ourselves if the connection would not be destroyed */
6044 if (conn->refCount <= 1) {
6045 conn->natKeepAliveEvent = NULL;
6046 MUTEX_EXIT(&conn->conn_data_lock);
6047 rx_DestroyConnection(conn); /* drop the reference for this */
6049 conn->natKeepAliveEvent = NULL;
6050 conn->refCount--; /* drop the reference for this */
6051 rxi_ScheduleNatKeepAliveEvent(conn);
6052 MUTEX_EXIT(&conn->conn_data_lock);
6057 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6059 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6060 struct clock when, now;
6061 clock_GetTime(&now);
6063 when.sec += conn->secondsUntilNatPing;
6064 conn->refCount++; /* hold a reference for this */
6065 conn->natKeepAliveEvent =
6066 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6071 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6073 MUTEX_ENTER(&conn->conn_data_lock);
6074 conn->secondsUntilNatPing = seconds;
6076 rxi_ScheduleNatKeepAliveEvent(conn);
6077 MUTEX_EXIT(&conn->conn_data_lock);
6081 rxi_NatKeepAliveOn(struct rx_connection *conn)
6083 MUTEX_ENTER(&conn->conn_data_lock);
6084 rxi_ScheduleNatKeepAliveEvent(conn);
6085 MUTEX_EXIT(&conn->conn_data_lock);
6088 /* When a call is in progress, this routine is called occasionally to
6089 * make sure that some traffic has arrived (or been sent to) the peer.
6090 * If nothing has arrived in a reasonable amount of time, the call is
6091 * declared dead; if nothing has been sent for a while, we send a
6092 * keep-alive packet (if we're actually trying to keep the call alive)
6095 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6097 struct rx_call *call = arg1;
6098 struct rx_connection *conn;
6101 MUTEX_ENTER(&call->lock);
6102 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6103 if (event == call->keepAliveEvent)
6104 call->keepAliveEvent = NULL;
6107 #ifdef RX_ENABLE_LOCKS
6108 if (rxi_CheckCall(call, 0)) {
6109 MUTEX_EXIT(&call->lock);
6112 #else /* RX_ENABLE_LOCKS */
6113 if (rxi_CheckCall(call))
6115 #endif /* RX_ENABLE_LOCKS */
6117 /* Don't try to keep alive dallying calls */
6118 if (call->state == RX_STATE_DALLY) {
6119 MUTEX_EXIT(&call->lock);
6124 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6125 /* Don't try to send keepalives if there is unacknowledged data */
6126 /* the rexmit code should be good enough, this little hack
6127 * doesn't quite work XXX */
6128 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6130 rxi_ScheduleKeepAliveEvent(call);
6131 MUTEX_EXIT(&call->lock);
6134 /* Does what's on the nameplate. */
6136 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6138 struct rx_call *call = arg1;
6139 struct rx_connection *conn;
6141 MUTEX_ENTER(&call->lock);
6142 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6143 if (event == call->growMTUEvent)
6144 call->growMTUEvent = NULL;
6146 #ifdef RX_ENABLE_LOCKS
6147 if (rxi_CheckCall(call, 0)) {
6148 MUTEX_EXIT(&call->lock);
6151 #else /* RX_ENABLE_LOCKS */
6152 if (rxi_CheckCall(call))
6154 #endif /* RX_ENABLE_LOCKS */
6156 /* Don't bother with dallying calls */
6157 if (call->state == RX_STATE_DALLY) {
6158 MUTEX_EXIT(&call->lock);
6165 * keep being scheduled, just don't do anything if we're at peak,
6166 * or we're not set up to be properly handled (idle timeout required)
6168 if ((conn->peer->maxPacketSize != 0) &&
6169 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6170 (conn->idleDeadErr))
6171 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6172 rxi_ScheduleGrowMTUEvent(call, 0);
6173 MUTEX_EXIT(&call->lock);
6177 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6179 if (!call->keepAliveEvent) {
6180 struct clock when, now;
6181 clock_GetTime(&now);
6183 when.sec += call->conn->secondsUntilPing;
6184 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6185 call->keepAliveEvent =
6186 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6191 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6193 if (!call->growMTUEvent) {
6194 struct clock when, now;
6196 clock_GetTime(&now);
6199 if (call->conn->secondsUntilPing)
6200 secs = (6*call->conn->secondsUntilPing)-1;
6202 if (call->conn->secondsUntilDead)
6203 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6207 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6208 call->growMTUEvent =
6209 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6213 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6215 rxi_KeepAliveOn(struct rx_call *call)
6217 /* Pretend last packet received was received now--i.e. if another
6218 * packet isn't received within the keep alive time, then the call
6219 * will die; Initialize last send time to the current time--even
6220 * if a packet hasn't been sent yet. This will guarantee that a
6221 * keep-alive is sent within the ping time */
6222 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6223 rxi_ScheduleKeepAliveEvent(call);
6227 rxi_GrowMTUOn(struct rx_call *call)
6229 struct rx_connection *conn = call->conn;
6230 MUTEX_ENTER(&conn->conn_data_lock);
6231 conn->lastPingSizeSer = conn->lastPingSize = 0;
6232 MUTEX_EXIT(&conn->conn_data_lock);
6233 rxi_ScheduleGrowMTUEvent(call, 1);
6236 /* This routine is called to send connection abort messages
6237 * that have been delayed to throttle looping clients. */
6239 rxi_SendDelayedConnAbort(struct rxevent *event,
6240 void *arg1, void *unused)
6242 struct rx_connection *conn = arg1;
6245 struct rx_packet *packet;
6247 MUTEX_ENTER(&conn->conn_data_lock);
6248 conn->delayedAbortEvent = NULL;
6249 error = htonl(conn->error);
6251 MUTEX_EXIT(&conn->conn_data_lock);
6252 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6255 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6256 RX_PACKET_TYPE_ABORT, (char *)&error,
6258 rxi_FreePacket(packet);
6262 /* This routine is called to send call abort messages
6263 * that have been delayed to throttle looping clients. */
6265 rxi_SendDelayedCallAbort(struct rxevent *event,
6266 void *arg1, void *dummy)
6268 struct rx_call *call = arg1;
6271 struct rx_packet *packet;
6273 MUTEX_ENTER(&call->lock);
6274 call->delayedAbortEvent = NULL;
6275 error = htonl(call->error);
6277 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6280 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6281 (char *)&error, sizeof(error), 0);
6282 rxi_FreePacket(packet);
6284 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6285 MUTEX_EXIT(&call->lock);
6288 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6289 * seconds) to ask the client to authenticate itself. The routine
6290 * issues a challenge to the client, which is obtained from the
6291 * security object associated with the connection */
6293 rxi_ChallengeEvent(struct rxevent *event,
6294 void *arg0, void *arg1, int tries)
6296 struct rx_connection *conn = arg0;
6298 conn->challengeEvent = NULL;
6299 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6300 struct rx_packet *packet;
6301 struct clock when, now;
6304 /* We've failed to authenticate for too long.
6305 * Reset any calls waiting for authentication;
6306 * they are all in RX_STATE_PRECALL.
6310 MUTEX_ENTER(&conn->conn_call_lock);
6311 for (i = 0; i < RX_MAXCALLS; i++) {
6312 struct rx_call *call = conn->call[i];
6314 MUTEX_ENTER(&call->lock);
6315 if (call->state == RX_STATE_PRECALL) {
6316 rxi_CallError(call, RX_CALL_DEAD);
6317 rxi_SendCallAbort(call, NULL, 0, 0);
6319 MUTEX_EXIT(&call->lock);
6322 MUTEX_EXIT(&conn->conn_call_lock);
6326 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6328 /* If there's no packet available, do this later. */
6329 RXS_GetChallenge(conn->securityObject, conn, packet);
6330 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6331 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6332 rxi_FreePacket(packet);
6334 clock_GetTime(&now);
6336 when.sec += RX_CHALLENGE_TIMEOUT;
6337 conn->challengeEvent =
6338 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6343 /* Call this routine to start requesting the client to authenticate
6344 * itself. This will continue until authentication is established,
6345 * the call times out, or an invalid response is returned. The
6346 * security object associated with the connection is asked to create
6347 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6348 * defined earlier. */
6350 rxi_ChallengeOn(struct rx_connection *conn)
6352 if (!conn->challengeEvent) {
6353 RXS_CreateChallenge(conn->securityObject, conn);
6354 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6359 /* Compute round trip time of the packet provided, in *rttp.
6362 /* rxi_ComputeRoundTripTime is called with peer locked. */
6363 /* sentp and/or peer may be null */
6365 rxi_ComputeRoundTripTime(struct rx_packet *p,
6366 struct clock *sentp,
6367 struct rx_peer *peer)
6369 struct clock thisRtt, *rttp = &thisRtt;
6373 clock_GetTime(rttp);
6375 if (clock_Lt(rttp, sentp)) {
6377 return; /* somebody set the clock back, don't count this time. */
6379 clock_Sub(rttp, sentp);
6380 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6381 p->header.callNumber, p, rttp->sec, rttp->usec));
6383 if (rttp->sec == 0 && rttp->usec == 0) {
6385 * The actual round trip time is shorter than the
6386 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6387 * Since we can't tell which at the moment we will assume 1ms.
6392 if (rx_stats_active) {
6393 MUTEX_ENTER(&rx_stats_mutex);
6394 if (clock_Lt(rttp, &rx_stats.minRtt))
6395 rx_stats.minRtt = *rttp;
6396 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
6397 if (rttp->sec > 60) {
6398 MUTEX_EXIT(&rx_stats_mutex);
6399 return; /* somebody set the clock ahead */
6401 rx_stats.maxRtt = *rttp;
6403 clock_Add(&rx_stats.totalRtt, rttp);
6404 rx_stats.nRttSamples++;
6405 MUTEX_EXIT(&rx_stats_mutex);
6408 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6410 /* Apply VanJacobson round-trip estimations */
6415 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6416 * srtt is stored as fixed point with 3 bits after the binary
6417 * point (i.e., scaled by 8). The following magic is
6418 * equivalent to the smoothing algorithm in rfc793 with an
6419 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6420 * srtt'*8 = rtt + srtt*7
6421 * srtt'*8 = srtt*8 + rtt - srtt
6422 * srtt' = srtt + rtt/8 - srtt/8
6423 * srtt' = srtt + (rtt - srtt)/8
6426 delta = _8THMSEC(rttp) - peer->rtt;
6427 peer->rtt += (delta >> 3);
6430 * We accumulate a smoothed rtt variance (actually, a smoothed
6431 * mean difference), then set the retransmit timer to smoothed
6432 * rtt + 4 times the smoothed variance (was 2x in van's original
6433 * paper, but 4x works better for me, and apparently for him as
6435 * rttvar is stored as
6436 * fixed point with 2 bits after the binary point (scaled by
6437 * 4). The following is equivalent to rfc793 smoothing with
6438 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6439 * rttvar'*4 = rttvar*3 + |delta|
6440 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6441 * rttvar' = rttvar + |delta|/4 - rttvar/4
6442 * rttvar' = rttvar + (|delta| - rttvar)/4
6443 * This replaces rfc793's wired-in beta.
6444 * dev*4 = dev*4 + (|actual - expected| - dev)
6450 delta -= (peer->rtt_dev << 1);
6451 peer->rtt_dev += (delta >> 3);
6453 /* I don't have a stored RTT so I start with this value. Since I'm
6454 * probably just starting a call, and will be pushing more data down
6455 * this, I expect congestion to increase rapidly. So I fudge a
6456 * little, and I set deviance to half the rtt. In practice,
6457 * deviance tends to approach something a little less than
6458 * half the smoothed rtt. */
6459 peer->rtt = _8THMSEC(rttp) + 8;
6460 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6462 /* the timeout is RTT + 4*MDEV but no less than rx_minPeerTimeout msec.
6463 * This is because one end or the other of these connections is usually
6464 * in a user process, and can be switched and/or swapped out. So on fast,
6465 * reliable networks, the timeout would otherwise be too short. */
6466 rtt_timeout = MAX(((peer->rtt >> 3) + peer->rtt_dev), rx_minPeerTimeout);
6467 clock_Zero(&(peer->timeout));
6468 clock_Addmsec(&(peer->timeout), rtt_timeout);
6470 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6471 p->header.callNumber, p, MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6475 /* Find all server connections that have not been active for a long time, and
6478 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6480 struct clock now, when;
6481 clock_GetTime(&now);
6483 /* Find server connection structures that haven't been used for
6484 * greater than rx_idleConnectionTime */
6486 struct rx_connection **conn_ptr, **conn_end;
6487 int i, havecalls = 0;
6488 MUTEX_ENTER(&rx_connHashTable_lock);
6489 for (conn_ptr = &rx_connHashTable[0], conn_end =
6490 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6492 struct rx_connection *conn, *next;
6493 struct rx_call *call;
6497 for (conn = *conn_ptr; conn; conn = next) {
6498 /* XXX -- Shouldn't the connection be locked? */
6501 for (i = 0; i < RX_MAXCALLS; i++) {
6502 call = conn->call[i];
6506 code = MUTEX_TRYENTER(&call->lock);
6509 #ifdef RX_ENABLE_LOCKS
6510 result = rxi_CheckCall(call, 1);
6511 #else /* RX_ENABLE_LOCKS */
6512 result = rxi_CheckCall(call);
6513 #endif /* RX_ENABLE_LOCKS */
6514 MUTEX_EXIT(&call->lock);
6516 /* If CheckCall freed the call, it might
6517 * have destroyed the connection as well,
6518 * which screws up the linked lists.
6524 if (conn->type == RX_SERVER_CONNECTION) {
6525 /* This only actually destroys the connection if
6526 * there are no outstanding calls */
6527 MUTEX_ENTER(&conn->conn_data_lock);
6528 if (!havecalls && !conn->refCount
6529 && ((conn->lastSendTime + rx_idleConnectionTime) <
6531 conn->refCount++; /* it will be decr in rx_DestroyConn */
6532 MUTEX_EXIT(&conn->conn_data_lock);
6533 #ifdef RX_ENABLE_LOCKS
6534 rxi_DestroyConnectionNoLock(conn);
6535 #else /* RX_ENABLE_LOCKS */
6536 rxi_DestroyConnection(conn);
6537 #endif /* RX_ENABLE_LOCKS */
6539 #ifdef RX_ENABLE_LOCKS
6541 MUTEX_EXIT(&conn->conn_data_lock);
6543 #endif /* RX_ENABLE_LOCKS */
6547 #ifdef RX_ENABLE_LOCKS
6548 while (rx_connCleanup_list) {
6549 struct rx_connection *conn;
6550 conn = rx_connCleanup_list;
6551 rx_connCleanup_list = rx_connCleanup_list->next;
6552 MUTEX_EXIT(&rx_connHashTable_lock);
6553 rxi_CleanupConnection(conn);
6554 MUTEX_ENTER(&rx_connHashTable_lock);
6556 MUTEX_EXIT(&rx_connHashTable_lock);
6557 #endif /* RX_ENABLE_LOCKS */
6560 /* Find any peer structures that haven't been used (haven't had an
6561 * associated connection) for greater than rx_idlePeerTime */
6563 struct rx_peer **peer_ptr, **peer_end;
6567 * Why do we need to hold the rx_peerHashTable_lock across
6568 * the incrementing of peer_ptr since the rx_peerHashTable
6569 * array is not changing? We don't.
6571 * By dropping the lock periodically we can permit other
6572 * activities to be performed while a rxi_ReapConnections
6573 * call is in progress. The goal of reap connections
6574 * is to clean up quickly without causing large amounts
6575 * of contention. Therefore, it is important that global
6576 * mutexes not be held for extended periods of time.
6578 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6579 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6581 struct rx_peer *peer, *next, *prev;
6583 MUTEX_ENTER(&rx_peerHashTable_lock);
6584 for (prev = peer = *peer_ptr; peer; peer = next) {
6586 code = MUTEX_TRYENTER(&peer->peer_lock);
6587 if ((code) && (peer->refCount == 0)
6588 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6589 rx_interface_stat_p rpc_stat, nrpc_stat;
6593 * now know that this peer object is one to be
6594 * removed from the hash table. Once it is removed
6595 * it can't be referenced by other threads.
6596 * Lets remove it first and decrement the struct
6597 * nPeerStructs count.
6599 if (peer == *peer_ptr) {
6605 if (rx_stats_active)
6606 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6609 * Now if we hold references on 'prev' and 'next'
6610 * we can safely drop the rx_peerHashTable_lock
6611 * while we destroy this 'peer' object.
6617 MUTEX_EXIT(&rx_peerHashTable_lock);
6619 MUTEX_EXIT(&peer->peer_lock);
6620 MUTEX_DESTROY(&peer->peer_lock);
6622 (&peer->rpcStats, rpc_stat, nrpc_stat,
6623 rx_interface_stat)) {
6624 unsigned int num_funcs;
6627 queue_Remove(&rpc_stat->queue_header);
6628 queue_Remove(&rpc_stat->all_peers);
6629 num_funcs = rpc_stat->stats[0].func_total;
6631 sizeof(rx_interface_stat_t) +
6632 rpc_stat->stats[0].func_total *
6633 sizeof(rx_function_entry_v1_t);
6635 rxi_Free(rpc_stat, space);
6637 MUTEX_ENTER(&rx_rpc_stats);
6638 rxi_rpc_peer_stat_cnt -= num_funcs;
6639 MUTEX_EXIT(&rx_rpc_stats);
6644 * Regain the rx_peerHashTable_lock and
6645 * decrement the reference count on 'prev'
6648 MUTEX_ENTER(&rx_peerHashTable_lock);
6655 MUTEX_EXIT(&peer->peer_lock);
6660 MUTEX_EXIT(&rx_peerHashTable_lock);
6664 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6665 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6666 * GC, just below. Really, we shouldn't have to keep moving packets from
6667 * one place to another, but instead ought to always know if we can
6668 * afford to hold onto a packet in its particular use. */
6669 MUTEX_ENTER(&rx_freePktQ_lock);
6670 if (rx_waitingForPackets) {
6671 rx_waitingForPackets = 0;
6672 #ifdef RX_ENABLE_LOCKS
6673 CV_BROADCAST(&rx_waitingForPackets_cv);
6675 osi_rxWakeup(&rx_waitingForPackets);
6678 MUTEX_EXIT(&rx_freePktQ_lock);
6681 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6682 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6686 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6687 * rx.h is sort of strange this is better. This is called with a security
6688 * object before it is discarded. Each connection using a security object has
6689 * its own refcount to the object so it won't actually be freed until the last
6690 * connection is destroyed.
6692 * This is the only rxs module call. A hold could also be written but no one
6696 rxs_Release(struct rx_securityClass *aobj)
6698 return RXS_Close(aobj);
6702 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6703 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6704 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6705 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6707 /* Adjust our estimate of the transmission rate to this peer, given
6708 * that the packet p was just acked. We can adjust peer->timeout and
6709 * call->twind. Pragmatically, this is called
6710 * only with packets of maximal length.
6711 * Called with peer and call locked.
6715 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6716 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6718 afs_int32 xferSize, xferMs;
6722 /* Count down packets */
6723 if (peer->rateFlag > 0)
6725 /* Do nothing until we're enabled */
6726 if (peer->rateFlag != 0)
6731 /* Count only when the ack seems legitimate */
6732 switch (ackReason) {
6733 case RX_ACK_REQUESTED:
6735 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6739 case RX_ACK_PING_RESPONSE:
6740 if (p) /* want the response to ping-request, not data send */
6742 clock_GetTime(&newTO);
6743 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6744 clock_Sub(&newTO, &call->pingRequestTime);
6745 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6749 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6756 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)",
6757 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
6758 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6760 /* Track only packets that are big enough. */
6761 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6765 /* absorb RTT data (in milliseconds) for these big packets */
6766 if (peer->smRtt == 0) {
6767 peer->smRtt = xferMs;
6769 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6774 if (peer->countDown) {
6778 peer->countDown = 10; /* recalculate only every so often */
6780 /* In practice, we can measure only the RTT for full packets,
6781 * because of the way Rx acks the data that it receives. (If it's
6782 * smaller than a full packet, it often gets implicitly acked
6783 * either by the call response (from a server) or by the next call
6784 * (from a client), and either case confuses transmission times
6785 * with processing times.) Therefore, replace the above
6786 * more-sophisticated processing with a simpler version, where the
6787 * smoothed RTT is kept for full-size packets, and the time to
6788 * transmit a windowful of full-size packets is simply RTT *
6789 * windowSize. Again, we take two steps:
6790 - ensure the timeout is large enough for a single packet's RTT;
6791 - ensure that the window is small enough to fit in the desired timeout.*/
6793 /* First, the timeout check. */
6794 minTime = peer->smRtt;
6795 /* Get a reasonable estimate for a timeout period */
6797 newTO.sec = minTime / 1000;
6798 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6800 /* Increase the timeout period so that we can always do at least
6801 * one packet exchange */
6802 if (clock_Gt(&newTO, &peer->timeout)) {
6804 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u, ps %u)",
6805 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
6806 newTO.sec, newTO.usec, peer->smRtt, peer->packetSize));
6808 peer->timeout = newTO;
6811 /* Now, get an estimate for the transmit window size. */
6812 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6813 /* Now, convert to the number of full packets that could fit in a
6814 * reasonable fraction of that interval */
6815 minTime /= (peer->smRtt << 1);
6816 xferSize = minTime; /* (make a copy) */
6818 /* Now clamp the size to reasonable bounds. */
6821 else if (minTime > rx_Window)
6822 minTime = rx_Window;
6823 /* if (minTime != peer->maxWindow) {
6824 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6825 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6826 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6828 peer->maxWindow = minTime;
6829 elide... call->twind = minTime;
6833 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6834 * Discern this by calculating the timeout necessary for rx_Window
6836 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6837 /* calculate estimate for transmission interval in milliseconds */
6838 minTime = rx_Window * peer->smRtt;
6839 if (minTime < 1000) {
6840 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u, ps %u)",
6841 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6842 peer->timeout.usec, peer->smRtt, peer->packetSize));
6844 newTO.sec = 0; /* cut back on timeout by half a second */
6845 newTO.usec = 500000;
6846 clock_Sub(&peer->timeout, &newTO);
6851 } /* end of rxi_ComputeRate */
6852 #endif /* ADAPT_WINDOW */
6860 #define TRACE_OPTION_RX_DEBUG 16
6868 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6869 0, KEY_QUERY_VALUE, &parmKey);
6870 if (code != ERROR_SUCCESS)
6873 dummyLen = sizeof(TraceOption);
6874 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6875 (BYTE *) &TraceOption, &dummyLen);
6876 if (code == ERROR_SUCCESS) {
6877 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6879 RegCloseKey (parmKey);
6880 #endif /* AFS_NT40_ENV */
6885 rx_DebugOnOff(int on)
6889 rxdebug_active = on;
6895 rx_StatsOnOff(int on)
6898 rx_stats_active = on;
6903 /* Don't call this debugging routine directly; use dpf */
6905 rxi_DebugPrint(char *format, ...)
6914 va_start(ap, format);
6916 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6919 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6921 if (msg[len-1] != '\n') {
6925 OutputDebugString(msg);
6932 va_start(ap, format);
6934 clock_GetTime(&now);
6935 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
6936 (unsigned int)now.usec);
6937 vfprintf(rx_Log, format, ap);
6946 * This function is used to process the rx_stats structure that is local
6947 * to a process as well as an rx_stats structure received from a remote
6948 * process (via rxdebug). Therefore, it needs to do minimal version
6952 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6953 afs_int32 freePackets, char version)
6958 if (size != sizeof(struct rx_statistics)) {
6960 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
6961 size, sizeof(struct rx_statistics));
6964 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6967 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6968 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
6969 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6970 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6971 s->specialPktAllocFailures);
6973 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
6974 s->receivePktAllocFailures, s->sendPktAllocFailures,
6975 s->specialPktAllocFailures);
6979 " greedy %u, " "bogusReads %u (last from host %x), "
6980 "noPackets %u, " "noBuffers %u, " "selects %u, "
6981 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
6982 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6983 s->selects, s->sendSelects);
6985 fprintf(file, " packets read: ");
6986 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6987 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
6989 fprintf(file, "\n");
6992 " other read counters: data %u, " "ack %u, " "dup %u "
6993 "spurious %u " "dally %u\n", s->dataPacketsRead,
6994 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6995 s->ignorePacketDally);
6997 fprintf(file, " packets sent: ");
6998 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6999 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7001 fprintf(file, "\n");
7004 " other send counters: ack %u, " "data %u (not resends), "
7005 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7006 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7007 s->dataPacketsPushed, s->ignoreAckedPacket);
7010 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7011 s->netSendFailures, (int)s->fatalErrors);
7013 if (s->nRttSamples) {
7014 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7015 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7017 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7018 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7022 " %d server connections, " "%d client connections, "
7023 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7024 s->nServerConns, s->nClientConns, s->nPeerStructs,
7025 s->nCallStructs, s->nFreeCallStructs);
7027 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7028 fprintf(file, " %d clock updates\n", clock_nUpdates);
7031 fprintf(file, "ERROR: compiled without RXDEBUG\n");
7035 /* for backward compatibility */
7037 rx_PrintStats(FILE * file)
7039 MUTEX_ENTER(&rx_stats_mutex);
7040 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
7042 MUTEX_EXIT(&rx_stats_mutex);
7046 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7048 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7049 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
7050 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7053 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7054 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7055 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7058 " Packet size %d, " "max in packet skew %d, "
7059 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7060 (int)peer->outPacketSkew);
7064 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7066 * This mutex protects the following static variables:
7070 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7071 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7073 #define LOCK_RX_DEBUG
7074 #define UNLOCK_RX_DEBUG
7075 #endif /* AFS_PTHREAD_ENV */
7079 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7080 u_char type, void *inputData, size_t inputLength,
7081 void *outputData, size_t outputLength)
7083 static afs_int32 counter = 100;
7084 time_t waitTime, waitCount;
7085 struct rx_header theader;
7088 struct timeval tv_now, tv_wake, tv_delta;
7089 struct sockaddr_in taddr, faddr;
7103 tp = &tbuffer[sizeof(struct rx_header)];
7104 taddr.sin_family = AF_INET;
7105 taddr.sin_port = remotePort;
7106 taddr.sin_addr.s_addr = remoteAddr;
7107 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7108 taddr.sin_len = sizeof(struct sockaddr_in);
7111 memset(&theader, 0, sizeof(theader));
7112 theader.epoch = htonl(999);
7114 theader.callNumber = htonl(counter);
7117 theader.type = type;
7118 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7119 theader.serviceId = 0;
7121 memcpy(tbuffer, &theader, sizeof(theader));
7122 memcpy(tp, inputData, inputLength);
7124 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7125 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7127 /* see if there's a packet available */
7128 gettimeofday(&tv_wake,0);
7129 tv_wake.tv_sec += waitTime;
7132 FD_SET(socket, &imask);
7133 tv_delta.tv_sec = tv_wake.tv_sec;
7134 tv_delta.tv_usec = tv_wake.tv_usec;
7135 gettimeofday(&tv_now, 0);
7137 if (tv_delta.tv_usec < tv_now.tv_usec) {
7139 tv_delta.tv_usec += 1000000;
7142 tv_delta.tv_usec -= tv_now.tv_usec;
7144 if (tv_delta.tv_sec < tv_now.tv_sec) {
7148 tv_delta.tv_sec -= tv_now.tv_sec;
7151 code = select(0, &imask, 0, 0, &tv_delta);
7152 #else /* AFS_NT40_ENV */
7153 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7154 #endif /* AFS_NT40_ENV */
7155 if (code == 1 && FD_ISSET(socket, &imask)) {
7156 /* now receive a packet */
7157 faddrLen = sizeof(struct sockaddr_in);
7159 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7160 (struct sockaddr *)&faddr, &faddrLen);
7163 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7164 if (counter == ntohl(theader.callNumber))
7172 /* see if we've timed out */
7180 code -= sizeof(struct rx_header);
7181 if (code > outputLength)
7182 code = outputLength;
7183 memcpy(outputData, tp, code);
7186 #endif /* RXDEBUG */
7189 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7190 afs_uint16 remotePort, struct rx_debugStats * stat,
7191 afs_uint32 * supportedValues)
7197 struct rx_debugIn in;
7199 *supportedValues = 0;
7200 in.type = htonl(RX_DEBUGI_GETSTATS);
7203 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7204 &in, sizeof(in), stat, sizeof(*stat));
7207 * If the call was successful, fixup the version and indicate
7208 * what contents of the stat structure are valid.
7209 * Also do net to host conversion of fields here.
7213 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7214 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7216 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7217 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7219 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7220 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7222 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7223 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7225 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7226 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7228 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7229 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7231 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7232 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7234 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7235 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7237 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7238 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7240 stat->nFreePackets = ntohl(stat->nFreePackets);
7241 stat->packetReclaims = ntohl(stat->packetReclaims);
7242 stat->callsExecuted = ntohl(stat->callsExecuted);
7243 stat->nWaiting = ntohl(stat->nWaiting);
7244 stat->idleThreads = ntohl(stat->idleThreads);
7245 stat->nWaited = ntohl(stat->nWaited);
7246 stat->nPackets = ntohl(stat->nPackets);
7253 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7254 afs_uint16 remotePort, struct rx_statistics * stat,
7255 afs_uint32 * supportedValues)
7261 struct rx_debugIn in;
7262 afs_int32 *lp = (afs_int32 *) stat;
7266 * supportedValues is currently unused, but added to allow future
7267 * versioning of this function.
7270 *supportedValues = 0;
7271 in.type = htonl(RX_DEBUGI_RXSTATS);
7273 memset(stat, 0, sizeof(*stat));
7275 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7276 &in, sizeof(in), stat, sizeof(*stat));
7281 * Do net to host conversion here
7284 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7293 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7294 afs_uint16 remotePort, size_t version_length,
7299 return MakeDebugCall(socket, remoteAddr, remotePort,
7300 RX_PACKET_TYPE_VERSION, a, 1, version,
7308 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7309 afs_uint16 remotePort, afs_int32 * nextConnection,
7310 int allConnections, afs_uint32 debugSupportedValues,
7311 struct rx_debugConn * conn,
7312 afs_uint32 * supportedValues)
7318 struct rx_debugIn in;
7322 * supportedValues is currently unused, but added to allow future
7323 * versioning of this function.
7326 *supportedValues = 0;
7327 if (allConnections) {
7328 in.type = htonl(RX_DEBUGI_GETALLCONN);
7330 in.type = htonl(RX_DEBUGI_GETCONN);
7332 in.index = htonl(*nextConnection);
7333 memset(conn, 0, sizeof(*conn));
7335 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7336 &in, sizeof(in), conn, sizeof(*conn));
7339 *nextConnection += 1;
7342 * Convert old connection format to new structure.
7345 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7346 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7347 #define MOVEvL(a) (conn->a = vL->a)
7349 /* any old or unrecognized version... */
7350 for (i = 0; i < RX_MAXCALLS; i++) {
7351 MOVEvL(callState[i]);
7352 MOVEvL(callMode[i]);
7353 MOVEvL(callFlags[i]);
7354 MOVEvL(callOther[i]);
7356 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7357 MOVEvL(secStats.type);
7358 MOVEvL(secStats.level);
7359 MOVEvL(secStats.flags);
7360 MOVEvL(secStats.expires);
7361 MOVEvL(secStats.packetsReceived);
7362 MOVEvL(secStats.packetsSent);
7363 MOVEvL(secStats.bytesReceived);
7364 MOVEvL(secStats.bytesSent);
7369 * Do net to host conversion here
7371 * I don't convert host or port since we are most likely
7372 * going to want these in NBO.
7374 conn->cid = ntohl(conn->cid);
7375 conn->serial = ntohl(conn->serial);
7376 for (i = 0; i < RX_MAXCALLS; i++) {
7377 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7379 conn->error = ntohl(conn->error);
7380 conn->secStats.flags = ntohl(conn->secStats.flags);
7381 conn->secStats.expires = ntohl(conn->secStats.expires);
7382 conn->secStats.packetsReceived =
7383 ntohl(conn->secStats.packetsReceived);
7384 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7385 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7386 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7387 conn->epoch = ntohl(conn->epoch);
7388 conn->natMTU = ntohl(conn->natMTU);
7395 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7396 afs_uint16 remotePort, afs_int32 * nextPeer,
7397 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7398 afs_uint32 * supportedValues)
7404 struct rx_debugIn in;
7407 * supportedValues is currently unused, but added to allow future
7408 * versioning of this function.
7411 *supportedValues = 0;
7412 in.type = htonl(RX_DEBUGI_GETPEER);
7413 in.index = htonl(*nextPeer);
7414 memset(peer, 0, sizeof(*peer));
7416 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7417 &in, sizeof(in), peer, sizeof(*peer));
7423 * Do net to host conversion here
7425 * I don't convert host or port since we are most likely
7426 * going to want these in NBO.
7428 peer->ifMTU = ntohs(peer->ifMTU);
7429 peer->idleWhen = ntohl(peer->idleWhen);
7430 peer->refCount = ntohs(peer->refCount);
7431 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7432 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7433 peer->rtt = ntohl(peer->rtt);
7434 peer->rtt_dev = ntohl(peer->rtt_dev);
7435 peer->timeout.sec = ntohl(peer->timeout.sec);
7436 peer->timeout.usec = ntohl(peer->timeout.usec);
7437 peer->nSent = ntohl(peer->nSent);
7438 peer->reSends = ntohl(peer->reSends);
7439 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7440 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7441 peer->rateFlag = ntohl(peer->rateFlag);
7442 peer->natMTU = ntohs(peer->natMTU);
7443 peer->maxMTU = ntohs(peer->maxMTU);
7444 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7445 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7446 peer->MTU = ntohs(peer->MTU);
7447 peer->cwind = ntohs(peer->cwind);
7448 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7449 peer->congestSeq = ntohs(peer->congestSeq);
7450 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7451 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7452 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7453 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7460 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7461 struct rx_debugPeer * peerStats)
7464 afs_int32 error = 1; /* default to "did not succeed" */
7465 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7467 MUTEX_ENTER(&rx_peerHashTable_lock);
7468 for(tp = rx_peerHashTable[hashValue];
7469 tp != NULL; tp = tp->next) {
7470 if (tp->host == peerHost)
7476 MUTEX_EXIT(&rx_peerHashTable_lock);
7480 MUTEX_ENTER(&tp->peer_lock);
7481 peerStats->host = tp->host;
7482 peerStats->port = tp->port;
7483 peerStats->ifMTU = tp->ifMTU;
7484 peerStats->idleWhen = tp->idleWhen;
7485 peerStats->refCount = tp->refCount;
7486 peerStats->burstSize = tp->burstSize;
7487 peerStats->burst = tp->burst;
7488 peerStats->burstWait.sec = tp->burstWait.sec;
7489 peerStats->burstWait.usec = tp->burstWait.usec;
7490 peerStats->rtt = tp->rtt;
7491 peerStats->rtt_dev = tp->rtt_dev;
7492 peerStats->timeout.sec = tp->timeout.sec;
7493 peerStats->timeout.usec = tp->timeout.usec;
7494 peerStats->nSent = tp->nSent;
7495 peerStats->reSends = tp->reSends;
7496 peerStats->inPacketSkew = tp->inPacketSkew;
7497 peerStats->outPacketSkew = tp->outPacketSkew;
7498 peerStats->rateFlag = tp->rateFlag;
7499 peerStats->natMTU = tp->natMTU;
7500 peerStats->maxMTU = tp->maxMTU;
7501 peerStats->maxDgramPackets = tp->maxDgramPackets;
7502 peerStats->ifDgramPackets = tp->ifDgramPackets;
7503 peerStats->MTU = tp->MTU;
7504 peerStats->cwind = tp->cwind;
7505 peerStats->nDgramPackets = tp->nDgramPackets;
7506 peerStats->congestSeq = tp->congestSeq;
7507 peerStats->bytesSent.high = tp->bytesSent.high;
7508 peerStats->bytesSent.low = tp->bytesSent.low;
7509 peerStats->bytesReceived.high = tp->bytesReceived.high;
7510 peerStats->bytesReceived.low = tp->bytesReceived.low;
7511 MUTEX_EXIT(&tp->peer_lock);
7513 MUTEX_ENTER(&rx_peerHashTable_lock);
7516 MUTEX_EXIT(&rx_peerHashTable_lock);
7524 struct rx_serverQueueEntry *np;
7527 struct rx_call *call;
7528 struct rx_serverQueueEntry *sq;
7532 if (rxinit_status == 1) {
7534 return; /* Already shutdown. */
7538 #ifndef AFS_PTHREAD_ENV
7539 FD_ZERO(&rx_selectMask);
7540 #endif /* AFS_PTHREAD_ENV */
7541 rxi_dataQuota = RX_MAX_QUOTA;
7542 #ifndef AFS_PTHREAD_ENV
7544 #endif /* AFS_PTHREAD_ENV */
7547 #ifndef AFS_PTHREAD_ENV
7548 #ifndef AFS_USE_GETTIMEOFDAY
7550 #endif /* AFS_USE_GETTIMEOFDAY */
7551 #endif /* AFS_PTHREAD_ENV */
7553 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7554 call = queue_First(&rx_freeCallQueue, rx_call);
7556 rxi_Free(call, sizeof(struct rx_call));
7559 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7560 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7566 struct rx_peer **peer_ptr, **peer_end;
7567 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7568 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7570 struct rx_peer *peer, *next;
7572 MUTEX_ENTER(&rx_peerHashTable_lock);
7573 for (peer = *peer_ptr; peer; peer = next) {
7574 rx_interface_stat_p rpc_stat, nrpc_stat;
7577 MUTEX_ENTER(&rx_rpc_stats);
7578 MUTEX_ENTER(&peer->peer_lock);
7580 (&peer->rpcStats, rpc_stat, nrpc_stat,
7581 rx_interface_stat)) {
7582 unsigned int num_funcs;
7585 queue_Remove(&rpc_stat->queue_header);
7586 queue_Remove(&rpc_stat->all_peers);
7587 num_funcs = rpc_stat->stats[0].func_total;
7589 sizeof(rx_interface_stat_t) +
7590 rpc_stat->stats[0].func_total *
7591 sizeof(rx_function_entry_v1_t);
7593 rxi_Free(rpc_stat, space);
7595 /* rx_rpc_stats must be held */
7596 rxi_rpc_peer_stat_cnt -= num_funcs;
7598 MUTEX_EXIT(&peer->peer_lock);
7599 MUTEX_EXIT(&rx_rpc_stats);
7603 if (rx_stats_active)
7604 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7606 MUTEX_EXIT(&rx_peerHashTable_lock);
7609 for (i = 0; i < RX_MAX_SERVICES; i++) {
7611 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7613 for (i = 0; i < rx_hashTableSize; i++) {
7614 struct rx_connection *tc, *ntc;
7615 MUTEX_ENTER(&rx_connHashTable_lock);
7616 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7618 for (j = 0; j < RX_MAXCALLS; j++) {
7620 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7623 rxi_Free(tc, sizeof(*tc));
7625 MUTEX_EXIT(&rx_connHashTable_lock);
7628 MUTEX_ENTER(&freeSQEList_lock);
7630 while ((np = rx_FreeSQEList)) {
7631 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7632 MUTEX_DESTROY(&np->lock);
7633 rxi_Free(np, sizeof(*np));
7636 MUTEX_EXIT(&freeSQEList_lock);
7637 MUTEX_DESTROY(&freeSQEList_lock);
7638 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7639 MUTEX_DESTROY(&rx_connHashTable_lock);
7640 MUTEX_DESTROY(&rx_peerHashTable_lock);
7641 MUTEX_DESTROY(&rx_serverPool_lock);
7643 osi_Free(rx_connHashTable,
7644 rx_hashTableSize * sizeof(struct rx_connection *));
7645 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7647 UNPIN(rx_connHashTable,
7648 rx_hashTableSize * sizeof(struct rx_connection *));
7649 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7651 rxi_FreeAllPackets();
7653 MUTEX_ENTER(&rx_quota_mutex);
7654 rxi_dataQuota = RX_MAX_QUOTA;
7655 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7656 MUTEX_EXIT(&rx_quota_mutex);
7661 #ifdef RX_ENABLE_LOCKS
7663 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7665 if (!MUTEX_ISMINE(lockaddr))
7666 osi_Panic("Lock not held: %s", msg);
7668 #endif /* RX_ENABLE_LOCKS */
7673 * Routines to implement connection specific data.
7677 rx_KeyCreate(rx_destructor_t rtn)
7680 MUTEX_ENTER(&rxi_keyCreate_lock);
7681 key = rxi_keyCreate_counter++;
7682 rxi_keyCreate_destructor = (rx_destructor_t *)
7683 realloc((void *)rxi_keyCreate_destructor,
7684 (key + 1) * sizeof(rx_destructor_t));
7685 rxi_keyCreate_destructor[key] = rtn;
7686 MUTEX_EXIT(&rxi_keyCreate_lock);
7691 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7694 MUTEX_ENTER(&conn->conn_data_lock);
7695 if (!conn->specific) {
7696 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7697 for (i = 0; i < key; i++)
7698 conn->specific[i] = NULL;
7699 conn->nSpecific = key + 1;
7700 conn->specific[key] = ptr;
7701 } else if (key >= conn->nSpecific) {
7702 conn->specific = (void **)
7703 realloc(conn->specific, (key + 1) * sizeof(void *));
7704 for (i = conn->nSpecific; i < key; i++)
7705 conn->specific[i] = NULL;
7706 conn->nSpecific = key + 1;
7707 conn->specific[key] = ptr;
7709 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7710 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7711 conn->specific[key] = ptr;
7713 MUTEX_EXIT(&conn->conn_data_lock);
7717 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7720 MUTEX_ENTER(&svc->svc_data_lock);
7721 if (!svc->specific) {
7722 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7723 for (i = 0; i < key; i++)
7724 svc->specific[i] = NULL;
7725 svc->nSpecific = key + 1;
7726 svc->specific[key] = ptr;
7727 } else if (key >= svc->nSpecific) {
7728 svc->specific = (void **)
7729 realloc(svc->specific, (key + 1) * sizeof(void *));
7730 for (i = svc->nSpecific; i < key; i++)
7731 svc->specific[i] = NULL;
7732 svc->nSpecific = key + 1;
7733 svc->specific[key] = ptr;
7735 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7736 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7737 svc->specific[key] = ptr;
7739 MUTEX_EXIT(&svc->svc_data_lock);
7743 rx_GetSpecific(struct rx_connection *conn, int key)
7746 MUTEX_ENTER(&conn->conn_data_lock);
7747 if (key >= conn->nSpecific)
7750 ptr = conn->specific[key];
7751 MUTEX_EXIT(&conn->conn_data_lock);
7756 rx_GetServiceSpecific(struct rx_service *svc, int key)
7759 MUTEX_ENTER(&svc->svc_data_lock);
7760 if (key >= svc->nSpecific)
7763 ptr = svc->specific[key];
7764 MUTEX_EXIT(&svc->svc_data_lock);
7769 #endif /* !KERNEL */
7772 * processStats is a queue used to store the statistics for the local
7773 * process. Its contents are similar to the contents of the rpcStats
7774 * queue on a rx_peer structure, but the actual data stored within
7775 * this queue contains totals across the lifetime of the process (assuming
7776 * the stats have not been reset) - unlike the per peer structures
7777 * which can come and go based upon the peer lifetime.
7780 static struct rx_queue processStats = { &processStats, &processStats };
7783 * peerStats is a queue used to store the statistics for all peer structs.
7784 * Its contents are the union of all the peer rpcStats queues.
7787 static struct rx_queue peerStats = { &peerStats, &peerStats };
7790 * rxi_monitor_processStats is used to turn process wide stat collection
7794 static int rxi_monitor_processStats = 0;
7797 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7800 static int rxi_monitor_peerStats = 0;
7803 * rxi_AddRpcStat - given all of the information for a particular rpc
7804 * call, create (if needed) and update the stat totals for the rpc.
7808 * IN stats - the queue of stats that will be updated with the new value
7810 * IN rxInterface - a unique number that identifies the rpc interface
7812 * IN currentFunc - the index of the function being invoked
7814 * IN totalFunc - the total number of functions in this interface
7816 * IN queueTime - the amount of time this function waited for a thread
7818 * IN execTime - the amount of time this function invocation took to execute
7820 * IN bytesSent - the number bytes sent by this invocation
7822 * IN bytesRcvd - the number bytes received by this invocation
7824 * IN isServer - if true, this invocation was made to a server
7826 * IN remoteHost - the ip address of the remote host
7828 * IN remotePort - the port of the remote host
7830 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7832 * INOUT counter - if a new stats structure is allocated, the counter will
7833 * be updated with the new number of allocated stat structures
7841 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7842 afs_uint32 currentFunc, afs_uint32 totalFunc,
7843 struct clock *queueTime, struct clock *execTime,
7844 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7845 afs_uint32 remoteHost, afs_uint32 remotePort,
7846 int addToPeerList, unsigned int *counter)
7849 rx_interface_stat_p rpc_stat, nrpc_stat;
7852 * See if there's already a structure for this interface
7855 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7856 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7857 && (rpc_stat->stats[0].remote_is_server == isServer))
7862 * Didn't find a match so allocate a new structure and add it to the
7866 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7867 || (rpc_stat->stats[0].interfaceId != rxInterface)
7868 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7873 sizeof(rx_interface_stat_t) +
7874 totalFunc * sizeof(rx_function_entry_v1_t);
7876 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7877 if (rpc_stat == NULL) {
7881 *counter += totalFunc;
7882 for (i = 0; i < totalFunc; i++) {
7883 rpc_stat->stats[i].remote_peer = remoteHost;
7884 rpc_stat->stats[i].remote_port = remotePort;
7885 rpc_stat->stats[i].remote_is_server = isServer;
7886 rpc_stat->stats[i].interfaceId = rxInterface;
7887 rpc_stat->stats[i].func_total = totalFunc;
7888 rpc_stat->stats[i].func_index = i;
7889 hzero(rpc_stat->stats[i].invocations);
7890 hzero(rpc_stat->stats[i].bytes_sent);
7891 hzero(rpc_stat->stats[i].bytes_rcvd);
7892 rpc_stat->stats[i].queue_time_sum.sec = 0;
7893 rpc_stat->stats[i].queue_time_sum.usec = 0;
7894 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7895 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7896 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7897 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7898 rpc_stat->stats[i].queue_time_max.sec = 0;
7899 rpc_stat->stats[i].queue_time_max.usec = 0;
7900 rpc_stat->stats[i].execution_time_sum.sec = 0;
7901 rpc_stat->stats[i].execution_time_sum.usec = 0;
7902 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7903 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7904 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7905 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7906 rpc_stat->stats[i].execution_time_max.sec = 0;
7907 rpc_stat->stats[i].execution_time_max.usec = 0;
7909 queue_Prepend(stats, rpc_stat);
7910 if (addToPeerList) {
7911 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7916 * Increment the stats for this function
7919 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7920 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7921 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7922 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7923 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7924 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7925 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7927 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7928 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7930 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7931 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7933 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7934 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7936 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7937 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7945 * rx_IncrementTimeAndCount - increment the times and count for a particular
7950 * IN peer - the peer who invoked the rpc
7952 * IN rxInterface - a unique number that identifies the rpc interface
7954 * IN currentFunc - the index of the function being invoked
7956 * IN totalFunc - the total number of functions in this interface
7958 * IN queueTime - the amount of time this function waited for a thread
7960 * IN execTime - the amount of time this function invocation took to execute
7962 * IN bytesSent - the number bytes sent by this invocation
7964 * IN bytesRcvd - the number bytes received by this invocation
7966 * IN isServer - if true, this invocation was made to a server
7974 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7975 afs_uint32 currentFunc, afs_uint32 totalFunc,
7976 struct clock *queueTime, struct clock *execTime,
7977 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7981 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7984 MUTEX_ENTER(&rx_rpc_stats);
7986 if (rxi_monitor_peerStats) {
7987 MUTEX_ENTER(&peer->peer_lock);
7988 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7989 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7990 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7991 MUTEX_EXIT(&peer->peer_lock);
7994 if (rxi_monitor_processStats) {
7995 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7996 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7997 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8000 MUTEX_EXIT(&rx_rpc_stats);
8005 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8009 * IN callerVersion - the rpc stat version of the caller.
8011 * IN count - the number of entries to marshall.
8013 * IN stats - pointer to stats to be marshalled.
8015 * OUT ptr - Where to store the marshalled data.
8022 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8023 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8029 * We only support the first version
8031 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8032 *(ptr++) = stats->remote_peer;
8033 *(ptr++) = stats->remote_port;
8034 *(ptr++) = stats->remote_is_server;
8035 *(ptr++) = stats->interfaceId;
8036 *(ptr++) = stats->func_total;
8037 *(ptr++) = stats->func_index;
8038 *(ptr++) = hgethi(stats->invocations);
8039 *(ptr++) = hgetlo(stats->invocations);
8040 *(ptr++) = hgethi(stats->bytes_sent);
8041 *(ptr++) = hgetlo(stats->bytes_sent);
8042 *(ptr++) = hgethi(stats->bytes_rcvd);
8043 *(ptr++) = hgetlo(stats->bytes_rcvd);
8044 *(ptr++) = stats->queue_time_sum.sec;
8045 *(ptr++) = stats->queue_time_sum.usec;
8046 *(ptr++) = stats->queue_time_sum_sqr.sec;
8047 *(ptr++) = stats->queue_time_sum_sqr.usec;
8048 *(ptr++) = stats->queue_time_min.sec;
8049 *(ptr++) = stats->queue_time_min.usec;
8050 *(ptr++) = stats->queue_time_max.sec;
8051 *(ptr++) = stats->queue_time_max.usec;
8052 *(ptr++) = stats->execution_time_sum.sec;
8053 *(ptr++) = stats->execution_time_sum.usec;
8054 *(ptr++) = stats->execution_time_sum_sqr.sec;
8055 *(ptr++) = stats->execution_time_sum_sqr.usec;
8056 *(ptr++) = stats->execution_time_min.sec;
8057 *(ptr++) = stats->execution_time_min.usec;
8058 *(ptr++) = stats->execution_time_max.sec;
8059 *(ptr++) = stats->execution_time_max.usec;
8065 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8070 * IN callerVersion - the rpc stat version of the caller
8072 * OUT myVersion - the rpc stat version of this function
8074 * OUT clock_sec - local time seconds
8076 * OUT clock_usec - local time microseconds
8078 * OUT allocSize - the number of bytes allocated to contain stats
8080 * OUT statCount - the number stats retrieved from this process.
8082 * OUT stats - the actual stats retrieved from this process.
8086 * Returns void. If successful, stats will != NULL.
8090 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8091 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8092 size_t * allocSize, afs_uint32 * statCount,
8093 afs_uint32 ** stats)
8103 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8106 * Check to see if stats are enabled
8109 MUTEX_ENTER(&rx_rpc_stats);
8110 if (!rxi_monitor_processStats) {
8111 MUTEX_EXIT(&rx_rpc_stats);
8115 clock_GetTime(&now);
8116 *clock_sec = now.sec;
8117 *clock_usec = now.usec;
8120 * Allocate the space based upon the caller version
8122 * If the client is at an older version than we are,
8123 * we return the statistic data in the older data format, but
8124 * we still return our version number so the client knows we
8125 * are maintaining more data than it can retrieve.
8128 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8129 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8130 *statCount = rxi_rpc_process_stat_cnt;
8133 * This can't happen yet, but in the future version changes
8134 * can be handled by adding additional code here
8138 if (space > (size_t) 0) {
8140 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
8143 rx_interface_stat_p rpc_stat, nrpc_stat;
8147 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8149 * Copy the data based upon the caller version
8151 rx_MarshallProcessRPCStats(callerVersion,
8152 rpc_stat->stats[0].func_total,
8153 rpc_stat->stats, &ptr);
8159 MUTEX_EXIT(&rx_rpc_stats);
8164 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8168 * IN callerVersion - the rpc stat version of the caller
8170 * OUT myVersion - the rpc stat version of this function
8172 * OUT clock_sec - local time seconds
8174 * OUT clock_usec - local time microseconds
8176 * OUT allocSize - the number of bytes allocated to contain stats
8178 * OUT statCount - the number of stats retrieved from the individual
8181 * OUT stats - the actual stats retrieved from the individual peer structures.
8185 * Returns void. If successful, stats will != NULL.
8189 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8190 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8191 size_t * allocSize, afs_uint32 * statCount,
8192 afs_uint32 ** stats)
8202 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8205 * Check to see if stats are enabled
8208 MUTEX_ENTER(&rx_rpc_stats);
8209 if (!rxi_monitor_peerStats) {
8210 MUTEX_EXIT(&rx_rpc_stats);
8214 clock_GetTime(&now);
8215 *clock_sec = now.sec;
8216 *clock_usec = now.usec;
8219 * Allocate the space based upon the caller version
8221 * If the client is at an older version than we are,
8222 * we return the statistic data in the older data format, but
8223 * we still return our version number so the client knows we
8224 * are maintaining more data than it can retrieve.
8227 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8228 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8229 *statCount = rxi_rpc_peer_stat_cnt;
8232 * This can't happen yet, but in the future version changes
8233 * can be handled by adding additional code here
8237 if (space > (size_t) 0) {
8239 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
8242 rx_interface_stat_p rpc_stat, nrpc_stat;
8246 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8248 * We have to fix the offset of rpc_stat since we are
8249 * keeping this structure on two rx_queues. The rx_queue
8250 * package assumes that the rx_queue member is the first
8251 * member of the structure. That is, rx_queue assumes that
8252 * any one item is only on one queue at a time. We are
8253 * breaking that assumption and so we have to do a little
8254 * math to fix our pointers.
8257 fix_offset = (char *)rpc_stat;
8258 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8259 rpc_stat = (rx_interface_stat_p) fix_offset;
8262 * Copy the data based upon the caller version
8264 rx_MarshallProcessRPCStats(callerVersion,
8265 rpc_stat->stats[0].func_total,
8266 rpc_stat->stats, &ptr);
8272 MUTEX_EXIT(&rx_rpc_stats);
8277 * rx_FreeRPCStats - free memory allocated by
8278 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8282 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8283 * rx_RetrievePeerRPCStats
8285 * IN allocSize - the number of bytes in stats.
8293 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8295 rxi_Free(stats, allocSize);
8299 * rx_queryProcessRPCStats - see if process rpc stat collection is
8300 * currently enabled.
8306 * Returns 0 if stats are not enabled != 0 otherwise
8310 rx_queryProcessRPCStats(void)
8313 MUTEX_ENTER(&rx_rpc_stats);
8314 rc = rxi_monitor_processStats;
8315 MUTEX_EXIT(&rx_rpc_stats);
8320 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8326 * Returns 0 if stats are not enabled != 0 otherwise
8330 rx_queryPeerRPCStats(void)
8333 MUTEX_ENTER(&rx_rpc_stats);
8334 rc = rxi_monitor_peerStats;
8335 MUTEX_EXIT(&rx_rpc_stats);
8340 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8350 rx_enableProcessRPCStats(void)
8352 MUTEX_ENTER(&rx_rpc_stats);
8353 rx_enable_stats = 1;
8354 rxi_monitor_processStats = 1;
8355 MUTEX_EXIT(&rx_rpc_stats);
8359 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8369 rx_enablePeerRPCStats(void)
8371 MUTEX_ENTER(&rx_rpc_stats);
8372 rx_enable_stats = 1;
8373 rxi_monitor_peerStats = 1;
8374 MUTEX_EXIT(&rx_rpc_stats);
8378 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8388 rx_disableProcessRPCStats(void)
8390 rx_interface_stat_p rpc_stat, nrpc_stat;
8393 MUTEX_ENTER(&rx_rpc_stats);
8396 * Turn off process statistics and if peer stats is also off, turn
8400 rxi_monitor_processStats = 0;
8401 if (rxi_monitor_peerStats == 0) {
8402 rx_enable_stats = 0;
8405 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8406 unsigned int num_funcs = 0;
8409 queue_Remove(rpc_stat);
8410 num_funcs = rpc_stat->stats[0].func_total;
8412 sizeof(rx_interface_stat_t) +
8413 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8415 rxi_Free(rpc_stat, space);
8416 rxi_rpc_process_stat_cnt -= num_funcs;
8418 MUTEX_EXIT(&rx_rpc_stats);
8422 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8432 rx_disablePeerRPCStats(void)
8434 struct rx_peer **peer_ptr, **peer_end;
8438 * Turn off peer statistics and if process stats is also off, turn
8442 rxi_monitor_peerStats = 0;
8443 if (rxi_monitor_processStats == 0) {
8444 rx_enable_stats = 0;
8447 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8448 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8450 struct rx_peer *peer, *next, *prev;
8452 MUTEX_ENTER(&rx_peerHashTable_lock);
8453 MUTEX_ENTER(&rx_rpc_stats);
8454 for (prev = peer = *peer_ptr; peer; peer = next) {
8456 code = MUTEX_TRYENTER(&peer->peer_lock);
8458 rx_interface_stat_p rpc_stat, nrpc_stat;
8461 if (prev == *peer_ptr) {
8472 MUTEX_EXIT(&rx_peerHashTable_lock);
8475 (&peer->rpcStats, rpc_stat, nrpc_stat,
8476 rx_interface_stat)) {
8477 unsigned int num_funcs = 0;
8480 queue_Remove(&rpc_stat->queue_header);
8481 queue_Remove(&rpc_stat->all_peers);
8482 num_funcs = rpc_stat->stats[0].func_total;
8484 sizeof(rx_interface_stat_t) +
8485 rpc_stat->stats[0].func_total *
8486 sizeof(rx_function_entry_v1_t);
8488 rxi_Free(rpc_stat, space);
8489 rxi_rpc_peer_stat_cnt -= num_funcs;
8491 MUTEX_EXIT(&peer->peer_lock);
8493 MUTEX_ENTER(&rx_peerHashTable_lock);
8503 MUTEX_EXIT(&rx_rpc_stats);
8504 MUTEX_EXIT(&rx_peerHashTable_lock);
8509 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8514 * IN clearFlag - flag indicating which stats to clear
8522 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8524 rx_interface_stat_p rpc_stat, nrpc_stat;
8526 MUTEX_ENTER(&rx_rpc_stats);
8528 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8529 unsigned int num_funcs = 0, i;
8530 num_funcs = rpc_stat->stats[0].func_total;
8531 for (i = 0; i < num_funcs; i++) {
8532 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8533 hzero(rpc_stat->stats[i].invocations);
8535 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8536 hzero(rpc_stat->stats[i].bytes_sent);
8538 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8539 hzero(rpc_stat->stats[i].bytes_rcvd);
8541 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8542 rpc_stat->stats[i].queue_time_sum.sec = 0;
8543 rpc_stat->stats[i].queue_time_sum.usec = 0;
8545 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8546 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8547 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8549 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8550 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8551 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8553 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8554 rpc_stat->stats[i].queue_time_max.sec = 0;
8555 rpc_stat->stats[i].queue_time_max.usec = 0;
8557 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8558 rpc_stat->stats[i].execution_time_sum.sec = 0;
8559 rpc_stat->stats[i].execution_time_sum.usec = 0;
8561 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8562 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8563 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8565 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8566 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8567 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8569 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8570 rpc_stat->stats[i].execution_time_max.sec = 0;
8571 rpc_stat->stats[i].execution_time_max.usec = 0;
8576 MUTEX_EXIT(&rx_rpc_stats);
8580 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8585 * IN clearFlag - flag indicating which stats to clear
8593 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8595 rx_interface_stat_p rpc_stat, nrpc_stat;
8597 MUTEX_ENTER(&rx_rpc_stats);
8599 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8600 unsigned int num_funcs = 0, i;
8603 * We have to fix the offset of rpc_stat since we are
8604 * keeping this structure on two rx_queues. The rx_queue
8605 * package assumes that the rx_queue member is the first
8606 * member of the structure. That is, rx_queue assumes that
8607 * any one item is only on one queue at a time. We are
8608 * breaking that assumption and so we have to do a little
8609 * math to fix our pointers.
8612 fix_offset = (char *)rpc_stat;
8613 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8614 rpc_stat = (rx_interface_stat_p) fix_offset;
8616 num_funcs = rpc_stat->stats[0].func_total;
8617 for (i = 0; i < num_funcs; i++) {
8618 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8619 hzero(rpc_stat->stats[i].invocations);
8621 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8622 hzero(rpc_stat->stats[i].bytes_sent);
8624 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8625 hzero(rpc_stat->stats[i].bytes_rcvd);
8627 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8628 rpc_stat->stats[i].queue_time_sum.sec = 0;
8629 rpc_stat->stats[i].queue_time_sum.usec = 0;
8631 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8632 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8633 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8635 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8636 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8637 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8639 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8640 rpc_stat->stats[i].queue_time_max.sec = 0;
8641 rpc_stat->stats[i].queue_time_max.usec = 0;
8643 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8644 rpc_stat->stats[i].execution_time_sum.sec = 0;
8645 rpc_stat->stats[i].execution_time_sum.usec = 0;
8647 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8648 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8649 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8651 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8652 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8653 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8655 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8656 rpc_stat->stats[i].execution_time_max.sec = 0;
8657 rpc_stat->stats[i].execution_time_max.usec = 0;
8662 MUTEX_EXIT(&rx_rpc_stats);
8666 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8667 * is authorized to enable/disable/clear RX statistics.
8669 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8672 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8674 rxi_rxstat_userok = proc;
8678 rx_RxStatUserOk(struct rx_call *call)
8680 if (!rxi_rxstat_userok)
8682 return rxi_rxstat_userok(call);
8687 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8688 * function in the MSVC runtime DLL (msvcrt.dll).
8690 * Note: the system serializes calls to this function.
8693 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8694 DWORD reason, /* reason function is being called */
8695 LPVOID reserved) /* reserved for future use */
8698 case DLL_PROCESS_ATTACH:
8699 /* library is being attached to a process */
8703 case DLL_PROCESS_DETACH:
8710 #endif /* AFS_NT40_ENV */
8713 int rx_DumpCalls(FILE *outputFile, char *cookie)
8715 #ifdef RXDEBUG_PACKET
8716 #ifdef KDUMP_RX_LOCK
8717 struct rx_call_rx_lock *c;
8724 #define RXDPRINTF sprintf
8725 #define RXDPRINTOUT output
8727 #define RXDPRINTF fprintf
8728 #define RXDPRINTOUT outputFile
8731 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8733 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8736 for (c = rx_allCallsp; c; c = c->allNextp) {
8737 u_short rqc, tqc, iovqc;
8738 struct rx_packet *p, *np;
8740 MUTEX_ENTER(&c->lock);
8741 queue_Count(&c->rq, p, np, rx_packet, rqc);
8742 queue_Count(&c->tq, p, np, rx_packet, tqc);
8743 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8745 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, "
8746 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8747 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8748 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8749 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8750 #ifdef RX_ENABLE_LOCKS
8753 #ifdef RX_REFCOUNT_CHECK
8754 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8755 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8758 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,
8759 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8760 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8761 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8762 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8763 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8764 #ifdef RX_ENABLE_LOCKS
8765 , (afs_uint32)c->refCount
8767 #ifdef RX_REFCOUNT_CHECK
8768 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8771 MUTEX_EXIT(&c->lock);
8774 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8777 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8779 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8781 #endif /* RXDEBUG_PACKET */