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 #include "rx_atomic.h"
73 #include "rx_internal.h"
75 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
76 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
77 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
79 extern afs_int32 afs_termState;
81 #include "sys/lockl.h"
82 #include "sys/lock_def.h"
83 #endif /* AFS_AIX41_ENV */
84 # include "afs/rxgen_consts.h"
86 # include <sys/types.h>
96 # include <afs/afsutil.h>
97 # include <WINNT\afsreg.h>
99 # include <sys/socket.h>
100 # include <sys/file.h>
102 # include <sys/stat.h>
103 # include <netinet/in.h>
104 # include <sys/time.h>
107 # include "rx_user.h"
108 # include "rx_clock.h"
109 # include "rx_queue.h"
110 # include "rx_atomic.h"
111 # include "rx_globals.h"
112 # include "rx_trace.h"
113 # include "rx_internal.h"
114 # include "rx_stats.h"
115 # include <afs/rxgen_consts.h>
119 #ifdef AFS_PTHREAD_ENV
121 int (*registerProgram) (pid_t, char *) = 0;
122 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
125 int (*registerProgram) (PROCESS, char *) = 0;
126 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
130 /* Local static routines */
131 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
132 #ifdef RX_ENABLE_LOCKS
133 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
136 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
138 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
139 rx_atomic_t rxi_start_in_error;
141 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
144 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
145 * currently allocated within rx. This number is used to allocate the
146 * memory required to return the statistics when queried.
147 * Protected by the rx_rpc_stats mutex.
150 static unsigned int rxi_rpc_peer_stat_cnt;
153 * rxi_rpc_process_stat_cnt counts the total number of local process stat
154 * structures currently allocated within rx. The number is used to allocate
155 * the memory required to return the statistics when queried.
156 * Protected by the rx_rpc_stats mutex.
159 static unsigned int rxi_rpc_process_stat_cnt;
161 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
162 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
164 #if !defined(offsetof)
165 #include <stddef.h> /* for definition of offsetof() */
168 #ifdef RX_ENABLE_LOCKS
169 afs_kmutex_t rx_atomic_mutex;
172 #ifdef AFS_PTHREAD_ENV
176 * Use procedural initialization of mutexes/condition variables
180 extern afs_kmutex_t rx_quota_mutex;
181 extern afs_kmutex_t rx_pthread_mutex;
182 extern afs_kmutex_t rx_packets_mutex;
183 extern afs_kmutex_t rx_refcnt_mutex;
184 extern afs_kmutex_t des_init_mutex;
185 extern afs_kmutex_t des_random_mutex;
186 extern afs_kmutex_t rx_clock_mutex;
187 extern afs_kmutex_t rxi_connCacheMutex;
188 extern afs_kmutex_t rx_event_mutex;
189 extern afs_kmutex_t osi_malloc_mutex;
190 extern afs_kmutex_t event_handler_mutex;
191 extern afs_kmutex_t listener_mutex;
192 extern afs_kmutex_t rx_if_init_mutex;
193 extern afs_kmutex_t rx_if_mutex;
194 extern afs_kmutex_t rxkad_client_uid_mutex;
195 extern afs_kmutex_t rxkad_random_mutex;
197 extern afs_kcondvar_t rx_event_handler_cond;
198 extern afs_kcondvar_t rx_listener_cond;
200 static afs_kmutex_t epoch_mutex;
201 static afs_kmutex_t rx_init_mutex;
202 static afs_kmutex_t rx_debug_mutex;
203 static afs_kmutex_t rx_rpc_stats;
206 rxi_InitPthread(void)
208 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
216 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
217 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
220 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
222 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
224 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
226 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
228 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
230 assert(pthread_cond_init
231 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
232 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
234 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
235 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
237 rxkad_global_stats_init();
239 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
240 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
241 #ifdef RX_ENABLE_LOCKS
244 #endif /* RX_LOCKS_DB */
245 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
246 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
248 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
250 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
252 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
254 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
255 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
256 #endif /* RX_ENABLE_LOCKS */
259 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
260 #define INIT_PTHREAD_LOCKS \
261 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
263 * The rx_stats_mutex mutex protects the following global variables:
264 * rxi_lowConnRefCount
265 * rxi_lowPeerRefCount
274 * The rx_quota_mutex mutex protects the following global variables:
282 * The rx_freePktQ_lock protects the following global variables:
287 * The rx_packets_mutex mutex protects the following global variables:
295 * The rx_pthread_mutex mutex protects the following global variables:
296 * rxi_fcfs_thread_num
299 #define INIT_PTHREAD_LOCKS
303 /* Variables for handling the minProcs implementation. availProcs gives the
304 * number of threads available in the pool at this moment (not counting dudes
305 * executing right now). totalMin gives the total number of procs required
306 * for handling all minProcs requests. minDeficit is a dynamic variable
307 * tracking the # of procs required to satisfy all of the remaining minProcs
309 * For fine grain locking to work, the quota check and the reservation of
310 * a server thread has to come while rxi_availProcs and rxi_minDeficit
311 * are locked. To this end, the code has been modified under #ifdef
312 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
313 * same time. A new function, ReturnToServerPool() returns the allocation.
315 * A call can be on several queue's (but only one at a time). When
316 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
317 * that no one else is touching the queue. To this end, we store the address
318 * of the queue lock in the call structure (under the call lock) when we
319 * put the call on a queue, and we clear the call_queue_lock when the
320 * call is removed from a queue (once the call lock has been obtained).
321 * This allows rxi_ResetCall to safely synchronize with others wishing
322 * to manipulate the queue.
325 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
326 static afs_kmutex_t rx_rpc_stats;
327 void rxi_StartUnlocked(struct rxevent *event, void *call,
328 void *arg1, int istack);
331 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
332 ** pretty good that the next packet coming in is from the same connection
333 ** as the last packet, since we're send multiple packets in a transmit window.
335 struct rx_connection *rxLastConn = 0;
337 #ifdef RX_ENABLE_LOCKS
338 /* The locking hierarchy for rx fine grain locking is composed of these
341 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
342 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
343 * call->lock - locks call data fields.
344 * These are independent of each other:
345 * rx_freeCallQueue_lock
350 * serverQueueEntry->lock
351 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
353 * peer->lock - locks peer data fields.
354 * conn_data_lock - that more than one thread is not updating a conn data
355 * field at the same time.
366 * Do we need a lock to protect the peer field in the conn structure?
367 * conn->peer was previously a constant for all intents and so has no
368 * lock protecting this field. The multihomed client delta introduced
369 * a RX code change : change the peer field in the connection structure
370 * to that remote interface from which the last packet for this
371 * connection was sent out. This may become an issue if further changes
374 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
375 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
377 /* rxdb_fileID is used to identify the lock location, along with line#. */
378 static int rxdb_fileID = RXDB_FILE_RX;
379 #endif /* RX_LOCKS_DB */
380 #else /* RX_ENABLE_LOCKS */
381 #define SET_CALL_QUEUE_LOCK(C, L)
382 #define CLEAR_CALL_QUEUE_LOCK(C)
383 #endif /* RX_ENABLE_LOCKS */
384 struct rx_serverQueueEntry *rx_waitForPacket = 0;
385 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
387 /* ------------Exported Interfaces------------- */
389 /* This function allows rxkad to set the epoch to a suitably random number
390 * which rx_NewConnection will use in the future. The principle purpose is to
391 * get rxnull connections to use the same epoch as the rxkad connections do, at
392 * least once the first rxkad connection is established. This is important now
393 * that the host/port addresses aren't used in FindConnection: the uniqueness
394 * of epoch/cid matters and the start time won't do. */
396 #ifdef AFS_PTHREAD_ENV
398 * This mutex protects the following global variables:
402 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
403 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
407 #endif /* AFS_PTHREAD_ENV */
410 rx_SetEpoch(afs_uint32 epoch)
417 /* Initialize rx. A port number may be mentioned, in which case this
418 * becomes the default port number for any service installed later.
419 * If 0 is provided for the port number, a random port will be chosen
420 * by the kernel. Whether this will ever overlap anything in
421 * /etc/services is anybody's guess... Returns 0 on success, -1 on
426 int rxinit_status = 1;
427 #ifdef AFS_PTHREAD_ENV
429 * This mutex protects the following global variables:
433 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
434 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
437 #define UNLOCK_RX_INIT
441 rx_InitHost(u_int host, u_int port)
448 char *htable, *ptable;
455 if (rxinit_status == 0) {
456 tmp_status = rxinit_status;
458 return tmp_status; /* Already started; return previous error code. */
464 if (afs_winsockInit() < 0)
470 * Initialize anything necessary to provide a non-premptive threading
473 rxi_InitializeThreadSupport();
476 /* Allocate and initialize a socket for client and perhaps server
479 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
480 if (rx_socket == OSI_NULLSOCKET) {
484 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
487 #endif /* RX_LOCKS_DB */
488 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
489 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
490 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
491 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
492 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
493 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
494 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
495 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
496 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
498 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
500 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
502 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
504 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
505 #if defined(AFS_HPUX110_ENV)
507 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
508 #endif /* AFS_HPUX110_ENV */
509 #endif /* RX_ENABLE_LOCKS && KERNEL */
512 rx_connDeadTime = 12;
513 rx_tranquil = 0; /* reset flag */
514 rxi_ResetStatistics();
516 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
517 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
518 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
519 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
520 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
521 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
523 /* Malloc up a bunch of packets & buffers */
525 queue_Init(&rx_freePacketQueue);
526 rxi_NeedMorePackets = FALSE;
527 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
529 /* enforce a minimum number of allocated packets */
530 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
531 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
533 /* allocate the initial free packet pool */
534 #ifdef RX_ENABLE_TSFPQ
535 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
536 #else /* RX_ENABLE_TSFPQ */
537 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
538 #endif /* RX_ENABLE_TSFPQ */
545 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
546 tv.tv_sec = clock_now.sec;
547 tv.tv_usec = clock_now.usec;
548 srand((unsigned int)tv.tv_usec);
555 #if defined(KERNEL) && !defined(UKERNEL)
556 /* Really, this should never happen in a real kernel */
559 struct sockaddr_in addr;
561 int addrlen = sizeof(addr);
563 socklen_t addrlen = sizeof(addr);
565 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
569 rx_port = addr.sin_port;
572 rx_stats.minRtt.sec = 9999999;
574 rx_SetEpoch(tv.tv_sec | 0x80000000);
576 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
577 * will provide a randomer value. */
579 MUTEX_ENTER(&rx_quota_mutex);
580 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
581 MUTEX_EXIT(&rx_quota_mutex);
582 /* *Slightly* random start time for the cid. This is just to help
583 * out with the hashing function at the peer */
584 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
585 rx_connHashTable = (struct rx_connection **)htable;
586 rx_peerHashTable = (struct rx_peer **)ptable;
588 rx_lastAckDelay.sec = 0;
589 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
590 rx_hardAckDelay.sec = 0;
591 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
592 rx_softAckDelay.sec = 0;
593 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
595 rxevent_Init(20, rxi_ReScheduleEvents);
597 /* Initialize various global queues */
598 queue_Init(&rx_idleServerQueue);
599 queue_Init(&rx_incomingCallQueue);
600 queue_Init(&rx_freeCallQueue);
602 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
603 /* Initialize our list of usable IP addresses. */
607 /* Start listener process (exact function is dependent on the
608 * implementation environment--kernel or user space) */
612 tmp_status = rxinit_status = 0;
620 return rx_InitHost(htonl(INADDR_ANY), port);
623 /* called with unincremented nRequestsRunning to see if it is OK to start
624 * a new thread in this service. Could be "no" for two reasons: over the
625 * max quota, or would prevent others from reaching their min quota.
627 #ifdef RX_ENABLE_LOCKS
628 /* This verion of QuotaOK reserves quota if it's ok while the
629 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
632 QuotaOK(struct rx_service *aservice)
634 /* check if over max quota */
635 if (aservice->nRequestsRunning >= aservice->maxProcs) {
639 /* under min quota, we're OK */
640 /* otherwise, can use only if there are enough to allow everyone
641 * to go to their min quota after this guy starts.
644 MUTEX_ENTER(&rx_quota_mutex);
645 if ((aservice->nRequestsRunning < aservice->minProcs)
646 || (rxi_availProcs > rxi_minDeficit)) {
647 aservice->nRequestsRunning++;
648 /* just started call in minProcs pool, need fewer to maintain
650 if (aservice->nRequestsRunning <= aservice->minProcs)
653 MUTEX_EXIT(&rx_quota_mutex);
656 MUTEX_EXIT(&rx_quota_mutex);
662 ReturnToServerPool(struct rx_service *aservice)
664 aservice->nRequestsRunning--;
665 MUTEX_ENTER(&rx_quota_mutex);
666 if (aservice->nRequestsRunning < aservice->minProcs)
669 MUTEX_EXIT(&rx_quota_mutex);
672 #else /* RX_ENABLE_LOCKS */
674 QuotaOK(struct rx_service *aservice)
677 /* under min quota, we're OK */
678 if (aservice->nRequestsRunning < aservice->minProcs)
681 /* check if over max quota */
682 if (aservice->nRequestsRunning >= aservice->maxProcs)
685 /* otherwise, can use only if there are enough to allow everyone
686 * to go to their min quota after this guy starts.
688 MUTEX_ENTER(&rx_quota_mutex);
689 if (rxi_availProcs > rxi_minDeficit)
691 MUTEX_EXIT(&rx_quota_mutex);
694 #endif /* RX_ENABLE_LOCKS */
697 /* Called by rx_StartServer to start up lwp's to service calls.
698 NExistingProcs gives the number of procs already existing, and which
699 therefore needn't be created. */
701 rxi_StartServerProcs(int nExistingProcs)
703 struct rx_service *service;
708 /* For each service, reserve N processes, where N is the "minimum"
709 * number of processes that MUST be able to execute a request in parallel,
710 * at any time, for that process. Also compute the maximum difference
711 * between any service's maximum number of processes that can run
712 * (i.e. the maximum number that ever will be run, and a guarantee
713 * that this number will run if other services aren't running), and its
714 * minimum number. The result is the extra number of processes that
715 * we need in order to provide the latter guarantee */
716 for (i = 0; i < RX_MAX_SERVICES; i++) {
718 service = rx_services[i];
719 if (service == (struct rx_service *)0)
721 nProcs += service->minProcs;
722 diff = service->maxProcs - service->minProcs;
726 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
727 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
728 for (i = 0; i < nProcs; i++) {
729 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
735 /* This routine is only required on Windows */
737 rx_StartClientThread(void)
739 #ifdef AFS_PTHREAD_ENV
741 pid = pthread_self();
742 #endif /* AFS_PTHREAD_ENV */
744 #endif /* AFS_NT40_ENV */
746 /* This routine must be called if any services are exported. If the
747 * donateMe flag is set, the calling process is donated to the server
750 rx_StartServer(int donateMe)
752 struct rx_service *service;
758 /* Start server processes, if necessary (exact function is dependent
759 * on the implementation environment--kernel or user space). DonateMe
760 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
761 * case, one less new proc will be created rx_StartServerProcs.
763 rxi_StartServerProcs(donateMe);
765 /* count up the # of threads in minProcs, and add set the min deficit to
766 * be that value, too.
768 for (i = 0; i < RX_MAX_SERVICES; i++) {
769 service = rx_services[i];
770 if (service == (struct rx_service *)0)
772 MUTEX_ENTER(&rx_quota_mutex);
773 rxi_totalMin += service->minProcs;
774 /* below works even if a thread is running, since minDeficit would
775 * still have been decremented and later re-incremented.
777 rxi_minDeficit += service->minProcs;
778 MUTEX_EXIT(&rx_quota_mutex);
781 /* Turn on reaping of idle server connections */
782 rxi_ReapConnections(NULL, NULL, NULL);
791 #ifdef AFS_PTHREAD_ENV
793 pid = afs_pointer_to_int(pthread_self());
794 #else /* AFS_PTHREAD_ENV */
796 LWP_CurrentProcess(&pid);
797 #endif /* AFS_PTHREAD_ENV */
799 sprintf(name, "srv_%d", ++nProcs);
801 (*registerProgram) (pid, name);
803 #endif /* AFS_NT40_ENV */
804 rx_ServerProc(NULL); /* Never returns */
806 #ifdef RX_ENABLE_TSFPQ
807 /* no use leaving packets around in this thread's local queue if
808 * it isn't getting donated to the server thread pool.
810 rxi_FlushLocalPacketsTSFPQ();
811 #endif /* RX_ENABLE_TSFPQ */
815 /* Create a new client connection to the specified service, using the
816 * specified security object to implement the security model for this
818 struct rx_connection *
819 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
820 struct rx_securityClass *securityObject,
821 int serviceSecurityIndex)
825 struct rx_connection *conn;
830 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
831 "serviceSecurityIndex %d)\n",
832 ntohl(shost), ntohs(sport), sservice, securityObject,
833 serviceSecurityIndex));
835 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
836 * the case of kmem_alloc? */
837 conn = rxi_AllocConnection();
838 #ifdef RX_ENABLE_LOCKS
839 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
840 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
841 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
844 MUTEX_ENTER(&rx_connHashTable_lock);
845 cid = (rx_nextCid += RX_MAXCALLS);
846 conn->type = RX_CLIENT_CONNECTION;
848 conn->epoch = rx_epoch;
849 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
850 conn->serviceId = sservice;
851 conn->securityObject = securityObject;
852 conn->securityData = (void *) 0;
853 conn->securityIndex = serviceSecurityIndex;
854 rx_SetConnDeadTime(conn, rx_connDeadTime);
855 rx_SetConnSecondsUntilNatPing(conn, 0);
856 conn->ackRate = RX_FAST_ACK_RATE;
858 conn->specific = NULL;
859 conn->challengeEvent = NULL;
860 conn->delayedAbortEvent = NULL;
861 conn->abortCount = 0;
863 for (i = 0; i < RX_MAXCALLS; i++) {
864 conn->twind[i] = rx_initSendWindow;
865 conn->rwind[i] = rx_initReceiveWindow;
868 RXS_NewConnection(securityObject, conn);
870 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
872 conn->refCount++; /* no lock required since only this thread knows... */
873 conn->next = rx_connHashTable[hashindex];
874 rx_connHashTable[hashindex] = conn;
876 rx_atomic_inc(&rx_stats.nClientConns);
877 MUTEX_EXIT(&rx_connHashTable_lock);
883 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
885 /* The idea is to set the dead time to a value that allows several
886 * keepalives to be dropped without timing out the connection. */
887 conn->secondsUntilDead = MAX(seconds, 6);
888 conn->secondsUntilPing = conn->secondsUntilDead / 6;
891 int rxi_lowPeerRefCount = 0;
892 int rxi_lowConnRefCount = 0;
895 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
896 * NOTE: must not be called with rx_connHashTable_lock held.
899 rxi_CleanupConnection(struct rx_connection *conn)
901 /* Notify the service exporter, if requested, that this connection
902 * is being destroyed */
903 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
904 (*conn->service->destroyConnProc) (conn);
906 /* Notify the security module that this connection is being destroyed */
907 RXS_DestroyConnection(conn->securityObject, conn);
909 /* If this is the last connection using the rx_peer struct, set its
910 * idle time to now. rxi_ReapConnections will reap it if it's still
911 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
913 MUTEX_ENTER(&rx_peerHashTable_lock);
914 if (conn->peer->refCount < 2) {
915 conn->peer->idleWhen = clock_Sec();
916 if (conn->peer->refCount < 1) {
917 conn->peer->refCount = 1;
918 if (rx_stats_active) {
919 MUTEX_ENTER(&rx_stats_mutex);
920 rxi_lowPeerRefCount++;
921 MUTEX_EXIT(&rx_stats_mutex);
925 conn->peer->refCount--;
926 MUTEX_EXIT(&rx_peerHashTable_lock);
930 if (conn->type == RX_SERVER_CONNECTION)
931 rx_atomic_dec(&rx_stats.nServerConns);
933 rx_atomic_dec(&rx_stats.nClientConns);
936 if (conn->specific) {
938 for (i = 0; i < conn->nSpecific; i++) {
939 if (conn->specific[i] && rxi_keyCreate_destructor[i])
940 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
941 conn->specific[i] = NULL;
943 free(conn->specific);
945 conn->specific = NULL;
949 MUTEX_DESTROY(&conn->conn_call_lock);
950 MUTEX_DESTROY(&conn->conn_data_lock);
951 CV_DESTROY(&conn->conn_call_cv);
953 rxi_FreeConnection(conn);
956 /* Destroy the specified connection */
958 rxi_DestroyConnection(struct rx_connection *conn)
960 MUTEX_ENTER(&rx_connHashTable_lock);
961 rxi_DestroyConnectionNoLock(conn);
962 /* conn should be at the head of the cleanup list */
963 if (conn == rx_connCleanup_list) {
964 rx_connCleanup_list = rx_connCleanup_list->next;
965 MUTEX_EXIT(&rx_connHashTable_lock);
966 rxi_CleanupConnection(conn);
968 #ifdef RX_ENABLE_LOCKS
970 MUTEX_EXIT(&rx_connHashTable_lock);
972 #endif /* RX_ENABLE_LOCKS */
976 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
978 struct rx_connection **conn_ptr;
980 struct rx_packet *packet;
987 MUTEX_ENTER(&conn->conn_data_lock);
988 MUTEX_ENTER(&rx_refcnt_mutex);
989 if (conn->refCount > 0)
992 if (rx_stats_active) {
993 MUTEX_ENTER(&rx_stats_mutex);
994 rxi_lowConnRefCount++;
995 MUTEX_EXIT(&rx_stats_mutex);
999 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1000 /* Busy; wait till the last guy before proceeding */
1001 MUTEX_EXIT(&rx_refcnt_mutex);
1002 MUTEX_EXIT(&conn->conn_data_lock);
1007 /* If the client previously called rx_NewCall, but it is still
1008 * waiting, treat this as a running call, and wait to destroy the
1009 * connection later when the call completes. */
1010 if ((conn->type == RX_CLIENT_CONNECTION)
1011 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1012 conn->flags |= RX_CONN_DESTROY_ME;
1013 MUTEX_EXIT(&conn->conn_data_lock);
1017 MUTEX_EXIT(&rx_refcnt_mutex);
1018 MUTEX_EXIT(&conn->conn_data_lock);
1020 /* Check for extant references to this connection */
1021 for (i = 0; i < RX_MAXCALLS; i++) {
1022 struct rx_call *call = conn->call[i];
1025 if (conn->type == RX_CLIENT_CONNECTION) {
1026 MUTEX_ENTER(&call->lock);
1027 if (call->delayedAckEvent) {
1028 /* Push the final acknowledgment out now--there
1029 * won't be a subsequent call to acknowledge the
1030 * last reply packets */
1031 rxevent_Cancel(call->delayedAckEvent, call,
1032 RX_CALL_REFCOUNT_DELAY);
1033 if (call->state == RX_STATE_PRECALL
1034 || call->state == RX_STATE_ACTIVE) {
1035 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1037 rxi_AckAll(NULL, call, 0);
1040 MUTEX_EXIT(&call->lock);
1044 #ifdef RX_ENABLE_LOCKS
1046 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1047 MUTEX_EXIT(&conn->conn_data_lock);
1049 /* Someone is accessing a packet right now. */
1053 #endif /* RX_ENABLE_LOCKS */
1056 /* Don't destroy the connection if there are any call
1057 * structures still in use */
1058 MUTEX_ENTER(&conn->conn_data_lock);
1059 conn->flags |= RX_CONN_DESTROY_ME;
1060 MUTEX_EXIT(&conn->conn_data_lock);
1065 if (conn->natKeepAliveEvent) {
1066 rxi_NatKeepAliveOff(conn);
1069 if (conn->delayedAbortEvent) {
1070 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1071 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1073 MUTEX_ENTER(&conn->conn_data_lock);
1074 rxi_SendConnectionAbort(conn, packet, 0, 1);
1075 MUTEX_EXIT(&conn->conn_data_lock);
1076 rxi_FreePacket(packet);
1080 /* Remove from connection hash table before proceeding */
1082 &rx_connHashTable[CONN_HASH
1083 (peer->host, peer->port, conn->cid, conn->epoch,
1085 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1086 if (*conn_ptr == conn) {
1087 *conn_ptr = conn->next;
1091 /* if the conn that we are destroying was the last connection, then we
1092 * clear rxLastConn as well */
1093 if (rxLastConn == conn)
1096 /* Make sure the connection is completely reset before deleting it. */
1097 /* get rid of pending events that could zap us later */
1098 if (conn->challengeEvent)
1099 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1100 if (conn->checkReachEvent)
1101 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1102 if (conn->natKeepAliveEvent)
1103 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1105 /* Add the connection to the list of destroyed connections that
1106 * need to be cleaned up. This is necessary to avoid deadlocks
1107 * in the routines we call to inform others that this connection is
1108 * being destroyed. */
1109 conn->next = rx_connCleanup_list;
1110 rx_connCleanup_list = conn;
1113 /* Externally available version */
1115 rx_DestroyConnection(struct rx_connection *conn)
1120 rxi_DestroyConnection(conn);
1125 rx_GetConnection(struct rx_connection *conn)
1130 MUTEX_ENTER(&rx_refcnt_mutex);
1132 MUTEX_EXIT(&rx_refcnt_mutex);
1136 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1137 /* Wait for the transmit queue to no longer be busy.
1138 * requires the call->lock to be held */
1139 static void rxi_WaitforTQBusy(struct rx_call *call) {
1140 while (call->flags & RX_CALL_TQ_BUSY) {
1141 call->flags |= RX_CALL_TQ_WAIT;
1143 #ifdef RX_ENABLE_LOCKS
1144 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1145 CV_WAIT(&call->cv_tq, &call->lock);
1146 #else /* RX_ENABLE_LOCKS */
1147 osi_rxSleep(&call->tq);
1148 #endif /* RX_ENABLE_LOCKS */
1150 if (call->tqWaiters == 0) {
1151 call->flags &= ~RX_CALL_TQ_WAIT;
1157 /* Start a new rx remote procedure call, on the specified connection.
1158 * If wait is set to 1, wait for a free call channel; otherwise return
1159 * 0. Maxtime gives the maximum number of seconds this call may take,
1160 * after rx_NewCall returns. After this time interval, a call to any
1161 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1162 * For fine grain locking, we hold the conn_call_lock in order to
1163 * to ensure that we don't get signalle after we found a call in an active
1164 * state and before we go to sleep.
1167 rx_NewCall(struct rx_connection *conn)
1170 struct rx_call *call;
1171 struct clock queueTime;
1175 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1178 clock_GetTime(&queueTime);
1180 * Check if there are others waiting for a new call.
1181 * If so, let them go first to avoid starving them.
1182 * This is a fairly simple scheme, and might not be
1183 * a complete solution for large numbers of waiters.
1185 * makeCallWaiters keeps track of the number of
1186 * threads waiting to make calls and the
1187 * RX_CONN_MAKECALL_WAITING flag bit is used to
1188 * indicate that there are indeed calls waiting.
1189 * The flag is set when the waiter is incremented.
1190 * It is only cleared when makeCallWaiters is 0.
1191 * This prevents us from accidently destroying the
1192 * connection while it is potentially about to be used.
1194 MUTEX_ENTER(&conn->conn_call_lock);
1195 MUTEX_ENTER(&conn->conn_data_lock);
1196 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1197 conn->flags |= RX_CONN_MAKECALL_WAITING;
1198 conn->makeCallWaiters++;
1199 MUTEX_EXIT(&conn->conn_data_lock);
1201 #ifdef RX_ENABLE_LOCKS
1202 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1206 MUTEX_ENTER(&conn->conn_data_lock);
1207 conn->makeCallWaiters--;
1208 if (conn->makeCallWaiters == 0)
1209 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1212 /* We are now the active thread in rx_NewCall */
1213 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1214 MUTEX_EXIT(&conn->conn_data_lock);
1219 for (i = 0; i < RX_MAXCALLS; i++) {
1220 call = conn->call[i];
1222 if (call->state == RX_STATE_DALLY) {
1223 MUTEX_ENTER(&call->lock);
1224 if (call->state == RX_STATE_DALLY) {
1226 * We are setting the state to RX_STATE_RESET to
1227 * ensure that no one else will attempt to use this
1228 * call once we drop the conn->conn_call_lock and
1229 * call->lock. We must drop the conn->conn_call_lock
1230 * before calling rxi_ResetCall because the process
1231 * of clearing the transmit queue can block for an
1232 * extended period of time. If we block while holding
1233 * the conn->conn_call_lock, then all rx_EndCall
1234 * processing will block as well. This has a detrimental
1235 * effect on overall system performance.
1237 call->state = RX_STATE_RESET;
1238 MUTEX_EXIT(&conn->conn_call_lock);
1239 MUTEX_ENTER(&rx_refcnt_mutex);
1240 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1241 MUTEX_EXIT(&rx_refcnt_mutex);
1242 rxi_ResetCall(call, 0);
1243 (*call->callNumber)++;
1244 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1248 * If we failed to be able to safely obtain the
1249 * conn->conn_call_lock we will have to drop the
1250 * call->lock to avoid a deadlock. When the call->lock
1251 * is released the state of the call can change. If it
1252 * is no longer RX_STATE_RESET then some other thread is
1255 MUTEX_EXIT(&call->lock);
1256 MUTEX_ENTER(&conn->conn_call_lock);
1257 MUTEX_ENTER(&call->lock);
1259 if (call->state == RX_STATE_RESET)
1263 * If we get here it means that after dropping
1264 * the conn->conn_call_lock and call->lock that
1265 * the call is no longer ours. If we can't find
1266 * a free call in the remaining slots we should
1267 * not go immediately to RX_CONN_MAKECALL_WAITING
1268 * because by dropping the conn->conn_call_lock
1269 * we have given up synchronization with rx_EndCall.
1270 * Instead, cycle through one more time to see if
1271 * we can find a call that can call our own.
1273 MUTEX_ENTER(&rx_refcnt_mutex);
1274 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1275 MUTEX_EXIT(&rx_refcnt_mutex);
1278 MUTEX_EXIT(&call->lock);
1281 /* rxi_NewCall returns with mutex locked */
1282 call = rxi_NewCall(conn, i);
1283 MUTEX_ENTER(&rx_refcnt_mutex);
1284 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1285 MUTEX_EXIT(&rx_refcnt_mutex);
1289 if (i < RX_MAXCALLS) {
1295 MUTEX_ENTER(&conn->conn_data_lock);
1296 conn->flags |= RX_CONN_MAKECALL_WAITING;
1297 conn->makeCallWaiters++;
1298 MUTEX_EXIT(&conn->conn_data_lock);
1300 #ifdef RX_ENABLE_LOCKS
1301 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1305 MUTEX_ENTER(&conn->conn_data_lock);
1306 conn->makeCallWaiters--;
1307 if (conn->makeCallWaiters == 0)
1308 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1309 MUTEX_EXIT(&conn->conn_data_lock);
1311 /* Client is initially in send mode */
1312 call->state = RX_STATE_ACTIVE;
1313 call->error = conn->error;
1315 call->mode = RX_MODE_ERROR;
1317 call->mode = RX_MODE_SENDING;
1319 /* remember start time for call in case we have hard dead time limit */
1320 call->queueTime = queueTime;
1321 clock_GetTime(&call->startTime);
1322 hzero(call->bytesSent);
1323 hzero(call->bytesRcvd);
1325 /* Turn on busy protocol. */
1326 rxi_KeepAliveOn(call);
1328 /* Attempt MTU discovery */
1329 rxi_GrowMTUOn(call);
1332 * We are no longer the active thread in rx_NewCall
1334 MUTEX_ENTER(&conn->conn_data_lock);
1335 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1336 MUTEX_EXIT(&conn->conn_data_lock);
1339 * Wake up anyone else who might be giving us a chance to
1340 * run (see code above that avoids resource starvation).
1342 #ifdef RX_ENABLE_LOCKS
1343 CV_BROADCAST(&conn->conn_call_cv);
1347 MUTEX_EXIT(&conn->conn_call_lock);
1349 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1350 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1351 osi_Panic("rx_NewCall call about to be used without an empty tq");
1353 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1355 MUTEX_EXIT(&call->lock);
1358 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1363 rxi_HasActiveCalls(struct rx_connection *aconn)
1366 struct rx_call *tcall;
1370 for (i = 0; i < RX_MAXCALLS; i++) {
1371 if ((tcall = aconn->call[i])) {
1372 if ((tcall->state == RX_STATE_ACTIVE)
1373 || (tcall->state == RX_STATE_PRECALL)) {
1384 rxi_GetCallNumberVector(struct rx_connection *aconn,
1385 afs_int32 * aint32s)
1388 struct rx_call *tcall;
1392 for (i = 0; i < RX_MAXCALLS; i++) {
1393 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1394 aint32s[i] = aconn->callNumber[i] + 1;
1396 aint32s[i] = aconn->callNumber[i];
1403 rxi_SetCallNumberVector(struct rx_connection *aconn,
1404 afs_int32 * aint32s)
1407 struct rx_call *tcall;
1411 for (i = 0; i < RX_MAXCALLS; i++) {
1412 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1413 aconn->callNumber[i] = aint32s[i] - 1;
1415 aconn->callNumber[i] = aint32s[i];
1421 /* Advertise a new service. A service is named locally by a UDP port
1422 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1425 char *serviceName; Name for identification purposes (e.g. the
1426 service name might be used for probing for
1429 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1430 char *serviceName, struct rx_securityClass **securityObjects,
1431 int nSecurityObjects,
1432 afs_int32(*serviceProc) (struct rx_call * acall))
1434 osi_socket socket = OSI_NULLSOCKET;
1435 struct rx_service *tservice;
1441 if (serviceId == 0) {
1443 "rx_NewService: service id for service %s is not non-zero.\n",
1450 "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",
1458 tservice = rxi_AllocService();
1461 #ifdef RX_ENABLE_LOCKS
1462 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1465 for (i = 0; i < RX_MAX_SERVICES; i++) {
1466 struct rx_service *service = rx_services[i];
1468 if (port == service->servicePort && host == service->serviceHost) {
1469 if (service->serviceId == serviceId) {
1470 /* The identical service has already been
1471 * installed; if the caller was intending to
1472 * change the security classes used by this
1473 * service, he/she loses. */
1475 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1476 serviceName, serviceId, service->serviceName);
1478 rxi_FreeService(tservice);
1481 /* Different service, same port: re-use the socket
1482 * which is bound to the same port */
1483 socket = service->socket;
1486 if (socket == OSI_NULLSOCKET) {
1487 /* If we don't already have a socket (from another
1488 * service on same port) get a new one */
1489 socket = rxi_GetHostUDPSocket(host, port);
1490 if (socket == OSI_NULLSOCKET) {
1492 rxi_FreeService(tservice);
1497 service->socket = socket;
1498 service->serviceHost = host;
1499 service->servicePort = port;
1500 service->serviceId = serviceId;
1501 service->serviceName = serviceName;
1502 service->nSecurityObjects = nSecurityObjects;
1503 service->securityObjects = securityObjects;
1504 service->minProcs = 0;
1505 service->maxProcs = 1;
1506 service->idleDeadTime = 60;
1507 service->idleDeadErr = 0;
1508 service->connDeadTime = rx_connDeadTime;
1509 service->executeRequestProc = serviceProc;
1510 service->checkReach = 0;
1511 service->nSpecific = 0;
1512 service->specific = NULL;
1513 rx_services[i] = service; /* not visible until now */
1519 rxi_FreeService(tservice);
1520 (osi_Msg "rx_NewService: cannot support > %d services\n",
1525 /* Set configuration options for all of a service's security objects */
1528 rx_SetSecurityConfiguration(struct rx_service *service,
1529 rx_securityConfigVariables type,
1533 for (i = 0; i<service->nSecurityObjects; i++) {
1534 if (service->securityObjects[i]) {
1535 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1543 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1544 struct rx_securityClass **securityObjects, int nSecurityObjects,
1545 afs_int32(*serviceProc) (struct rx_call * acall))
1547 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1550 /* Generic request processing loop. This routine should be called
1551 * by the implementation dependent rx_ServerProc. If socketp is
1552 * non-null, it will be set to the file descriptor that this thread
1553 * is now listening on. If socketp is null, this routine will never
1556 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1558 struct rx_call *call;
1560 struct rx_service *tservice = NULL;
1567 call = rx_GetCall(threadID, tservice, socketp);
1568 if (socketp && *socketp != OSI_NULLSOCKET) {
1569 /* We are now a listener thread */
1574 /* if server is restarting( typically smooth shutdown) then do not
1575 * allow any new calls.
1578 if (rx_tranquil && (call != NULL)) {
1582 MUTEX_ENTER(&call->lock);
1584 rxi_CallError(call, RX_RESTARTING);
1585 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1587 MUTEX_EXIT(&call->lock);
1591 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1592 #ifdef RX_ENABLE_LOCKS
1594 #endif /* RX_ENABLE_LOCKS */
1595 afs_termState = AFSOP_STOP_AFS;
1596 afs_osi_Wakeup(&afs_termState);
1597 #ifdef RX_ENABLE_LOCKS
1599 #endif /* RX_ENABLE_LOCKS */
1604 tservice = call->conn->service;
1606 if (tservice->beforeProc)
1607 (*tservice->beforeProc) (call);
1609 code = tservice->executeRequestProc(call);
1611 if (tservice->afterProc)
1612 (*tservice->afterProc) (call, code);
1614 rx_EndCall(call, code);
1615 if (rx_stats_active) {
1616 MUTEX_ENTER(&rx_stats_mutex);
1618 MUTEX_EXIT(&rx_stats_mutex);
1625 rx_WakeupServerProcs(void)
1627 struct rx_serverQueueEntry *np, *tqp;
1631 MUTEX_ENTER(&rx_serverPool_lock);
1633 #ifdef RX_ENABLE_LOCKS
1634 if (rx_waitForPacket)
1635 CV_BROADCAST(&rx_waitForPacket->cv);
1636 #else /* RX_ENABLE_LOCKS */
1637 if (rx_waitForPacket)
1638 osi_rxWakeup(rx_waitForPacket);
1639 #endif /* RX_ENABLE_LOCKS */
1640 MUTEX_ENTER(&freeSQEList_lock);
1641 for (np = rx_FreeSQEList; np; np = tqp) {
1642 tqp = *(struct rx_serverQueueEntry **)np;
1643 #ifdef RX_ENABLE_LOCKS
1644 CV_BROADCAST(&np->cv);
1645 #else /* RX_ENABLE_LOCKS */
1647 #endif /* RX_ENABLE_LOCKS */
1649 MUTEX_EXIT(&freeSQEList_lock);
1650 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1651 #ifdef RX_ENABLE_LOCKS
1652 CV_BROADCAST(&np->cv);
1653 #else /* RX_ENABLE_LOCKS */
1655 #endif /* RX_ENABLE_LOCKS */
1657 MUTEX_EXIT(&rx_serverPool_lock);
1662 * One thing that seems to happen is that all the server threads get
1663 * tied up on some empty or slow call, and then a whole bunch of calls
1664 * arrive at once, using up the packet pool, so now there are more
1665 * empty calls. The most critical resources here are server threads
1666 * and the free packet pool. The "doreclaim" code seems to help in
1667 * general. I think that eventually we arrive in this state: there
1668 * are lots of pending calls which do have all their packets present,
1669 * so they won't be reclaimed, are multi-packet calls, so they won't
1670 * be scheduled until later, and thus are tying up most of the free
1671 * packet pool for a very long time.
1673 * 1. schedule multi-packet calls if all the packets are present.
1674 * Probably CPU-bound operation, useful to return packets to pool.
1675 * Do what if there is a full window, but the last packet isn't here?
1676 * 3. preserve one thread which *only* runs "best" calls, otherwise
1677 * it sleeps and waits for that type of call.
1678 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1679 * the current dataquota business is badly broken. The quota isn't adjusted
1680 * to reflect how many packets are presently queued for a running call.
1681 * So, when we schedule a queued call with a full window of packets queued
1682 * up for it, that *should* free up a window full of packets for other 2d-class
1683 * calls to be able to use from the packet pool. But it doesn't.
1685 * NB. Most of the time, this code doesn't run -- since idle server threads
1686 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1687 * as a new call arrives.
1689 /* Sleep until a call arrives. Returns a pointer to the call, ready
1690 * for an rx_Read. */
1691 #ifdef RX_ENABLE_LOCKS
1693 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1695 struct rx_serverQueueEntry *sq;
1696 struct rx_call *call = (struct rx_call *)0;
1697 struct rx_service *service = NULL;
1700 MUTEX_ENTER(&freeSQEList_lock);
1702 if ((sq = rx_FreeSQEList)) {
1703 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1704 MUTEX_EXIT(&freeSQEList_lock);
1705 } else { /* otherwise allocate a new one and return that */
1706 MUTEX_EXIT(&freeSQEList_lock);
1707 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1708 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1709 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1712 MUTEX_ENTER(&rx_serverPool_lock);
1713 if (cur_service != NULL) {
1714 ReturnToServerPool(cur_service);
1717 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1718 struct rx_call *tcall, *ncall, *choice2 = NULL;
1720 /* Scan for eligible incoming calls. A call is not eligible
1721 * if the maximum number of calls for its service type are
1722 * already executing */
1723 /* One thread will process calls FCFS (to prevent starvation),
1724 * while the other threads may run ahead looking for calls which
1725 * have all their input data available immediately. This helps
1726 * keep threads from blocking, waiting for data from the client. */
1727 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1728 service = tcall->conn->service;
1729 if (!QuotaOK(service)) {
1732 MUTEX_ENTER(&rx_pthread_mutex);
1733 if (tno == rxi_fcfs_thread_num
1734 || !tcall->queue_item_header.next) {
1735 MUTEX_EXIT(&rx_pthread_mutex);
1736 /* If we're the fcfs thread , then we'll just use
1737 * this call. If we haven't been able to find an optimal
1738 * choice, and we're at the end of the list, then use a
1739 * 2d choice if one has been identified. Otherwise... */
1740 call = (choice2 ? choice2 : tcall);
1741 service = call->conn->service;
1743 MUTEX_EXIT(&rx_pthread_mutex);
1744 if (!queue_IsEmpty(&tcall->rq)) {
1745 struct rx_packet *rp;
1746 rp = queue_First(&tcall->rq, rx_packet);
1747 if (rp->header.seq == 1) {
1749 || (rp->header.flags & RX_LAST_PACKET)) {
1751 } else if (rxi_2dchoice && !choice2
1752 && !(tcall->flags & RX_CALL_CLEARED)
1753 && (tcall->rprev > rxi_HardAckRate)) {
1763 ReturnToServerPool(service);
1770 MUTEX_EXIT(&rx_serverPool_lock);
1771 MUTEX_ENTER(&call->lock);
1773 if (call->flags & RX_CALL_WAIT_PROC) {
1774 call->flags &= ~RX_CALL_WAIT_PROC;
1775 rx_atomic_dec(&rx_nWaiting);
1778 if (call->state != RX_STATE_PRECALL || call->error) {
1779 MUTEX_EXIT(&call->lock);
1780 MUTEX_ENTER(&rx_serverPool_lock);
1781 ReturnToServerPool(service);
1786 if (queue_IsEmpty(&call->rq)
1787 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1788 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1790 CLEAR_CALL_QUEUE_LOCK(call);
1793 /* If there are no eligible incoming calls, add this process
1794 * to the idle server queue, to wait for one */
1798 *socketp = OSI_NULLSOCKET;
1800 sq->socketp = socketp;
1801 queue_Append(&rx_idleServerQueue, sq);
1802 #ifndef AFS_AIX41_ENV
1803 rx_waitForPacket = sq;
1805 rx_waitingForPacket = sq;
1806 #endif /* AFS_AIX41_ENV */
1808 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1810 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1811 MUTEX_EXIT(&rx_serverPool_lock);
1812 return (struct rx_call *)0;
1815 } while (!(call = sq->newcall)
1816 && !(socketp && *socketp != OSI_NULLSOCKET));
1817 MUTEX_EXIT(&rx_serverPool_lock);
1819 MUTEX_ENTER(&call->lock);
1825 MUTEX_ENTER(&freeSQEList_lock);
1826 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1827 rx_FreeSQEList = sq;
1828 MUTEX_EXIT(&freeSQEList_lock);
1831 clock_GetTime(&call->startTime);
1832 call->state = RX_STATE_ACTIVE;
1833 call->mode = RX_MODE_RECEIVING;
1834 #ifdef RX_KERNEL_TRACE
1835 if (ICL_SETACTIVE(afs_iclSetp)) {
1836 int glockOwner = ISAFS_GLOCK();
1839 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1840 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1847 rxi_calltrace(RX_CALL_START, call);
1848 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1849 call->conn->service->servicePort, call->conn->service->serviceId,
1852 MUTEX_EXIT(&call->lock);
1853 MUTEX_ENTER(&rx_refcnt_mutex);
1854 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1855 MUTEX_EXIT(&rx_refcnt_mutex);
1857 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1862 #else /* RX_ENABLE_LOCKS */
1864 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1866 struct rx_serverQueueEntry *sq;
1867 struct rx_call *call = (struct rx_call *)0, *choice2;
1868 struct rx_service *service = NULL;
1872 MUTEX_ENTER(&freeSQEList_lock);
1874 if ((sq = rx_FreeSQEList)) {
1875 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1876 MUTEX_EXIT(&freeSQEList_lock);
1877 } else { /* otherwise allocate a new one and return that */
1878 MUTEX_EXIT(&freeSQEList_lock);
1879 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1880 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1881 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1883 MUTEX_ENTER(&sq->lock);
1885 if (cur_service != NULL) {
1886 cur_service->nRequestsRunning--;
1887 MUTEX_ENTER(&rx_quota_mutex);
1888 if (cur_service->nRequestsRunning < cur_service->minProcs)
1891 MUTEX_EXIT(&rx_quota_mutex);
1893 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1894 struct rx_call *tcall, *ncall;
1895 /* Scan for eligible incoming calls. A call is not eligible
1896 * if the maximum number of calls for its service type are
1897 * already executing */
1898 /* One thread will process calls FCFS (to prevent starvation),
1899 * while the other threads may run ahead looking for calls which
1900 * have all their input data available immediately. This helps
1901 * keep threads from blocking, waiting for data from the client. */
1902 choice2 = (struct rx_call *)0;
1903 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1904 service = tcall->conn->service;
1905 if (QuotaOK(service)) {
1906 MUTEX_ENTER(&rx_pthread_mutex);
1907 if (tno == rxi_fcfs_thread_num
1908 || !tcall->queue_item_header.next) {
1909 MUTEX_EXIT(&rx_pthread_mutex);
1910 /* If we're the fcfs thread, then we'll just use
1911 * this call. If we haven't been able to find an optimal
1912 * choice, and we're at the end of the list, then use a
1913 * 2d choice if one has been identified. Otherwise... */
1914 call = (choice2 ? choice2 : tcall);
1915 service = call->conn->service;
1917 MUTEX_EXIT(&rx_pthread_mutex);
1918 if (!queue_IsEmpty(&tcall->rq)) {
1919 struct rx_packet *rp;
1920 rp = queue_First(&tcall->rq, rx_packet);
1921 if (rp->header.seq == 1
1923 || (rp->header.flags & RX_LAST_PACKET))) {
1925 } else if (rxi_2dchoice && !choice2
1926 && !(tcall->flags & RX_CALL_CLEARED)
1927 && (tcall->rprev > rxi_HardAckRate)) {
1941 /* we can't schedule a call if there's no data!!! */
1942 /* send an ack if there's no data, if we're missing the
1943 * first packet, or we're missing something between first
1944 * and last -- there's a "hole" in the incoming data. */
1945 if (queue_IsEmpty(&call->rq)
1946 || queue_First(&call->rq, rx_packet)->header.seq != 1
1947 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1948 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1950 call->flags &= (~RX_CALL_WAIT_PROC);
1951 service->nRequestsRunning++;
1952 /* just started call in minProcs pool, need fewer to maintain
1954 MUTEX_ENTER(&rx_quota_mutex);
1955 if (service->nRequestsRunning <= service->minProcs)
1958 MUTEX_EXIT(&rx_quota_mutex);
1959 rx_atomic_dec(&rx_nWaiting);
1960 /* MUTEX_EXIT(&call->lock); */
1962 /* If there are no eligible incoming calls, add this process
1963 * to the idle server queue, to wait for one */
1966 *socketp = OSI_NULLSOCKET;
1968 sq->socketp = socketp;
1969 queue_Append(&rx_idleServerQueue, sq);
1973 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1975 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1976 return (struct rx_call *)0;
1979 } while (!(call = sq->newcall)
1980 && !(socketp && *socketp != OSI_NULLSOCKET));
1982 MUTEX_EXIT(&sq->lock);
1984 MUTEX_ENTER(&freeSQEList_lock);
1985 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1986 rx_FreeSQEList = sq;
1987 MUTEX_EXIT(&freeSQEList_lock);
1990 clock_GetTime(&call->startTime);
1991 call->state = RX_STATE_ACTIVE;
1992 call->mode = RX_MODE_RECEIVING;
1993 #ifdef RX_KERNEL_TRACE
1994 if (ICL_SETACTIVE(afs_iclSetp)) {
1995 int glockOwner = ISAFS_GLOCK();
1998 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1999 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2006 rxi_calltrace(RX_CALL_START, call);
2007 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2008 call->conn->service->servicePort, call->conn->service->serviceId,
2011 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2018 #endif /* RX_ENABLE_LOCKS */
2022 /* Establish a procedure to be called when a packet arrives for a
2023 * call. This routine will be called at most once after each call,
2024 * and will also be called if there is an error condition on the or
2025 * the call is complete. Used by multi rx to build a selection
2026 * function which determines which of several calls is likely to be a
2027 * good one to read from.
2028 * NOTE: the way this is currently implemented it is probably only a
2029 * good idea to (1) use it immediately after a newcall (clients only)
2030 * and (2) only use it once. Other uses currently void your warranty
2033 rx_SetArrivalProc(struct rx_call *call,
2034 void (*proc) (struct rx_call * call,
2037 void * handle, int arg)
2039 call->arrivalProc = proc;
2040 call->arrivalProcHandle = handle;
2041 call->arrivalProcArg = arg;
2044 /* Call is finished (possibly prematurely). Return rc to the peer, if
2045 * appropriate, and return the final error code from the conversation
2049 rx_EndCall(struct rx_call *call, afs_int32 rc)
2051 struct rx_connection *conn = call->conn;
2055 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2056 call, rc, call->error, call->abortCode));
2059 MUTEX_ENTER(&call->lock);
2061 if (rc == 0 && call->error == 0) {
2062 call->abortCode = 0;
2063 call->abortCount = 0;
2066 call->arrivalProc = (void (*)())0;
2067 if (rc && call->error == 0) {
2068 rxi_CallError(call, rc);
2069 /* Send an abort message to the peer if this error code has
2070 * only just been set. If it was set previously, assume the
2071 * peer has already been sent the error code or will request it
2073 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2075 if (conn->type == RX_SERVER_CONNECTION) {
2076 /* Make sure reply or at least dummy reply is sent */
2077 if (call->mode == RX_MODE_RECEIVING) {
2078 rxi_WriteProc(call, 0, 0);
2080 if (call->mode == RX_MODE_SENDING) {
2081 rxi_FlushWrite(call);
2083 rxi_calltrace(RX_CALL_END, call);
2084 /* Call goes to hold state until reply packets are acknowledged */
2085 if (call->tfirst + call->nSoftAcked < call->tnext) {
2086 call->state = RX_STATE_HOLD;
2088 call->state = RX_STATE_DALLY;
2089 rxi_ClearTransmitQueue(call, 0);
2090 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2091 rxevent_Cancel(call->keepAliveEvent, call,
2092 RX_CALL_REFCOUNT_ALIVE);
2094 } else { /* Client connection */
2096 /* Make sure server receives input packets, in the case where
2097 * no reply arguments are expected */
2098 if ((call->mode == RX_MODE_SENDING)
2099 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2100 (void)rxi_ReadProc(call, &dummy, 1);
2103 /* If we had an outstanding delayed ack, be nice to the server
2104 * and force-send it now.
2106 if (call->delayedAckEvent) {
2107 rxevent_Cancel(call->delayedAckEvent, call,
2108 RX_CALL_REFCOUNT_DELAY);
2109 call->delayedAckEvent = NULL;
2110 rxi_SendDelayedAck(NULL, call, NULL);
2113 /* We need to release the call lock since it's lower than the
2114 * conn_call_lock and we don't want to hold the conn_call_lock
2115 * over the rx_ReadProc call. The conn_call_lock needs to be held
2116 * here for the case where rx_NewCall is perusing the calls on
2117 * the connection structure. We don't want to signal until
2118 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2119 * have checked this call, found it active and by the time it
2120 * goes to sleep, will have missed the signal.
2122 MUTEX_EXIT(&call->lock);
2123 MUTEX_ENTER(&conn->conn_call_lock);
2124 MUTEX_ENTER(&call->lock);
2125 MUTEX_ENTER(&conn->conn_data_lock);
2126 conn->flags |= RX_CONN_BUSY;
2127 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2128 MUTEX_EXIT(&conn->conn_data_lock);
2129 #ifdef RX_ENABLE_LOCKS
2130 CV_BROADCAST(&conn->conn_call_cv);
2135 #ifdef RX_ENABLE_LOCKS
2137 MUTEX_EXIT(&conn->conn_data_lock);
2139 #endif /* RX_ENABLE_LOCKS */
2140 call->state = RX_STATE_DALLY;
2142 error = call->error;
2144 /* currentPacket, nLeft, and NFree must be zeroed here, because
2145 * ResetCall cannot: ResetCall may be called at splnet(), in the
2146 * kernel version, and may interrupt the macros rx_Read or
2147 * rx_Write, which run at normal priority for efficiency. */
2148 if (call->currentPacket) {
2149 #ifdef RX_TRACK_PACKETS
2150 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2152 rxi_FreePacket(call->currentPacket);
2153 call->currentPacket = (struct rx_packet *)0;
2156 call->nLeft = call->nFree = call->curlen = 0;
2158 /* Free any packets from the last call to ReadvProc/WritevProc */
2159 #ifdef RXDEBUG_PACKET
2161 #endif /* RXDEBUG_PACKET */
2162 rxi_FreePackets(0, &call->iovq);
2163 MUTEX_EXIT(&call->lock);
2165 MUTEX_ENTER(&rx_refcnt_mutex);
2166 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2167 MUTEX_EXIT(&rx_refcnt_mutex);
2168 if (conn->type == RX_CLIENT_CONNECTION) {
2169 MUTEX_ENTER(&conn->conn_data_lock);
2170 conn->flags &= ~RX_CONN_BUSY;
2171 MUTEX_EXIT(&conn->conn_data_lock);
2172 MUTEX_EXIT(&conn->conn_call_lock);
2176 * Map errors to the local host's errno.h format.
2178 error = ntoh_syserr_conv(error);
2182 #if !defined(KERNEL)
2184 /* Call this routine when shutting down a server or client (especially
2185 * clients). This will allow Rx to gracefully garbage collect server
2186 * connections, and reduce the number of retries that a server might
2187 * make to a dead client.
2188 * This is not quite right, since some calls may still be ongoing and
2189 * we can't lock them to destroy them. */
2193 struct rx_connection **conn_ptr, **conn_end;
2197 if (rxinit_status == 1) {
2199 return; /* Already shutdown. */
2201 rxi_DeleteCachedConnections();
2202 if (rx_connHashTable) {
2203 MUTEX_ENTER(&rx_connHashTable_lock);
2204 for (conn_ptr = &rx_connHashTable[0], conn_end =
2205 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2207 struct rx_connection *conn, *next;
2208 for (conn = *conn_ptr; conn; conn = next) {
2210 if (conn->type == RX_CLIENT_CONNECTION) {
2211 MUTEX_ENTER(&rx_refcnt_mutex);
2213 MUTEX_EXIT(&rx_refcnt_mutex);
2214 #ifdef RX_ENABLE_LOCKS
2215 rxi_DestroyConnectionNoLock(conn);
2216 #else /* RX_ENABLE_LOCKS */
2217 rxi_DestroyConnection(conn);
2218 #endif /* RX_ENABLE_LOCKS */
2222 #ifdef RX_ENABLE_LOCKS
2223 while (rx_connCleanup_list) {
2224 struct rx_connection *conn;
2225 conn = rx_connCleanup_list;
2226 rx_connCleanup_list = rx_connCleanup_list->next;
2227 MUTEX_EXIT(&rx_connHashTable_lock);
2228 rxi_CleanupConnection(conn);
2229 MUTEX_ENTER(&rx_connHashTable_lock);
2231 MUTEX_EXIT(&rx_connHashTable_lock);
2232 #endif /* RX_ENABLE_LOCKS */
2237 afs_winsockCleanup();
2245 /* if we wakeup packet waiter too often, can get in loop with two
2246 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2248 rxi_PacketsUnWait(void)
2250 if (!rx_waitingForPackets) {
2254 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2255 return; /* still over quota */
2258 rx_waitingForPackets = 0;
2259 #ifdef RX_ENABLE_LOCKS
2260 CV_BROADCAST(&rx_waitingForPackets_cv);
2262 osi_rxWakeup(&rx_waitingForPackets);
2268 /* ------------------Internal interfaces------------------------- */
2270 /* Return this process's service structure for the
2271 * specified socket and service */
2273 rxi_FindService(osi_socket socket, u_short serviceId)
2275 struct rx_service **sp;
2276 for (sp = &rx_services[0]; *sp; sp++) {
2277 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2283 #ifdef RXDEBUG_PACKET
2284 #ifdef KDUMP_RX_LOCK
2285 static struct rx_call_rx_lock *rx_allCallsp = 0;
2287 static struct rx_call *rx_allCallsp = 0;
2289 #endif /* RXDEBUG_PACKET */
2291 /* Allocate a call structure, for the indicated channel of the
2292 * supplied connection. The mode and state of the call must be set by
2293 * the caller. Returns the call with mutex locked. */
2295 rxi_NewCall(struct rx_connection *conn, int channel)
2297 struct rx_call *call;
2298 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2299 struct rx_call *cp; /* Call pointer temp */
2300 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2301 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2303 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2305 /* Grab an existing call structure, or allocate a new one.
2306 * Existing call structures are assumed to have been left reset by
2308 MUTEX_ENTER(&rx_freeCallQueue_lock);
2310 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2312 * EXCEPT that the TQ might not yet be cleared out.
2313 * Skip over those with in-use TQs.
2316 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2317 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2323 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2324 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2325 call = queue_First(&rx_freeCallQueue, rx_call);
2326 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2328 if (rx_stats_active)
2329 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2330 MUTEX_EXIT(&rx_freeCallQueue_lock);
2331 MUTEX_ENTER(&call->lock);
2332 CLEAR_CALL_QUEUE_LOCK(call);
2333 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2334 /* Now, if TQ wasn't cleared earlier, do it now. */
2335 rxi_WaitforTQBusy(call);
2336 if (call->flags & RX_CALL_TQ_CLEARME) {
2337 rxi_ClearTransmitQueue(call, 1);
2338 /*queue_Init(&call->tq);*/
2340 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2341 /* Bind the call to its connection structure */
2343 rxi_ResetCall(call, 1);
2346 call = rxi_Alloc(sizeof(struct rx_call));
2347 #ifdef RXDEBUG_PACKET
2348 call->allNextp = rx_allCallsp;
2349 rx_allCallsp = call;
2351 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2352 #else /* RXDEBUG_PACKET */
2353 rx_atomic_inc(&rx_stats.nCallStructs);
2354 #endif /* RXDEBUG_PACKET */
2356 MUTEX_EXIT(&rx_freeCallQueue_lock);
2357 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2358 MUTEX_ENTER(&call->lock);
2359 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2360 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2361 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2363 /* Initialize once-only items */
2364 queue_Init(&call->tq);
2365 queue_Init(&call->rq);
2366 queue_Init(&call->iovq);
2367 #ifdef RXDEBUG_PACKET
2368 call->rqc = call->tqc = call->iovqc = 0;
2369 #endif /* RXDEBUG_PACKET */
2370 /* Bind the call to its connection structure (prereq for reset) */
2372 rxi_ResetCall(call, 1);
2374 call->channel = channel;
2375 call->callNumber = &conn->callNumber[channel];
2376 call->rwind = conn->rwind[channel];
2377 call->twind = conn->twind[channel];
2378 /* Note that the next expected call number is retained (in
2379 * conn->callNumber[i]), even if we reallocate the call structure
2381 conn->call[channel] = call;
2382 /* if the channel's never been used (== 0), we should start at 1, otherwise
2383 * the call number is valid from the last time this channel was used */
2384 if (*call->callNumber == 0)
2385 *call->callNumber = 1;
2390 /* A call has been inactive long enough that so we can throw away
2391 * state, including the call structure, which is placed on the call
2394 * call->lock amd rx_refcnt_mutex are held upon entry.
2395 * haveCTLock is set when called from rxi_ReapConnections.
2398 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2400 int channel = call->channel;
2401 struct rx_connection *conn = call->conn;
2404 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2405 (*call->callNumber)++;
2406 rxi_ResetCall(call, 0);
2407 call->conn->call[channel] = (struct rx_call *)0;
2408 MUTEX_EXIT(&rx_refcnt_mutex);
2410 MUTEX_ENTER(&rx_freeCallQueue_lock);
2411 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2412 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2413 /* A call may be free even though its transmit queue is still in use.
2414 * Since we search the call list from head to tail, put busy calls at
2415 * the head of the list, and idle calls at the tail.
2417 if (call->flags & RX_CALL_TQ_BUSY)
2418 queue_Prepend(&rx_freeCallQueue, call);
2420 queue_Append(&rx_freeCallQueue, call);
2421 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2422 queue_Append(&rx_freeCallQueue, call);
2423 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2424 if (rx_stats_active)
2425 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2426 MUTEX_EXIT(&rx_freeCallQueue_lock);
2428 /* Destroy the connection if it was previously slated for
2429 * destruction, i.e. the Rx client code previously called
2430 * rx_DestroyConnection (client connections), or
2431 * rxi_ReapConnections called the same routine (server
2432 * connections). Only do this, however, if there are no
2433 * outstanding calls. Note that for fine grain locking, there appears
2434 * to be a deadlock in that rxi_FreeCall has a call locked and
2435 * DestroyConnectionNoLock locks each call in the conn. But note a
2436 * few lines up where we have removed this call from the conn.
2437 * If someone else destroys a connection, they either have no
2438 * call lock held or are going through this section of code.
2440 MUTEX_ENTER(&conn->conn_data_lock);
2441 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2442 MUTEX_ENTER(&rx_refcnt_mutex);
2444 MUTEX_EXIT(&rx_refcnt_mutex);
2445 MUTEX_EXIT(&conn->conn_data_lock);
2446 #ifdef RX_ENABLE_LOCKS
2448 rxi_DestroyConnectionNoLock(conn);
2450 rxi_DestroyConnection(conn);
2451 #else /* RX_ENABLE_LOCKS */
2452 rxi_DestroyConnection(conn);
2453 #endif /* RX_ENABLE_LOCKS */
2455 MUTEX_EXIT(&conn->conn_data_lock);
2457 MUTEX_ENTER(&rx_refcnt_mutex);
2460 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2461 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2464 rxi_Alloc(size_t size)
2468 if (rx_stats_active) {
2469 rx_atomic_add(&rxi_Allocsize, (int) size);
2470 rx_atomic_inc(&rxi_Alloccnt);
2474 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2475 afs_osi_Alloc_NoSleep(size);
2480 osi_Panic("rxi_Alloc error");
2486 rxi_Free(void *addr, size_t size)
2488 if (rx_stats_active) {
2489 rx_atomic_sub(&rxi_Allocsize, (int) size);
2490 rx_atomic_dec(&rxi_Alloccnt);
2492 osi_Free(addr, size);
2496 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2498 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2499 struct rx_peer *next = NULL;
2503 MUTEX_ENTER(&rx_peerHashTable_lock);
2505 peer_ptr = &rx_peerHashTable[0];
2506 peer_end = &rx_peerHashTable[rx_hashTableSize];
2509 for ( ; peer_ptr < peer_end; peer_ptr++) {
2512 for ( ; peer; peer = next) {
2514 if (host == peer->host)
2519 hashIndex = PEER_HASH(host, port);
2520 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2521 if ((peer->host == host) && (peer->port == port))
2526 MUTEX_ENTER(&rx_peerHashTable_lock);
2531 MUTEX_EXIT(&rx_peerHashTable_lock);
2533 MUTEX_ENTER(&peer->peer_lock);
2534 /* We don't handle dropping below min, so don't */
2535 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2536 peer->ifMTU=MIN(mtu, peer->ifMTU);
2537 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2538 /* if we tweaked this down, need to tune our peer MTU too */
2539 peer->MTU = MIN(peer->MTU, peer->natMTU);
2540 /* if we discovered a sub-1500 mtu, degrade */
2541 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2542 peer->maxDgramPackets = 1;
2543 /* We no longer have valid peer packet information */
2544 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2545 peer->maxPacketSize = 0;
2546 MUTEX_EXIT(&peer->peer_lock);
2548 MUTEX_ENTER(&rx_peerHashTable_lock);
2550 if (host && !port) {
2552 /* pick up where we left off */
2556 MUTEX_EXIT(&rx_peerHashTable_lock);
2559 /* Find the peer process represented by the supplied (host,port)
2560 * combination. If there is no appropriate active peer structure, a
2561 * new one will be allocated and initialized
2562 * The origPeer, if set, is a pointer to a peer structure on which the
2563 * refcount will be be decremented. This is used to replace the peer
2564 * structure hanging off a connection structure */
2566 rxi_FindPeer(afs_uint32 host, u_short port,
2567 struct rx_peer *origPeer, int create)
2571 hashIndex = PEER_HASH(host, port);
2572 MUTEX_ENTER(&rx_peerHashTable_lock);
2573 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2574 if ((pp->host == host) && (pp->port == port))
2579 pp = rxi_AllocPeer(); /* This bzero's *pp */
2580 pp->host = host; /* set here or in InitPeerParams is zero */
2582 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2583 queue_Init(&pp->congestionQueue);
2584 queue_Init(&pp->rpcStats);
2585 pp->next = rx_peerHashTable[hashIndex];
2586 rx_peerHashTable[hashIndex] = pp;
2587 rxi_InitPeerParams(pp);
2588 if (rx_stats_active)
2589 rx_atomic_inc(&rx_stats.nPeerStructs);
2596 origPeer->refCount--;
2597 MUTEX_EXIT(&rx_peerHashTable_lock);
2602 /* Find the connection at (host, port) started at epoch, and with the
2603 * given connection id. Creates the server connection if necessary.
2604 * The type specifies whether a client connection or a server
2605 * connection is desired. In both cases, (host, port) specify the
2606 * peer's (host, pair) pair. Client connections are not made
2607 * automatically by this routine. The parameter socket gives the
2608 * socket descriptor on which the packet was received. This is used,
2609 * in the case of server connections, to check that *new* connections
2610 * come via a valid (port, serviceId). Finally, the securityIndex
2611 * parameter must match the existing index for the connection. If a
2612 * server connection is created, it will be created using the supplied
2613 * index, if the index is valid for this service */
2614 struct rx_connection *
2615 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2616 u_short port, u_short serviceId, afs_uint32 cid,
2617 afs_uint32 epoch, int type, u_int securityIndex)
2619 int hashindex, flag, i;
2620 struct rx_connection *conn;
2621 hashindex = CONN_HASH(host, port, cid, epoch, type);
2622 MUTEX_ENTER(&rx_connHashTable_lock);
2623 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2624 rx_connHashTable[hashindex],
2627 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2628 && (epoch == conn->epoch)) {
2629 struct rx_peer *pp = conn->peer;
2630 if (securityIndex != conn->securityIndex) {
2631 /* this isn't supposed to happen, but someone could forge a packet
2632 * like this, and there seems to be some CM bug that makes this
2633 * happen from time to time -- in which case, the fileserver
2635 MUTEX_EXIT(&rx_connHashTable_lock);
2636 return (struct rx_connection *)0;
2638 if (pp->host == host && pp->port == port)
2640 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2642 /* So what happens when it's a callback connection? */
2643 if ( /*type == RX_CLIENT_CONNECTION && */
2644 (conn->epoch & 0x80000000))
2648 /* the connection rxLastConn that was used the last time is not the
2649 ** one we are looking for now. Hence, start searching in the hash */
2651 conn = rx_connHashTable[hashindex];
2656 struct rx_service *service;
2657 if (type == RX_CLIENT_CONNECTION) {
2658 MUTEX_EXIT(&rx_connHashTable_lock);
2659 return (struct rx_connection *)0;
2661 service = rxi_FindService(socket, serviceId);
2662 if (!service || (securityIndex >= service->nSecurityObjects)
2663 || (service->securityObjects[securityIndex] == 0)) {
2664 MUTEX_EXIT(&rx_connHashTable_lock);
2665 return (struct rx_connection *)0;
2667 conn = rxi_AllocConnection(); /* This bzero's the connection */
2668 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2669 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2670 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2671 conn->next = rx_connHashTable[hashindex];
2672 rx_connHashTable[hashindex] = conn;
2673 conn->peer = rxi_FindPeer(host, port, 0, 1);
2674 conn->type = RX_SERVER_CONNECTION;
2675 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2676 conn->epoch = epoch;
2677 conn->cid = cid & RX_CIDMASK;
2678 /* conn->serial = conn->lastSerial = 0; */
2679 /* conn->timeout = 0; */
2680 conn->ackRate = RX_FAST_ACK_RATE;
2681 conn->service = service;
2682 conn->serviceId = serviceId;
2683 conn->securityIndex = securityIndex;
2684 conn->securityObject = service->securityObjects[securityIndex];
2685 conn->nSpecific = 0;
2686 conn->specific = NULL;
2687 rx_SetConnDeadTime(conn, service->connDeadTime);
2688 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2689 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2690 for (i = 0; i < RX_MAXCALLS; i++) {
2691 conn->twind[i] = rx_initSendWindow;
2692 conn->rwind[i] = rx_initReceiveWindow;
2694 /* Notify security object of the new connection */
2695 RXS_NewConnection(conn->securityObject, conn);
2696 /* XXXX Connection timeout? */
2697 if (service->newConnProc)
2698 (*service->newConnProc) (conn);
2699 if (rx_stats_active)
2700 rx_atomic_inc(&rx_stats.nServerConns);
2703 MUTEX_ENTER(&rx_refcnt_mutex);
2705 MUTEX_EXIT(&rx_refcnt_mutex);
2707 rxLastConn = conn; /* store this connection as the last conn used */
2708 MUTEX_EXIT(&rx_connHashTable_lock);
2712 /* There are two packet tracing routines available for testing and monitoring
2713 * Rx. One is called just after every packet is received and the other is
2714 * called just before every packet is sent. Received packets, have had their
2715 * headers decoded, and packets to be sent have not yet had their headers
2716 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2717 * containing the network address. Both can be modified. The return value, if
2718 * non-zero, indicates that the packet should be dropped. */
2720 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2721 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2723 /* A packet has been received off the interface. Np is the packet, socket is
2724 * the socket number it was received from (useful in determining which service
2725 * this packet corresponds to), and (host, port) reflect the host,port of the
2726 * sender. This call returns the packet to the caller if it is finished with
2727 * it, rather than de-allocating it, just as a small performance hack */
2730 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2731 afs_uint32 host, u_short port, int *tnop,
2732 struct rx_call **newcallp)
2734 struct rx_call *call;
2735 struct rx_connection *conn;
2737 afs_uint32 currentCallNumber;
2743 struct rx_packet *tnp;
2746 /* We don't print out the packet until now because (1) the time may not be
2747 * accurate enough until now in the lwp implementation (rx_Listener only gets
2748 * the time after the packet is read) and (2) from a protocol point of view,
2749 * this is the first time the packet has been seen */
2750 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2751 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2752 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2753 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2754 np->header.epoch, np->header.cid, np->header.callNumber,
2755 np->header.seq, np->header.flags, np));
2758 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2759 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2762 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2763 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2766 /* If an input tracer function is defined, call it with the packet and
2767 * network address. Note this function may modify its arguments. */
2768 if (rx_justReceived) {
2769 struct sockaddr_in addr;
2771 addr.sin_family = AF_INET;
2772 addr.sin_port = port;
2773 addr.sin_addr.s_addr = host;
2774 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2775 addr.sin_len = sizeof(addr);
2776 #endif /* AFS_OSF_ENV */
2777 drop = (*rx_justReceived) (np, &addr);
2778 /* drop packet if return value is non-zero */
2781 port = addr.sin_port; /* in case fcn changed addr */
2782 host = addr.sin_addr.s_addr;
2786 /* If packet was not sent by the client, then *we* must be the client */
2787 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2788 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2790 /* Find the connection (or fabricate one, if we're the server & if
2791 * necessary) associated with this packet */
2793 rxi_FindConnection(socket, host, port, np->header.serviceId,
2794 np->header.cid, np->header.epoch, type,
2795 np->header.securityIndex);
2798 /* If no connection found or fabricated, just ignore the packet.
2799 * (An argument could be made for sending an abort packet for
2804 MUTEX_ENTER(&conn->conn_data_lock);
2805 if (conn->maxSerial < np->header.serial)
2806 conn->maxSerial = np->header.serial;
2807 MUTEX_EXIT(&conn->conn_data_lock);
2809 /* If the connection is in an error state, send an abort packet and ignore
2810 * the incoming packet */
2812 /* Don't respond to an abort packet--we don't want loops! */
2813 MUTEX_ENTER(&conn->conn_data_lock);
2814 if (np->header.type != RX_PACKET_TYPE_ABORT)
2815 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2816 MUTEX_ENTER(&rx_refcnt_mutex);
2818 MUTEX_EXIT(&rx_refcnt_mutex);
2819 MUTEX_EXIT(&conn->conn_data_lock);
2823 /* Check for connection-only requests (i.e. not call specific). */
2824 if (np->header.callNumber == 0) {
2825 switch (np->header.type) {
2826 case RX_PACKET_TYPE_ABORT: {
2827 /* What if the supplied error is zero? */
2828 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2829 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2830 rxi_ConnectionError(conn, errcode);
2831 MUTEX_ENTER(&rx_refcnt_mutex);
2833 MUTEX_EXIT(&rx_refcnt_mutex);
2836 case RX_PACKET_TYPE_CHALLENGE:
2837 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2838 MUTEX_ENTER(&rx_refcnt_mutex);
2840 MUTEX_EXIT(&rx_refcnt_mutex);
2842 case RX_PACKET_TYPE_RESPONSE:
2843 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2844 MUTEX_ENTER(&rx_refcnt_mutex);
2846 MUTEX_EXIT(&rx_refcnt_mutex);
2848 case RX_PACKET_TYPE_PARAMS:
2849 case RX_PACKET_TYPE_PARAMS + 1:
2850 case RX_PACKET_TYPE_PARAMS + 2:
2851 /* ignore these packet types for now */
2852 MUTEX_ENTER(&rx_refcnt_mutex);
2854 MUTEX_EXIT(&rx_refcnt_mutex);
2859 /* Should not reach here, unless the peer is broken: send an
2861 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2862 MUTEX_ENTER(&conn->conn_data_lock);
2863 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2864 MUTEX_ENTER(&rx_refcnt_mutex);
2866 MUTEX_EXIT(&rx_refcnt_mutex);
2867 MUTEX_EXIT(&conn->conn_data_lock);
2872 channel = np->header.cid & RX_CHANNELMASK;
2873 call = conn->call[channel];
2874 #ifdef RX_ENABLE_LOCKS
2876 MUTEX_ENTER(&call->lock);
2877 /* Test to see if call struct is still attached to conn. */
2878 if (call != conn->call[channel]) {
2880 MUTEX_EXIT(&call->lock);
2881 if (type == RX_SERVER_CONNECTION) {
2882 call = conn->call[channel];
2883 /* If we started with no call attached and there is one now,
2884 * another thread is also running this routine and has gotten
2885 * the connection channel. We should drop this packet in the tests
2886 * below. If there was a call on this connection and it's now
2887 * gone, then we'll be making a new call below.
2888 * If there was previously a call and it's now different then
2889 * the old call was freed and another thread running this routine
2890 * has created a call on this channel. One of these two threads
2891 * has a packet for the old call and the code below handles those
2895 MUTEX_ENTER(&call->lock);
2897 /* This packet can't be for this call. If the new call address is
2898 * 0 then no call is running on this channel. If there is a call
2899 * then, since this is a client connection we're getting data for
2900 * it must be for the previous call.
2902 if (rx_stats_active)
2903 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2904 MUTEX_ENTER(&rx_refcnt_mutex);
2906 MUTEX_EXIT(&rx_refcnt_mutex);
2911 currentCallNumber = conn->callNumber[channel];
2913 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2914 if (np->header.callNumber < currentCallNumber) {
2915 if (rx_stats_active)
2916 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2917 #ifdef RX_ENABLE_LOCKS
2919 MUTEX_EXIT(&call->lock);
2921 MUTEX_ENTER(&rx_refcnt_mutex);
2923 MUTEX_EXIT(&rx_refcnt_mutex);
2927 MUTEX_ENTER(&conn->conn_call_lock);
2928 call = rxi_NewCall(conn, channel);
2929 MUTEX_EXIT(&conn->conn_call_lock);
2930 *call->callNumber = np->header.callNumber;
2932 if (np->header.callNumber == 0)
2933 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d",
2934 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2935 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2936 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2938 call->state = RX_STATE_PRECALL;
2939 clock_GetTime(&call->queueTime);
2940 hzero(call->bytesSent);
2941 hzero(call->bytesRcvd);
2943 * If the number of queued calls exceeds the overload
2944 * threshold then abort this call.
2946 if ((rx_BusyThreshold > 0) &&
2947 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
2948 struct rx_packet *tp;
2950 rxi_CallError(call, rx_BusyError);
2951 tp = rxi_SendCallAbort(call, np, 1, 0);
2952 MUTEX_EXIT(&call->lock);
2953 MUTEX_ENTER(&rx_refcnt_mutex);
2955 MUTEX_EXIT(&rx_refcnt_mutex);
2956 if (rx_stats_active)
2957 rx_atomic_inc(&rx_stats.nBusies);
2960 rxi_KeepAliveOn(call);
2961 } else if (np->header.callNumber != currentCallNumber) {
2962 /* Wait until the transmit queue is idle before deciding
2963 * whether to reset the current call. Chances are that the
2964 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2967 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2968 while ((call->state == RX_STATE_ACTIVE)
2969 && (call->flags & RX_CALL_TQ_BUSY)) {
2970 call->flags |= RX_CALL_TQ_WAIT;
2972 #ifdef RX_ENABLE_LOCKS
2973 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2974 CV_WAIT(&call->cv_tq, &call->lock);
2975 #else /* RX_ENABLE_LOCKS */
2976 osi_rxSleep(&call->tq);
2977 #endif /* RX_ENABLE_LOCKS */
2979 if (call->tqWaiters == 0)
2980 call->flags &= ~RX_CALL_TQ_WAIT;
2982 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2983 /* If the new call cannot be taken right now send a busy and set
2984 * the error condition in this call, so that it terminates as
2985 * quickly as possible */
2986 if (call->state == RX_STATE_ACTIVE) {
2987 struct rx_packet *tp;
2989 rxi_CallError(call, RX_CALL_DEAD);
2990 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2992 MUTEX_EXIT(&call->lock);
2993 MUTEX_ENTER(&rx_refcnt_mutex);
2995 MUTEX_EXIT(&rx_refcnt_mutex);
2998 rxi_ResetCall(call, 0);
2999 *call->callNumber = np->header.callNumber;
3001 if (np->header.callNumber == 0)
3002 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
3003 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3004 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3005 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3007 call->state = RX_STATE_PRECALL;
3008 clock_GetTime(&call->queueTime);
3009 hzero(call->bytesSent);
3010 hzero(call->bytesRcvd);
3012 * If the number of queued calls exceeds the overload
3013 * threshold then abort this call.
3015 if ((rx_BusyThreshold > 0) &&
3016 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3017 struct rx_packet *tp;
3019 rxi_CallError(call, rx_BusyError);
3020 tp = rxi_SendCallAbort(call, np, 1, 0);
3021 MUTEX_EXIT(&call->lock);
3022 MUTEX_ENTER(&rx_refcnt_mutex);
3024 MUTEX_EXIT(&rx_refcnt_mutex);
3025 if (rx_stats_active)
3026 rx_atomic_inc(&rx_stats.nBusies);
3029 rxi_KeepAliveOn(call);
3031 /* Continuing call; do nothing here. */
3033 } else { /* we're the client */
3034 /* Ignore all incoming acknowledgements for calls in DALLY state */
3035 if (call && (call->state == RX_STATE_DALLY)
3036 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3037 if (rx_stats_active)
3038 rx_atomic_inc(&rx_stats.ignorePacketDally);
3039 #ifdef RX_ENABLE_LOCKS
3041 MUTEX_EXIT(&call->lock);
3044 MUTEX_ENTER(&rx_refcnt_mutex);
3046 MUTEX_EXIT(&rx_refcnt_mutex);
3050 /* Ignore anything that's not relevant to the current call. If there
3051 * isn't a current call, then no packet is relevant. */
3052 if (!call || (np->header.callNumber != currentCallNumber)) {
3053 if (rx_stats_active)
3054 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3055 #ifdef RX_ENABLE_LOCKS
3057 MUTEX_EXIT(&call->lock);
3060 MUTEX_ENTER(&rx_refcnt_mutex);
3062 MUTEX_EXIT(&rx_refcnt_mutex);
3065 /* If the service security object index stamped in the packet does not
3066 * match the connection's security index, ignore the packet */
3067 if (np->header.securityIndex != conn->securityIndex) {
3068 #ifdef RX_ENABLE_LOCKS
3069 MUTEX_EXIT(&call->lock);
3071 MUTEX_ENTER(&rx_refcnt_mutex);
3073 MUTEX_EXIT(&rx_refcnt_mutex);
3077 /* If we're receiving the response, then all transmit packets are
3078 * implicitly acknowledged. Get rid of them. */
3079 if (np->header.type == RX_PACKET_TYPE_DATA) {
3080 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3081 /* XXX Hack. Because we must release the global rx lock when
3082 * sending packets (osi_NetSend) we drop all acks while we're
3083 * traversing the tq in rxi_Start sending packets out because
3084 * packets may move to the freePacketQueue as result of being here!
3085 * So we drop these packets until we're safely out of the
3086 * traversing. Really ugly!
3087 * For fine grain RX locking, we set the acked field in the
3088 * packets and let rxi_Start remove them from the transmit queue.
3090 if (call->flags & RX_CALL_TQ_BUSY) {
3091 #ifdef RX_ENABLE_LOCKS
3092 rxi_SetAcksInTransmitQueue(call);
3094 MUTEX_ENTER(&rx_refcnt_mutex);
3096 MUTEX_EXIT(&rx_refcnt_mutex);
3097 return np; /* xmitting; drop packet */
3100 rxi_ClearTransmitQueue(call, 0);
3102 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3103 rxi_ClearTransmitQueue(call, 0);
3104 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3106 if (np->header.type == RX_PACKET_TYPE_ACK) {
3107 /* now check to see if this is an ack packet acknowledging that the
3108 * server actually *lost* some hard-acked data. If this happens we
3109 * ignore this packet, as it may indicate that the server restarted in
3110 * the middle of a call. It is also possible that this is an old ack
3111 * packet. We don't abort the connection in this case, because this
3112 * *might* just be an old ack packet. The right way to detect a server
3113 * restart in the midst of a call is to notice that the server epoch
3115 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3116 * XXX unacknowledged. I think that this is off-by-one, but
3117 * XXX I don't dare change it just yet, since it will
3118 * XXX interact badly with the server-restart detection
3119 * XXX code in receiveackpacket. */
3120 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3121 if (rx_stats_active)
3122 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3123 MUTEX_EXIT(&call->lock);
3124 MUTEX_ENTER(&rx_refcnt_mutex);
3126 MUTEX_EXIT(&rx_refcnt_mutex);
3130 } /* else not a data packet */
3133 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3134 /* Set remote user defined status from packet */
3135 call->remoteStatus = np->header.userStatus;
3137 /* Note the gap between the expected next packet and the actual
3138 * packet that arrived, when the new packet has a smaller serial number
3139 * than expected. Rioses frequently reorder packets all by themselves,
3140 * so this will be quite important with very large window sizes.
3141 * Skew is checked against 0 here to avoid any dependence on the type of
3142 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3144 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3145 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3146 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3148 MUTEX_ENTER(&conn->conn_data_lock);
3149 skew = conn->lastSerial - np->header.serial;
3150 conn->lastSerial = np->header.serial;
3151 MUTEX_EXIT(&conn->conn_data_lock);
3153 struct rx_peer *peer;
3155 if (skew > peer->inPacketSkew) {
3156 dpf(("*** In skew changed from %d to %d\n",
3157 peer->inPacketSkew, skew));
3158 peer->inPacketSkew = skew;
3162 /* Now do packet type-specific processing */
3163 switch (np->header.type) {
3164 case RX_PACKET_TYPE_DATA:
3165 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3168 case RX_PACKET_TYPE_ACK:
3169 /* Respond immediately to ack packets requesting acknowledgement
3171 if (np->header.flags & RX_REQUEST_ACK) {
3173 (void)rxi_SendCallAbort(call, 0, 1, 0);
3175 (void)rxi_SendAck(call, 0, np->header.serial,
3176 RX_ACK_PING_RESPONSE, 1);
3178 np = rxi_ReceiveAckPacket(call, np, 1);
3180 case RX_PACKET_TYPE_ABORT: {
3181 /* An abort packet: reset the call, passing the error up to the user. */
3182 /* What if error is zero? */
3183 /* What if the error is -1? the application will treat it as a timeout. */
3184 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3185 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3186 rxi_CallError(call, errdata);
3187 MUTEX_EXIT(&call->lock);
3188 MUTEX_ENTER(&rx_refcnt_mutex);
3190 MUTEX_EXIT(&rx_refcnt_mutex);
3191 return np; /* xmitting; drop packet */
3193 case RX_PACKET_TYPE_BUSY:
3196 case RX_PACKET_TYPE_ACKALL:
3197 /* All packets acknowledged, so we can drop all packets previously
3198 * readied for sending */
3199 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3200 /* XXX Hack. We because we can't release the global rx lock when
3201 * sending packets (osi_NetSend) we drop all ack pkts while we're
3202 * traversing the tq in rxi_Start sending packets out because
3203 * packets may move to the freePacketQueue as result of being
3204 * here! So we drop these packets until we're safely out of the
3205 * traversing. Really ugly!
3206 * For fine grain RX locking, we set the acked field in the packets
3207 * and let rxi_Start remove the packets from the transmit queue.
3209 if (call->flags & RX_CALL_TQ_BUSY) {
3210 #ifdef RX_ENABLE_LOCKS
3211 rxi_SetAcksInTransmitQueue(call);
3213 #else /* RX_ENABLE_LOCKS */
3214 MUTEX_EXIT(&call->lock);
3215 MUTEX_ENTER(&rx_refcnt_mutex);
3217 MUTEX_EXIT(&rx_refcnt_mutex);
3218 return np; /* xmitting; drop packet */
3219 #endif /* RX_ENABLE_LOCKS */
3221 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3222 rxi_ClearTransmitQueue(call, 0);
3223 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3226 /* Should not reach here, unless the peer is broken: send an abort
3228 rxi_CallError(call, RX_PROTOCOL_ERROR);
3229 np = rxi_SendCallAbort(call, np, 1, 0);
3232 /* Note when this last legitimate packet was received, for keep-alive
3233 * processing. Note, we delay getting the time until now in the hope that
3234 * the packet will be delivered to the user before any get time is required
3235 * (if not, then the time won't actually be re-evaluated here). */
3236 call->lastReceiveTime = clock_Sec();
3237 MUTEX_EXIT(&call->lock);
3238 MUTEX_ENTER(&rx_refcnt_mutex);
3240 MUTEX_EXIT(&rx_refcnt_mutex);
3244 /* return true if this is an "interesting" connection from the point of view
3245 of someone trying to debug the system */
3247 rxi_IsConnInteresting(struct rx_connection *aconn)
3250 struct rx_call *tcall;
3252 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3255 for (i = 0; i < RX_MAXCALLS; i++) {
3256 tcall = aconn->call[i];
3258 if ((tcall->state == RX_STATE_PRECALL)
3259 || (tcall->state == RX_STATE_ACTIVE))
3261 if ((tcall->mode == RX_MODE_SENDING)
3262 || (tcall->mode == RX_MODE_RECEIVING))
3270 /* if this is one of the last few packets AND it wouldn't be used by the
3271 receiving call to immediately satisfy a read request, then drop it on
3272 the floor, since accepting it might prevent a lock-holding thread from
3273 making progress in its reading. If a call has been cleared while in
3274 the precall state then ignore all subsequent packets until the call
3275 is assigned to a thread. */
3278 TooLow(struct rx_packet *ap, struct rx_call *acall)
3282 MUTEX_ENTER(&rx_quota_mutex);
3283 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3284 && (acall->state == RX_STATE_PRECALL))
3285 || ((rx_nFreePackets < rxi_dataQuota + 2)
3286 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3287 && (acall->flags & RX_CALL_READER_WAIT)))) {
3290 MUTEX_EXIT(&rx_quota_mutex);
3296 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3298 struct rx_connection *conn = arg1;
3299 struct rx_call *acall = arg2;
3300 struct rx_call *call = acall;
3301 struct clock when, now;
3304 MUTEX_ENTER(&conn->conn_data_lock);
3305 conn->checkReachEvent = NULL;
3306 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3308 MUTEX_ENTER(&rx_refcnt_mutex);
3310 MUTEX_EXIT(&rx_refcnt_mutex);
3312 MUTEX_EXIT(&conn->conn_data_lock);
3316 MUTEX_ENTER(&conn->conn_call_lock);
3317 MUTEX_ENTER(&conn->conn_data_lock);
3318 for (i = 0; i < RX_MAXCALLS; i++) {
3319 struct rx_call *tc = conn->call[i];
3320 if (tc && tc->state == RX_STATE_PRECALL) {
3326 /* Indicate that rxi_CheckReachEvent is no longer running by
3327 * clearing the flag. Must be atomic under conn_data_lock to
3328 * avoid a new call slipping by: rxi_CheckConnReach holds
3329 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3331 conn->flags &= ~RX_CONN_ATTACHWAIT;
3332 MUTEX_EXIT(&conn->conn_data_lock);
3333 MUTEX_EXIT(&conn->conn_call_lock);
3338 MUTEX_ENTER(&call->lock);
3339 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3341 MUTEX_EXIT(&call->lock);
3343 clock_GetTime(&now);
3345 when.sec += RX_CHECKREACH_TIMEOUT;
3346 MUTEX_ENTER(&conn->conn_data_lock);
3347 if (!conn->checkReachEvent) {
3348 MUTEX_ENTER(&rx_refcnt_mutex);
3350 MUTEX_EXIT(&rx_refcnt_mutex);
3351 conn->checkReachEvent =
3352 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3355 MUTEX_EXIT(&conn->conn_data_lock);
3361 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3363 struct rx_service *service = conn->service;
3364 struct rx_peer *peer = conn->peer;
3365 afs_uint32 now, lastReach;
3367 if (service->checkReach == 0)
3371 MUTEX_ENTER(&peer->peer_lock);
3372 lastReach = peer->lastReachTime;
3373 MUTEX_EXIT(&peer->peer_lock);
3374 if (now - lastReach < RX_CHECKREACH_TTL)
3377 MUTEX_ENTER(&conn->conn_data_lock);
3378 if (conn->flags & RX_CONN_ATTACHWAIT) {
3379 MUTEX_EXIT(&conn->conn_data_lock);
3382 conn->flags |= RX_CONN_ATTACHWAIT;
3383 MUTEX_EXIT(&conn->conn_data_lock);
3384 if (!conn->checkReachEvent)
3385 rxi_CheckReachEvent(NULL, conn, call);
3390 /* try to attach call, if authentication is complete */
3392 TryAttach(struct rx_call *acall, osi_socket socket,
3393 int *tnop, struct rx_call **newcallp,
3396 struct rx_connection *conn = acall->conn;
3398 if (conn->type == RX_SERVER_CONNECTION
3399 && acall->state == RX_STATE_PRECALL) {
3400 /* Don't attach until we have any req'd. authentication. */
3401 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3402 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3403 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3404 /* Note: this does not necessarily succeed; there
3405 * may not any proc available
3408 rxi_ChallengeOn(acall->conn);
3413 /* A data packet has been received off the interface. This packet is
3414 * appropriate to the call (the call is in the right state, etc.). This
3415 * routine can return a packet to the caller, for re-use */
3418 rxi_ReceiveDataPacket(struct rx_call *call,
3419 struct rx_packet *np, int istack,
3420 osi_socket socket, afs_uint32 host, u_short port,
3421 int *tnop, struct rx_call **newcallp)
3423 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3428 afs_uint32 serial=0, flags=0;
3430 struct rx_packet *tnp;
3431 struct clock when, now;
3432 if (rx_stats_active)
3433 rx_atomic_inc(&rx_stats.dataPacketsRead);
3436 /* If there are no packet buffers, drop this new packet, unless we can find
3437 * packet buffers from inactive calls */
3439 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3440 MUTEX_ENTER(&rx_freePktQ_lock);
3441 rxi_NeedMorePackets = TRUE;
3442 MUTEX_EXIT(&rx_freePktQ_lock);
3443 if (rx_stats_active)
3444 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3445 call->rprev = np->header.serial;
3446 rxi_calltrace(RX_TRACE_DROP, call);
3447 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3449 rxi_ClearReceiveQueue(call);
3450 clock_GetTime(&now);
3452 clock_Add(&when, &rx_softAckDelay);
3453 if (!call->delayedAckEvent
3454 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3455 rxevent_Cancel(call->delayedAckEvent, call,
3456 RX_CALL_REFCOUNT_DELAY);
3457 MUTEX_ENTER(&rx_refcnt_mutex);
3458 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3459 MUTEX_EXIT(&rx_refcnt_mutex);
3461 call->delayedAckEvent =
3462 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3464 /* we've damaged this call already, might as well do it in. */
3470 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3471 * packet is one of several packets transmitted as a single
3472 * datagram. Do not send any soft or hard acks until all packets
3473 * in a jumbogram have been processed. Send negative acks right away.
3475 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3476 /* tnp is non-null when there are more packets in the
3477 * current jumbo gram */
3484 seq = np->header.seq;
3485 serial = np->header.serial;
3486 flags = np->header.flags;
3488 /* If the call is in an error state, send an abort message */
3490 return rxi_SendCallAbort(call, np, istack, 0);
3492 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3493 * AFS 3.5 jumbogram. */
3494 if (flags & RX_JUMBO_PACKET) {
3495 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3500 if (np->header.spare != 0) {
3501 MUTEX_ENTER(&call->conn->conn_data_lock);
3502 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3503 MUTEX_EXIT(&call->conn->conn_data_lock);
3506 /* The usual case is that this is the expected next packet */
3507 if (seq == call->rnext) {
3509 /* Check to make sure it is not a duplicate of one already queued */
3510 if (queue_IsNotEmpty(&call->rq)
3511 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3512 if (rx_stats_active)
3513 rx_atomic_inc(&rx_stats.dupPacketsRead);
3514 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3515 rxevent_Cancel(call->delayedAckEvent, call,
3516 RX_CALL_REFCOUNT_DELAY);
3517 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3523 /* It's the next packet. Stick it on the receive queue
3524 * for this call. Set newPackets to make sure we wake
3525 * the reader once all packets have been processed */
3526 #ifdef RX_TRACK_PACKETS
3527 np->flags |= RX_PKTFLAG_RQ;
3529 queue_Prepend(&call->rq, np);
3530 #ifdef RXDEBUG_PACKET
3532 #endif /* RXDEBUG_PACKET */
3534 np = NULL; /* We can't use this anymore */
3537 /* If an ack is requested then set a flag to make sure we
3538 * send an acknowledgement for this packet */
3539 if (flags & RX_REQUEST_ACK) {
3540 ackNeeded = RX_ACK_REQUESTED;
3543 /* Keep track of whether we have received the last packet */
3544 if (flags & RX_LAST_PACKET) {
3545 call->flags |= RX_CALL_HAVE_LAST;
3549 /* Check whether we have all of the packets for this call */
3550 if (call->flags & RX_CALL_HAVE_LAST) {
3551 afs_uint32 tseq; /* temporary sequence number */
3552 struct rx_packet *tp; /* Temporary packet pointer */
3553 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3555 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3556 if (tseq != tp->header.seq)
3558 if (tp->header.flags & RX_LAST_PACKET) {
3559 call->flags |= RX_CALL_RECEIVE_DONE;
3566 /* Provide asynchronous notification for those who want it
3567 * (e.g. multi rx) */
3568 if (call->arrivalProc) {
3569 (*call->arrivalProc) (call, call->arrivalProcHandle,
3570 call->arrivalProcArg);
3571 call->arrivalProc = (void (*)())0;
3574 /* Update last packet received */
3577 /* If there is no server process serving this call, grab
3578 * one, if available. We only need to do this once. If a
3579 * server thread is available, this thread becomes a server
3580 * thread and the server thread becomes a listener thread. */
3582 TryAttach(call, socket, tnop, newcallp, 0);
3585 /* This is not the expected next packet. */
3587 /* Determine whether this is a new or old packet, and if it's
3588 * a new one, whether it fits into the current receive window.
3589 * Also figure out whether the packet was delivered in sequence.
3590 * We use the prev variable to determine whether the new packet
3591 * is the successor of its immediate predecessor in the
3592 * receive queue, and the missing flag to determine whether
3593 * any of this packets predecessors are missing. */
3595 afs_uint32 prev; /* "Previous packet" sequence number */
3596 struct rx_packet *tp; /* Temporary packet pointer */
3597 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3598 int missing; /* Are any predecessors missing? */
3600 /* If the new packet's sequence number has been sent to the
3601 * application already, then this is a duplicate */
3602 if (seq < call->rnext) {
3603 if (rx_stats_active)
3604 rx_atomic_inc(&rx_stats.dupPacketsRead);
3605 rxevent_Cancel(call->delayedAckEvent, call,
3606 RX_CALL_REFCOUNT_DELAY);
3607 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3613 /* If the sequence number is greater than what can be
3614 * accomodated by the current window, then send a negative
3615 * acknowledge and drop the packet */
3616 if ((call->rnext + call->rwind) <= seq) {
3617 rxevent_Cancel(call->delayedAckEvent, call,
3618 RX_CALL_REFCOUNT_DELAY);
3619 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3626 /* Look for the packet in the queue of old received packets */
3627 for (prev = call->rnext - 1, missing =
3628 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3629 /*Check for duplicate packet */
3630 if (seq == tp->header.seq) {
3631 if (rx_stats_active)
3632 rx_atomic_inc(&rx_stats.dupPacketsRead);
3633 rxevent_Cancel(call->delayedAckEvent, call,
3634 RX_CALL_REFCOUNT_DELAY);
3635 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3641 /* If we find a higher sequence packet, break out and
3642 * insert the new packet here. */
3643 if (seq < tp->header.seq)
3645 /* Check for missing packet */
3646 if (tp->header.seq != prev + 1) {
3650 prev = tp->header.seq;
3653 /* Keep track of whether we have received the last packet. */
3654 if (flags & RX_LAST_PACKET) {
3655 call->flags |= RX_CALL_HAVE_LAST;
3658 /* It's within the window: add it to the the receive queue.
3659 * tp is left by the previous loop either pointing at the
3660 * packet before which to insert the new packet, or at the
3661 * queue head if the queue is empty or the packet should be
3663 #ifdef RX_TRACK_PACKETS
3664 np->flags |= RX_PKTFLAG_RQ;
3666 #ifdef RXDEBUG_PACKET
3668 #endif /* RXDEBUG_PACKET */
3669 queue_InsertBefore(tp, np);
3673 /* Check whether we have all of the packets for this call */
3674 if ((call->flags & RX_CALL_HAVE_LAST)
3675 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3676 afs_uint32 tseq; /* temporary sequence number */
3679 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3680 if (tseq != tp->header.seq)
3682 if (tp->header.flags & RX_LAST_PACKET) {
3683 call->flags |= RX_CALL_RECEIVE_DONE;
3690 /* We need to send an ack of the packet is out of sequence,
3691 * or if an ack was requested by the peer. */
3692 if (seq != prev + 1 || missing) {
3693 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3694 } else if (flags & RX_REQUEST_ACK) {
3695 ackNeeded = RX_ACK_REQUESTED;
3698 /* Acknowledge the last packet for each call */
3699 if (flags & RX_LAST_PACKET) {
3710 * If the receiver is waiting for an iovec, fill the iovec
3711 * using the data from the receive queue */
3712 if (call->flags & RX_CALL_IOVEC_WAIT) {
3713 didHardAck = rxi_FillReadVec(call, serial);
3714 /* the call may have been aborted */
3723 /* Wakeup the reader if any */
3724 if ((call->flags & RX_CALL_READER_WAIT)
3725 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3726 || (call->iovNext >= call->iovMax)
3727 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3728 call->flags &= ~RX_CALL_READER_WAIT;
3729 #ifdef RX_ENABLE_LOCKS
3730 CV_BROADCAST(&call->cv_rq);
3732 osi_rxWakeup(&call->rq);
3738 * Send an ack when requested by the peer, or once every
3739 * rxi_SoftAckRate packets until the last packet has been
3740 * received. Always send a soft ack for the last packet in
3741 * the server's reply.
3743 * If we have received all of the packets for the call
3744 * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3745 * the peer can empty its packet queue and cancel all resend
3748 if (call->flags & RX_CALL_RECEIVE_DONE) {
3749 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3750 rxi_AckAll(NULL, call, 0);
3751 } else if (ackNeeded) {
3752 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3753 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3754 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3755 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3756 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3757 } else if (call->nSoftAcks) {
3758 clock_GetTime(&now);
3760 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3761 clock_Add(&when, &rx_lastAckDelay);
3763 clock_Add(&when, &rx_softAckDelay);
3765 if (!call->delayedAckEvent
3766 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3767 rxevent_Cancel(call->delayedAckEvent, call,
3768 RX_CALL_REFCOUNT_DELAY);
3769 MUTEX_ENTER(&rx_refcnt_mutex);
3770 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3771 MUTEX_EXIT(&rx_refcnt_mutex);
3772 call->delayedAckEvent =
3773 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3781 static void rxi_ComputeRate();
3785 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3787 struct rx_peer *peer = conn->peer;
3789 MUTEX_ENTER(&peer->peer_lock);
3790 peer->lastReachTime = clock_Sec();
3791 MUTEX_EXIT(&peer->peer_lock);
3793 MUTEX_ENTER(&conn->conn_data_lock);
3794 if (conn->flags & RX_CONN_ATTACHWAIT) {
3797 conn->flags &= ~RX_CONN_ATTACHWAIT;
3798 MUTEX_EXIT(&conn->conn_data_lock);
3800 for (i = 0; i < RX_MAXCALLS; i++) {
3801 struct rx_call *call = conn->call[i];
3804 MUTEX_ENTER(&call->lock);
3805 /* tnop can be null if newcallp is null */
3806 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3808 MUTEX_EXIT(&call->lock);
3812 MUTEX_EXIT(&conn->conn_data_lock);
3815 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3817 rx_ack_reason(int reason)
3820 case RX_ACK_REQUESTED:
3822 case RX_ACK_DUPLICATE:
3824 case RX_ACK_OUT_OF_SEQUENCE:
3826 case RX_ACK_EXCEEDS_WINDOW:
3828 case RX_ACK_NOSPACE:
3832 case RX_ACK_PING_RESPONSE:
3845 /* rxi_ComputePeerNetStats
3847 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3848 * estimates (like RTT and throughput) based on ack packets. Caller
3849 * must ensure that the packet in question is the right one (i.e.
3850 * serial number matches).
3853 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3854 struct rx_ackPacket *ap, struct rx_packet *np)
3856 struct rx_peer *peer = call->conn->peer;
3858 /* Use RTT if not delayed by client and
3859 * ignore packets that were retransmitted. */
3860 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3861 ap->reason != RX_ACK_DELAY &&
3862 clock_Eq(&p->timeSent, &p->firstSent))
3863 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3865 rxi_ComputeRate(peer, call, p, np, ap->reason);
3869 /* The real smarts of the whole thing. */
3871 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3874 struct rx_ackPacket *ap;
3876 struct rx_packet *tp;
3877 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3878 struct rx_connection *conn = call->conn;
3879 struct rx_peer *peer = conn->peer;
3882 /* because there are CM's that are bogus, sending weird values for this. */
3883 afs_uint32 skew = 0;
3888 int newAckCount = 0;
3889 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3890 int pktsize = 0; /* Set if we need to update the peer mtu */
3891 int conn_data_locked = 0;
3893 if (rx_stats_active)
3894 rx_atomic_inc(&rx_stats.ackPacketsRead);
3895 ap = (struct rx_ackPacket *)rx_DataOf(np);
3896 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3898 return np; /* truncated ack packet */
3900 /* depends on ack packet struct */
3901 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3902 first = ntohl(ap->firstPacket);
3903 serial = ntohl(ap->serial);
3904 /* temporarily disabled -- needs to degrade over time
3905 * skew = ntohs(ap->maxSkew); */
3907 /* Ignore ack packets received out of order */
3908 if (first < call->tfirst) {
3912 if (np->header.flags & RX_SLOW_START_OK) {
3913 call->flags |= RX_CALL_SLOW_START_OK;
3916 if (ap->reason == RX_ACK_PING_RESPONSE)
3917 rxi_UpdatePeerReach(conn, call);
3919 if (conn->lastPacketSizeSeq) {
3920 MUTEX_ENTER(&conn->conn_data_lock);
3921 conn_data_locked = 1;
3922 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
3923 pktsize = conn->lastPacketSize;
3924 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
3927 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
3928 if (!conn_data_locked) {
3929 MUTEX_ENTER(&conn->conn_data_lock);
3930 conn_data_locked = 1;
3932 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
3933 /* process mtu ping ack */
3934 pktsize = conn->lastPingSize;
3935 conn->lastPingSizeSer = conn->lastPingSize = 0;
3939 if (conn_data_locked) {
3940 MUTEX_EXIT(&conn->conn_data_lock);
3941 conn_data_locked = 0;
3945 if (rxdebug_active) {
3949 len = _snprintf(msg, sizeof(msg),
3950 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3951 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3952 ntohl(ap->serial), ntohl(ap->previousPacket),
3953 (unsigned int)np->header.seq, (unsigned int)skew,
3954 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3958 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3959 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3963 OutputDebugString(msg);
3965 #else /* AFS_NT40_ENV */
3968 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3969 ap->reason, ntohl(ap->previousPacket),
3970 (unsigned int)np->header.seq, (unsigned int)serial,
3971 (unsigned int)skew, ntohl(ap->firstPacket));
3974 for (offset = 0; offset < nAcks; offset++)
3975 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3980 #endif /* AFS_NT40_ENV */
3983 MUTEX_ENTER(&peer->peer_lock);
3986 * Start somewhere. Can't assume we can send what we can receive,
3987 * but we are clearly receiving.
3989 if (!peer->maxPacketSize)
3990 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
3992 if (pktsize > peer->maxPacketSize) {
3993 peer->maxPacketSize = pktsize;
3994 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
3995 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
3996 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
3997 rxi_ScheduleGrowMTUEvent(call, 1);
4002 /* Update the outgoing packet skew value to the latest value of
4003 * the peer's incoming packet skew value. The ack packet, of
4004 * course, could arrive out of order, but that won't affect things
4006 peer->outPacketSkew = skew;
4008 /* Check for packets that no longer need to be transmitted, and
4009 * discard them. This only applies to packets positively
4010 * acknowledged as having been sent to the peer's upper level.
4011 * All other packets must be retained. So only packets with
4012 * sequence numbers < ap->firstPacket are candidates. */
4013 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4014 if (tp->header.seq >= first)
4016 call->tfirst = tp->header.seq + 1;
4017 rxi_ComputePeerNetStats(call, tp, ap, np);
4018 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4021 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4022 /* XXX Hack. Because we have to release the global rx lock when sending
4023 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4024 * in rxi_Start sending packets out because packets may move to the
4025 * freePacketQueue as result of being here! So we drop these packets until
4026 * we're safely out of the traversing. Really ugly!
4027 * To make it even uglier, if we're using fine grain locking, we can
4028 * set the ack bits in the packets and have rxi_Start remove the packets
4029 * when it's done transmitting.
4031 if (call->flags & RX_CALL_TQ_BUSY) {
4032 #ifdef RX_ENABLE_LOCKS
4033 tp->flags |= RX_PKTFLAG_ACKED;
4034 call->flags |= RX_CALL_TQ_SOME_ACKED;
4035 #else /* RX_ENABLE_LOCKS */
4037 #endif /* RX_ENABLE_LOCKS */
4039 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4042 #ifdef RX_TRACK_PACKETS
4043 tp->flags &= ~RX_PKTFLAG_TQ;
4045 #ifdef RXDEBUG_PACKET
4047 #endif /* RXDEBUG_PACKET */
4048 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4053 /* Give rate detector a chance to respond to ping requests */
4054 if (ap->reason == RX_ACK_PING_RESPONSE) {
4055 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4059 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4061 /* Now go through explicit acks/nacks and record the results in
4062 * the waiting packets. These are packets that can't be released
4063 * yet, even with a positive acknowledge. This positive
4064 * acknowledge only means the packet has been received by the
4065 * peer, not that it will be retained long enough to be sent to
4066 * the peer's upper level. In addition, reset the transmit timers
4067 * of any missing packets (those packets that must be missing
4068 * because this packet was out of sequence) */
4070 call->nSoftAcked = 0;
4071 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4072 /* Update round trip time if the ack was stimulated on receipt
4074 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4075 #ifdef RX_ENABLE_LOCKS
4076 if (tp->header.seq >= first)
4077 #endif /* RX_ENABLE_LOCKS */
4078 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4079 rxi_ComputePeerNetStats(call, tp, ap, np);
4081 /* Set the acknowledge flag per packet based on the
4082 * information in the ack packet. An acknowlegded packet can
4083 * be downgraded when the server has discarded a packet it
4084 * soacked previously, or when an ack packet is received
4085 * out of sequence. */
4086 if (tp->header.seq < first) {
4087 /* Implicit ack information */
4088 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4091 tp->flags |= RX_PKTFLAG_ACKED;
4092 } else if (tp->header.seq < first + nAcks) {
4093 /* Explicit ack information: set it in the packet appropriately */
4094 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4095 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4097 tp->flags |= RX_PKTFLAG_ACKED;
4104 } else /* RX_ACK_TYPE_NACK */ {
4105 tp->flags &= ~RX_PKTFLAG_ACKED;
4109 tp->flags &= ~RX_PKTFLAG_ACKED;
4114 * Following the suggestion of Phil Kern, we back off the peer's
4115 * timeout value for future packets until a successful response
4116 * is received for an initial transmission.
4118 if (missing && !peer->backedOff) {
4119 struct clock c = peer->timeout;
4120 struct clock max_to = {3, 0};
4122 clock_Add(&peer->timeout, &c);
4123 if (clock_Gt(&peer->timeout, &max_to))
4124 peer->timeout = max_to;
4125 peer->backedOff = 1;
4128 /* If packet isn't yet acked, and it has been transmitted at least
4129 * once, reset retransmit time using latest timeout
4130 * ie, this should readjust the retransmit timer for all outstanding
4131 * packets... So we don't just retransmit when we should know better*/
4133 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4134 tp->retryTime = tp->timeSent;
4135 clock_Add(&tp->retryTime, &peer->timeout);
4136 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4137 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4141 /* If the window has been extended by this acknowledge packet,
4142 * then wakeup a sender waiting in alloc for window space, or try
4143 * sending packets now, if he's been sitting on packets due to
4144 * lack of window space */
4145 if (call->tnext < (call->tfirst + call->twind)) {
4146 #ifdef RX_ENABLE_LOCKS
4147 CV_SIGNAL(&call->cv_twind);
4149 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4150 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4151 osi_rxWakeup(&call->twind);
4154 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4155 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4159 /* if the ack packet has a receivelen field hanging off it,
4160 * update our state */
4161 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4164 /* If the ack packet has a "recommended" size that is less than
4165 * what I am using now, reduce my size to match */
4166 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4167 (int)sizeof(afs_int32), &tSize);
4168 tSize = (afs_uint32) ntohl(tSize);
4169 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4171 /* Get the maximum packet size to send to this peer */
4172 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4174 tSize = (afs_uint32) ntohl(tSize);
4175 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4176 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4178 /* sanity check - peer might have restarted with different params.
4179 * If peer says "send less", dammit, send less... Peer should never
4180 * be unable to accept packets of the size that prior AFS versions would
4181 * send without asking. */
4182 if (peer->maxMTU != tSize) {
4183 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4185 peer->maxMTU = tSize;
4186 peer->MTU = MIN(tSize, peer->MTU);
4187 call->MTU = MIN(call->MTU, tSize);
4190 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4193 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4194 (int)sizeof(afs_int32), &tSize);
4195 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4196 if (tSize < call->twind) { /* smaller than our send */
4197 call->twind = tSize; /* window, we must send less... */
4198 call->ssthresh = MIN(call->twind, call->ssthresh);
4199 call->conn->twind[call->channel] = call->twind;
4202 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4203 * network MTU confused with the loopback MTU. Calculate the
4204 * maximum MTU here for use in the slow start code below.
4206 /* Did peer restart with older RX version? */
4207 if (peer->maxDgramPackets > 1) {
4208 peer->maxDgramPackets = 1;
4210 } else if (np->length >=
4211 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4214 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4215 sizeof(afs_int32), &tSize);
4216 tSize = (afs_uint32) ntohl(tSize);
4218 * As of AFS 3.5 we set the send window to match the receive window.
4220 if (tSize < call->twind) {
4221 call->twind = tSize;
4222 call->conn->twind[call->channel] = call->twind;
4223 call->ssthresh = MIN(call->twind, call->ssthresh);
4224 } else if (tSize > call->twind) {
4225 call->twind = tSize;
4226 call->conn->twind[call->channel] = call->twind;
4230 * As of AFS 3.5, a jumbogram is more than one fixed size
4231 * packet transmitted in a single UDP datagram. If the remote
4232 * MTU is smaller than our local MTU then never send a datagram
4233 * larger than the natural MTU.
4236 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4237 (int)sizeof(afs_int32), &tSize);
4238 maxDgramPackets = (afs_uint32) ntohl(tSize);
4239 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4241 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4242 maxDgramPackets = MIN(maxDgramPackets, tSize);
4243 if (maxDgramPackets > 1) {
4244 peer->maxDgramPackets = maxDgramPackets;
4245 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4247 peer->maxDgramPackets = 1;
4248 call->MTU = peer->natMTU;
4250 } else if (peer->maxDgramPackets > 1) {
4251 /* Restarted with lower version of RX */
4252 peer->maxDgramPackets = 1;
4254 } else if (peer->maxDgramPackets > 1
4255 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4256 /* Restarted with lower version of RX */
4257 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4258 peer->natMTU = OLD_MAX_PACKET_SIZE;
4259 peer->MTU = OLD_MAX_PACKET_SIZE;
4260 peer->maxDgramPackets = 1;
4261 peer->nDgramPackets = 1;
4263 call->MTU = OLD_MAX_PACKET_SIZE;
4268 * Calculate how many datagrams were successfully received after
4269 * the first missing packet and adjust the negative ack counter
4274 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4275 if (call->nNacks < nNacked) {
4276 call->nNacks = nNacked;
4279 call->nAcks += newAckCount;
4283 if (call->flags & RX_CALL_FAST_RECOVER) {
4285 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4287 call->flags &= ~RX_CALL_FAST_RECOVER;
4288 call->cwind = call->nextCwind;
4289 call->nextCwind = 0;
4292 call->nCwindAcks = 0;
4293 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4294 /* Three negative acks in a row trigger congestion recovery */
4295 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4296 MUTEX_EXIT(&peer->peer_lock);
4297 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4298 /* someone else is waiting to start recovery */
4301 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4302 rxi_WaitforTQBusy(call);
4303 MUTEX_ENTER(&peer->peer_lock);
4304 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4305 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4306 call->flags |= RX_CALL_FAST_RECOVER;
4307 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4309 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4310 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4311 call->nextCwind = call->ssthresh;
4314 peer->MTU = call->MTU;
4315 peer->cwind = call->nextCwind;
4316 peer->nDgramPackets = call->nDgramPackets;
4318 call->congestSeq = peer->congestSeq;
4319 /* Reset the resend times on the packets that were nacked
4320 * so we will retransmit as soon as the window permits*/
4321 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4323 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4324 clock_Zero(&tp->retryTime);
4326 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4331 /* If cwind is smaller than ssthresh, then increase
4332 * the window one packet for each ack we receive (exponential
4334 * If cwind is greater than or equal to ssthresh then increase
4335 * the congestion window by one packet for each cwind acks we
4336 * receive (linear growth). */
4337 if (call->cwind < call->ssthresh) {
4339 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4340 call->nCwindAcks = 0;
4342 call->nCwindAcks += newAckCount;
4343 if (call->nCwindAcks >= call->cwind) {
4344 call->nCwindAcks = 0;
4345 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4349 * If we have received several acknowledgements in a row then
4350 * it is time to increase the size of our datagrams
4352 if ((int)call->nAcks > rx_nDgramThreshold) {
4353 if (peer->maxDgramPackets > 1) {
4354 if (call->nDgramPackets < peer->maxDgramPackets) {
4355 call->nDgramPackets++;
4357 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4358 } else if (call->MTU < peer->maxMTU) {
4359 /* don't upgrade if we can't handle it */
4360 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4361 call->MTU = peer->ifMTU;
4363 call->MTU += peer->natMTU;
4364 call->MTU = MIN(call->MTU, peer->maxMTU);
4371 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4373 /* Servers need to hold the call until all response packets have
4374 * been acknowledged. Soft acks are good enough since clients
4375 * are not allowed to clear their receive queues. */
4376 if (call->state == RX_STATE_HOLD
4377 && call->tfirst + call->nSoftAcked >= call->tnext) {
4378 call->state = RX_STATE_DALLY;
4379 rxi_ClearTransmitQueue(call, 0);
4380 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4381 } else if (!queue_IsEmpty(&call->tq)) {
4382 rxi_Start(0, call, 0, istack);
4387 /* Received a response to a challenge packet */
4389 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4390 struct rx_packet *np, int istack)
4394 /* Ignore the packet if we're the client */
4395 if (conn->type == RX_CLIENT_CONNECTION)
4398 /* If already authenticated, ignore the packet (it's probably a retry) */
4399 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4402 /* Otherwise, have the security object evaluate the response packet */
4403 error = RXS_CheckResponse(conn->securityObject, conn, np);
4405 /* If the response is invalid, reset the connection, sending
4406 * an abort to the peer */
4410 rxi_ConnectionError(conn, error);
4411 MUTEX_ENTER(&conn->conn_data_lock);
4412 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4413 MUTEX_EXIT(&conn->conn_data_lock);
4416 /* If the response is valid, any calls waiting to attach
4417 * servers can now do so */
4420 for (i = 0; i < RX_MAXCALLS; i++) {
4421 struct rx_call *call = conn->call[i];
4423 MUTEX_ENTER(&call->lock);
4424 if (call->state == RX_STATE_PRECALL)
4425 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4426 /* tnop can be null if newcallp is null */
4427 MUTEX_EXIT(&call->lock);
4431 /* Update the peer reachability information, just in case
4432 * some calls went into attach-wait while we were waiting
4433 * for authentication..
4435 rxi_UpdatePeerReach(conn, NULL);
4440 /* A client has received an authentication challenge: the security
4441 * object is asked to cough up a respectable response packet to send
4442 * back to the server. The server is responsible for retrying the
4443 * challenge if it fails to get a response. */
4446 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4447 struct rx_packet *np, int istack)
4451 /* Ignore the challenge if we're the server */
4452 if (conn->type == RX_SERVER_CONNECTION)
4455 /* Ignore the challenge if the connection is otherwise idle; someone's
4456 * trying to use us as an oracle. */
4457 if (!rxi_HasActiveCalls(conn))
4460 /* Send the security object the challenge packet. It is expected to fill
4461 * in the response. */
4462 error = RXS_GetResponse(conn->securityObject, conn, np);
4464 /* If the security object is unable to return a valid response, reset the
4465 * connection and send an abort to the peer. Otherwise send the response
4466 * packet to the peer connection. */
4468 rxi_ConnectionError(conn, error);
4469 MUTEX_ENTER(&conn->conn_data_lock);
4470 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4471 MUTEX_EXIT(&conn->conn_data_lock);
4473 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4474 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4480 /* Find an available server process to service the current request in
4481 * the given call structure. If one isn't available, queue up this
4482 * call so it eventually gets one */
4484 rxi_AttachServerProc(struct rx_call *call,
4485 osi_socket socket, int *tnop,
4486 struct rx_call **newcallp)
4488 struct rx_serverQueueEntry *sq;
4489 struct rx_service *service = call->conn->service;
4492 /* May already be attached */
4493 if (call->state == RX_STATE_ACTIVE)
4496 MUTEX_ENTER(&rx_serverPool_lock);
4498 haveQuota = QuotaOK(service);
4499 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4500 /* If there are no processes available to service this call,
4501 * put the call on the incoming call queue (unless it's
4502 * already on the queue).
4504 #ifdef RX_ENABLE_LOCKS
4506 ReturnToServerPool(service);
4507 #endif /* RX_ENABLE_LOCKS */
4509 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4510 call->flags |= RX_CALL_WAIT_PROC;
4511 rx_atomic_inc(&rx_nWaiting);
4512 rx_atomic_inc(&rx_nWaited);
4513 rxi_calltrace(RX_CALL_ARRIVAL, call);
4514 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4515 queue_Append(&rx_incomingCallQueue, call);
4518 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4520 /* If hot threads are enabled, and both newcallp and sq->socketp
4521 * are non-null, then this thread will process the call, and the
4522 * idle server thread will start listening on this threads socket.
4525 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4528 *sq->socketp = socket;
4529 clock_GetTime(&call->startTime);
4530 MUTEX_ENTER(&rx_refcnt_mutex);
4531 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4532 MUTEX_EXIT(&rx_refcnt_mutex);
4536 if (call->flags & RX_CALL_WAIT_PROC) {
4537 /* Conservative: I don't think this should happen */
4538 call->flags &= ~RX_CALL_WAIT_PROC;
4539 if (queue_IsOnQueue(call)) {
4542 rx_atomic_dec(&rx_nWaiting);
4545 call->state = RX_STATE_ACTIVE;
4546 call->mode = RX_MODE_RECEIVING;
4547 #ifdef RX_KERNEL_TRACE
4549 int glockOwner = ISAFS_GLOCK();
4552 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4553 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4559 if (call->flags & RX_CALL_CLEARED) {
4560 /* send an ack now to start the packet flow up again */
4561 call->flags &= ~RX_CALL_CLEARED;
4562 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4564 #ifdef RX_ENABLE_LOCKS
4567 service->nRequestsRunning++;
4568 MUTEX_ENTER(&rx_quota_mutex);
4569 if (service->nRequestsRunning <= service->minProcs)
4572 MUTEX_EXIT(&rx_quota_mutex);
4576 MUTEX_EXIT(&rx_serverPool_lock);
4579 /* Delay the sending of an acknowledge event for a short while, while
4580 * a new call is being prepared (in the case of a client) or a reply
4581 * is being prepared (in the case of a server). Rather than sending
4582 * an ack packet, an ACKALL packet is sent. */
4584 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4586 #ifdef RX_ENABLE_LOCKS
4588 MUTEX_ENTER(&call->lock);
4589 call->delayedAckEvent = NULL;
4590 MUTEX_ENTER(&rx_refcnt_mutex);
4591 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4592 MUTEX_EXIT(&rx_refcnt_mutex);
4594 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4595 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4597 MUTEX_EXIT(&call->lock);
4598 #else /* RX_ENABLE_LOCKS */
4600 call->delayedAckEvent = NULL;
4601 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4602 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4603 #endif /* RX_ENABLE_LOCKS */
4607 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4609 struct rx_call *call = arg1;
4610 #ifdef RX_ENABLE_LOCKS
4612 MUTEX_ENTER(&call->lock);
4613 if (event == call->delayedAckEvent)
4614 call->delayedAckEvent = NULL;
4615 MUTEX_ENTER(&rx_refcnt_mutex);
4616 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4617 MUTEX_EXIT(&rx_refcnt_mutex);
4619 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4621 MUTEX_EXIT(&call->lock);
4622 #else /* RX_ENABLE_LOCKS */
4624 call->delayedAckEvent = NULL;
4625 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4626 #endif /* RX_ENABLE_LOCKS */
4630 #ifdef RX_ENABLE_LOCKS
4631 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4632 * clearing them out.
4635 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4637 struct rx_packet *p, *tp;
4640 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4641 p->flags |= RX_PKTFLAG_ACKED;
4645 call->flags |= RX_CALL_TQ_CLEARME;
4646 call->flags |= RX_CALL_TQ_SOME_ACKED;
4649 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4650 call->tfirst = call->tnext;
4651 call->nSoftAcked = 0;
4653 if (call->flags & RX_CALL_FAST_RECOVER) {
4654 call->flags &= ~RX_CALL_FAST_RECOVER;
4655 call->cwind = call->nextCwind;
4656 call->nextCwind = 0;
4659 CV_SIGNAL(&call->cv_twind);
4661 #endif /* RX_ENABLE_LOCKS */
4663 /* Clear out the transmit queue for the current call (all packets have
4664 * been received by peer) */
4666 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4668 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4669 struct rx_packet *p, *tp;
4671 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4673 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4674 p->flags |= RX_PKTFLAG_ACKED;
4678 call->flags |= RX_CALL_TQ_CLEARME;
4679 call->flags |= RX_CALL_TQ_SOME_ACKED;
4682 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4683 #ifdef RXDEBUG_PACKET
4685 #endif /* RXDEBUG_PACKET */
4686 rxi_FreePackets(0, &call->tq);
4687 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
4688 #ifdef RX_ENABLE_LOCKS
4689 CV_BROADCAST(&call->cv_tq);
4690 #else /* RX_ENABLE_LOCKS */
4691 osi_rxWakeup(&call->tq);
4692 #endif /* RX_ENABLE_LOCKS */
4694 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4695 call->flags &= ~RX_CALL_TQ_CLEARME;
4697 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4699 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4700 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4701 call->nSoftAcked = 0;
4703 if (call->flags & RX_CALL_FAST_RECOVER) {
4704 call->flags &= ~RX_CALL_FAST_RECOVER;
4705 call->cwind = call->nextCwind;
4707 #ifdef RX_ENABLE_LOCKS
4708 CV_SIGNAL(&call->cv_twind);
4710 osi_rxWakeup(&call->twind);
4715 rxi_ClearReceiveQueue(struct rx_call *call)
4717 if (queue_IsNotEmpty(&call->rq)) {
4720 count = rxi_FreePackets(0, &call->rq);
4721 rx_packetReclaims += count;
4722 #ifdef RXDEBUG_PACKET
4724 if ( call->rqc != 0 )
4725 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0", call, call->rqc));
4727 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4729 if (call->state == RX_STATE_PRECALL) {
4730 call->flags |= RX_CALL_CLEARED;
4734 /* Send an abort packet for the specified call */
4736 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4737 int istack, int force)
4740 struct clock when, now;
4745 /* Clients should never delay abort messages */
4746 if (rx_IsClientConn(call->conn))
4749 if (call->abortCode != call->error) {
4750 call->abortCode = call->error;
4751 call->abortCount = 0;
4754 if (force || rxi_callAbortThreshhold == 0
4755 || call->abortCount < rxi_callAbortThreshhold) {
4756 if (call->delayedAbortEvent) {
4757 rxevent_Cancel(call->delayedAbortEvent, call,
4758 RX_CALL_REFCOUNT_ABORT);
4760 error = htonl(call->error);
4763 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4764 (char *)&error, sizeof(error), istack);
4765 } else if (!call->delayedAbortEvent) {
4766 clock_GetTime(&now);
4768 clock_Addmsec(&when, rxi_callAbortDelay);
4769 MUTEX_ENTER(&rx_refcnt_mutex);
4770 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4771 MUTEX_EXIT(&rx_refcnt_mutex);
4772 call->delayedAbortEvent =
4773 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4778 /* Send an abort packet for the specified connection. Packet is an
4779 * optional pointer to a packet that can be used to send the abort.
4780 * Once the number of abort messages reaches the threshhold, an
4781 * event is scheduled to send the abort. Setting the force flag
4782 * overrides sending delayed abort messages.
4784 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4785 * to send the abort packet.
4788 rxi_SendConnectionAbort(struct rx_connection *conn,
4789 struct rx_packet *packet, int istack, int force)
4792 struct clock when, now;
4797 /* Clients should never delay abort messages */
4798 if (rx_IsClientConn(conn))
4801 if (force || rxi_connAbortThreshhold == 0
4802 || conn->abortCount < rxi_connAbortThreshhold) {
4803 if (conn->delayedAbortEvent) {
4804 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4806 error = htonl(conn->error);
4808 MUTEX_EXIT(&conn->conn_data_lock);
4810 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4811 RX_PACKET_TYPE_ABORT, (char *)&error,
4812 sizeof(error), istack);
4813 MUTEX_ENTER(&conn->conn_data_lock);
4814 } else if (!conn->delayedAbortEvent) {
4815 clock_GetTime(&now);
4817 clock_Addmsec(&when, rxi_connAbortDelay);
4818 conn->delayedAbortEvent =
4819 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4824 /* Associate an error all of the calls owned by a connection. Called
4825 * with error non-zero. This is only for really fatal things, like
4826 * bad authentication responses. The connection itself is set in
4827 * error at this point, so that future packets received will be
4830 rxi_ConnectionError(struct rx_connection *conn,
4836 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d", conn, error));
4838 MUTEX_ENTER(&conn->conn_data_lock);
4839 if (conn->challengeEvent)
4840 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4841 if (conn->natKeepAliveEvent)
4842 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
4843 if (conn->checkReachEvent) {
4844 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4845 conn->checkReachEvent = 0;
4846 conn->flags &= ~RX_CONN_ATTACHWAIT;
4847 MUTEX_ENTER(&rx_refcnt_mutex);
4849 MUTEX_EXIT(&rx_refcnt_mutex);
4851 MUTEX_EXIT(&conn->conn_data_lock);
4852 for (i = 0; i < RX_MAXCALLS; i++) {
4853 struct rx_call *call = conn->call[i];
4855 MUTEX_ENTER(&call->lock);
4856 rxi_CallError(call, error);
4857 MUTEX_EXIT(&call->lock);
4860 conn->error = error;
4861 if (rx_stats_active)
4862 rx_atomic_inc(&rx_stats.fatalErrors);
4867 rxi_CallError(struct rx_call *call, afs_int32 error)
4870 osirx_AssertMine(&call->lock, "rxi_CallError");
4872 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d", call, error, call->error));
4874 error = call->error;
4876 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4877 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4878 rxi_ResetCall(call, 0);
4881 rxi_ResetCall(call, 0);
4883 call->error = error;
4884 call->mode = RX_MODE_ERROR;
4887 /* Reset various fields in a call structure, and wakeup waiting
4888 * processes. Some fields aren't changed: state & mode are not
4889 * touched (these must be set by the caller), and bufptr, nLeft, and
4890 * nFree are not reset, since these fields are manipulated by
4891 * unprotected macros, and may only be reset by non-interrupting code.
4894 /* this code requires that call->conn be set properly as a pre-condition. */
4895 #endif /* ADAPT_WINDOW */
4898 rxi_ResetCall(struct rx_call *call, int newcall)
4901 struct rx_peer *peer;
4902 struct rx_packet *packet;
4904 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4906 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
4908 /* Notify anyone who is waiting for asynchronous packet arrival */
4909 if (call->arrivalProc) {
4910 (*call->arrivalProc) (call, call->arrivalProcHandle,
4911 call->arrivalProcArg);
4912 call->arrivalProc = (void (*)())0;
4915 if (call->delayedAbortEvent) {
4916 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4917 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4919 rxi_SendCallAbort(call, packet, 0, 1);
4920 rxi_FreePacket(packet);
4925 * Update the peer with the congestion information in this call
4926 * so other calls on this connection can pick up where this call
4927 * left off. If the congestion sequence numbers don't match then
4928 * another call experienced a retransmission.
4930 peer = call->conn->peer;
4931 MUTEX_ENTER(&peer->peer_lock);
4933 if (call->congestSeq == peer->congestSeq) {
4934 peer->cwind = MAX(peer->cwind, call->cwind);
4935 peer->MTU = MAX(peer->MTU, call->MTU);
4936 peer->nDgramPackets =
4937 MAX(peer->nDgramPackets, call->nDgramPackets);
4940 call->abortCode = 0;
4941 call->abortCount = 0;
4943 if (peer->maxDgramPackets > 1) {
4944 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4946 call->MTU = peer->MTU;
4948 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4949 call->ssthresh = rx_maxSendWindow;
4950 call->nDgramPackets = peer->nDgramPackets;
4951 call->congestSeq = peer->congestSeq;
4952 MUTEX_EXIT(&peer->peer_lock);
4954 flags = call->flags;
4955 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4956 rxi_WaitforTQBusy(call);
4957 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4959 rxi_ClearTransmitQueue(call, 1);
4960 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4961 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4965 rxi_ClearReceiveQueue(call);
4966 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4970 call->twind = call->conn->twind[call->channel];
4971 call->rwind = call->conn->rwind[call->channel];
4972 call->nSoftAcked = 0;
4973 call->nextCwind = 0;
4976 call->nCwindAcks = 0;
4977 call->nSoftAcks = 0;
4978 call->nHardAcks = 0;
4980 call->tfirst = call->rnext = call->tnext = 1;
4982 call->lastAcked = 0;
4983 call->localStatus = call->remoteStatus = 0;
4985 if (flags & RX_CALL_READER_WAIT) {
4986 #ifdef RX_ENABLE_LOCKS
4987 CV_BROADCAST(&call->cv_rq);
4989 osi_rxWakeup(&call->rq);
4992 if (flags & RX_CALL_WAIT_PACKETS) {
4993 MUTEX_ENTER(&rx_freePktQ_lock);
4994 rxi_PacketsUnWait(); /* XXX */
4995 MUTEX_EXIT(&rx_freePktQ_lock);
4997 #ifdef RX_ENABLE_LOCKS
4998 CV_SIGNAL(&call->cv_twind);
5000 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5001 osi_rxWakeup(&call->twind);
5004 #ifdef RX_ENABLE_LOCKS
5005 /* The following ensures that we don't mess with any queue while some
5006 * other thread might also be doing so. The call_queue_lock field is
5007 * is only modified under the call lock. If the call is in the process
5008 * of being removed from a queue, the call is not locked until the
5009 * the queue lock is dropped and only then is the call_queue_lock field
5010 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5011 * Note that any other routine which removes a call from a queue has to
5012 * obtain the queue lock before examing the queue and removing the call.
5014 if (call->call_queue_lock) {
5015 MUTEX_ENTER(call->call_queue_lock);
5016 if (queue_IsOnQueue(call)) {
5018 if (flags & RX_CALL_WAIT_PROC) {
5019 rx_atomic_dec(&rx_nWaiting);
5022 MUTEX_EXIT(call->call_queue_lock);
5023 CLEAR_CALL_QUEUE_LOCK(call);
5025 #else /* RX_ENABLE_LOCKS */
5026 if (queue_IsOnQueue(call)) {
5028 if (flags & RX_CALL_WAIT_PROC)
5029 rx_atomic_dec(&rx_nWaiting);
5031 #endif /* RX_ENABLE_LOCKS */
5033 rxi_KeepAliveOff(call);
5034 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5037 /* Send an acknowledge for the indicated packet (seq,serial) of the
5038 * indicated call, for the indicated reason (reason). This
5039 * acknowledge will specifically acknowledge receiving the packet, and
5040 * will also specify which other packets for this call have been
5041 * received. This routine returns the packet that was used to the
5042 * caller. The caller is responsible for freeing it or re-using it.
5043 * This acknowledgement also returns the highest sequence number
5044 * actually read out by the higher level to the sender; the sender
5045 * promises to keep around packets that have not been read by the
5046 * higher level yet (unless, of course, the sender decides to abort
5047 * the call altogether). Any of p, seq, serial, pflags, or reason may
5048 * be set to zero without ill effect. That is, if they are zero, they
5049 * will not convey any information.
5050 * NOW there is a trailer field, after the ack where it will safely be
5051 * ignored by mundanes, which indicates the maximum size packet this
5052 * host can swallow. */
5054 struct rx_packet *optionalPacket; use to send ack (or null)
5055 int seq; Sequence number of the packet we are acking
5056 int serial; Serial number of the packet
5057 int pflags; Flags field from packet header
5058 int reason; Reason an acknowledge was prompted
5062 rxi_SendAck(struct rx_call *call,
5063 struct rx_packet *optionalPacket, int serial, int reason,
5066 struct rx_ackPacket *ap;
5067 struct rx_packet *rqp;
5068 struct rx_packet *nxp; /* For queue_Scan */
5069 struct rx_packet *p;
5072 afs_uint32 padbytes = 0;
5073 #ifdef RX_ENABLE_TSFPQ
5074 struct rx_ts_info_t * rx_ts_info;
5078 * Open the receive window once a thread starts reading packets
5080 if (call->rnext > 1) {
5081 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5084 /* Don't attempt to grow MTU if this is a critical ping */
5085 if (reason == RX_ACK_MTU) {
5086 /* keep track of per-call attempts, if we're over max, do in small
5087 * otherwise in larger? set a size to increment by, decrease
5090 if (call->conn->peer->maxPacketSize &&
5091 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5093 padbytes = call->conn->peer->maxPacketSize+16;
5095 padbytes = call->conn->peer->maxMTU + 128;
5097 /* do always try a minimum size ping */
5098 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5100 /* subtract the ack payload */
5101 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5102 reason = RX_ACK_PING;
5105 call->nHardAcks = 0;
5106 call->nSoftAcks = 0;
5107 if (call->rnext > call->lastAcked)
5108 call->lastAcked = call->rnext;
5112 rx_computelen(p, p->length); /* reset length, you never know */
5113 } /* where that's been... */
5114 #ifdef RX_ENABLE_TSFPQ
5116 RX_TS_INFO_GET(rx_ts_info);
5117 if ((p = rx_ts_info->local_special_packet)) {
5118 rx_computelen(p, p->length);
5119 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5120 rx_ts_info->local_special_packet = p;
5121 } else { /* We won't send the ack, but don't panic. */
5122 return optionalPacket;
5126 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5127 /* We won't send the ack, but don't panic. */
5128 return optionalPacket;
5133 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5136 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5137 #ifndef RX_ENABLE_TSFPQ
5138 if (!optionalPacket)
5141 return optionalPacket;
5143 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5144 if (rx_Contiguous(p) < templ) {
5145 #ifndef RX_ENABLE_TSFPQ
5146 if (!optionalPacket)
5149 return optionalPacket;
5154 /* MTUXXX failing to send an ack is very serious. We should */
5155 /* try as hard as possible to send even a partial ack; it's */
5156 /* better than nothing. */
5157 ap = (struct rx_ackPacket *)rx_DataOf(p);
5158 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5159 ap->reason = reason;
5161 /* The skew computation used to be bogus, I think it's better now. */
5162 /* We should start paying attention to skew. XXX */
5163 ap->serial = htonl(serial);
5164 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5166 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5167 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5169 /* No fear of running out of ack packet here because there can only be at most
5170 * one window full of unacknowledged packets. The window size must be constrained
5171 * to be less than the maximum ack size, of course. Also, an ack should always
5172 * fit into a single packet -- it should not ever be fragmented. */
5173 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5174 if (!rqp || !call->rq.next
5175 || (rqp->header.seq > (call->rnext + call->rwind))) {
5176 #ifndef RX_ENABLE_TSFPQ
5177 if (!optionalPacket)
5180 rxi_CallError(call, RX_CALL_DEAD);
5181 return optionalPacket;
5184 while (rqp->header.seq > call->rnext + offset)
5185 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5186 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5188 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5189 #ifndef RX_ENABLE_TSFPQ
5190 if (!optionalPacket)
5193 rxi_CallError(call, RX_CALL_DEAD);
5194 return optionalPacket;
5199 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5201 /* these are new for AFS 3.3 */
5202 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5203 templ = htonl(templ);
5204 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5205 templ = htonl(call->conn->peer->ifMTU);
5206 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5207 sizeof(afs_int32), &templ);
5209 /* new for AFS 3.4 */
5210 templ = htonl(call->rwind);
5211 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5212 sizeof(afs_int32), &templ);
5214 /* new for AFS 3.5 */
5215 templ = htonl(call->conn->peer->ifDgramPackets);
5216 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5217 sizeof(afs_int32), &templ);
5219 p->header.serviceId = call->conn->serviceId;
5220 p->header.cid = (call->conn->cid | call->channel);
5221 p->header.callNumber = *call->callNumber;
5223 p->header.securityIndex = call->conn->securityIndex;
5224 p->header.epoch = call->conn->epoch;
5225 p->header.type = RX_PACKET_TYPE_ACK;
5226 p->header.flags = RX_SLOW_START_OK;
5227 if (reason == RX_ACK_PING) {
5228 p->header.flags |= RX_REQUEST_ACK;
5230 clock_GetTime(&call->pingRequestTime);
5233 p->length = padbytes +
5234 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5237 /* not fast but we can potentially use this if truncated
5238 * fragments are delivered to figure out the mtu.
5240 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5241 sizeof(afs_int32), sizeof(afs_int32),
5245 if (call->conn->type == RX_CLIENT_CONNECTION)
5246 p->header.flags |= RX_CLIENT_INITIATED;
5250 if (rxdebug_active) {
5254 len = _snprintf(msg, sizeof(msg),
5255 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5256 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5257 ntohl(ap->serial), ntohl(ap->previousPacket),
5258 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5259 ap->nAcks, ntohs(ap->bufferSpace) );
5263 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5264 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5268 OutputDebugString(msg);
5270 #else /* AFS_NT40_ENV */
5272 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5273 ap->reason, ntohl(ap->previousPacket),
5274 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5276 for (offset = 0; offset < ap->nAcks; offset++)
5277 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5282 #endif /* AFS_NT40_ENV */
5285 int i, nbytes = p->length;
5287 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5288 if (nbytes <= p->wirevec[i].iov_len) {
5291 savelen = p->wirevec[i].iov_len;
5293 p->wirevec[i].iov_len = nbytes;
5295 rxi_Send(call, p, istack);
5296 p->wirevec[i].iov_len = savelen;
5300 nbytes -= p->wirevec[i].iov_len;
5303 if (rx_stats_active)
5304 rx_atomic_inc(&rx_stats.ackPacketsSent);
5305 #ifndef RX_ENABLE_TSFPQ
5306 if (!optionalPacket)
5309 return optionalPacket; /* Return packet for re-use by caller */
5312 /* Send all of the packets in the list in single datagram */
5314 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5315 int istack, int moreFlag, struct clock *now,
5316 struct clock *retryTime, int resending)
5321 struct rx_connection *conn = call->conn;
5322 struct rx_peer *peer = conn->peer;
5324 MUTEX_ENTER(&peer->peer_lock);
5327 peer->reSends += len;
5328 MUTEX_EXIT(&peer->peer_lock);
5330 if (rx_stats_active) {
5332 rx_atomic_add(&rx_stats.dataPacketsReSent, len);
5334 rx_atomic_add(&rx_stats.dataPacketsSent, len);
5337 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5341 /* Set the packet flags and schedule the resend events */
5342 /* Only request an ack for the last packet in the list */
5343 for (i = 0; i < len; i++) {
5344 list[i]->retryTime = *retryTime;
5345 if (list[i]->header.serial) {
5346 /* Exponentially backoff retry times */
5347 if (list[i]->backoff < MAXBACKOFF) {
5348 /* so it can't stay == 0 */
5349 list[i]->backoff = (list[i]->backoff << 1) + 1;
5352 clock_Addmsec(&(list[i]->retryTime),
5353 ((afs_uint32) list[i]->backoff) << 8);
5356 /* Wait a little extra for the ack on the last packet */
5357 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5358 clock_Addmsec(&(list[i]->retryTime), 400);
5361 /* Record the time sent */
5362 list[i]->timeSent = *now;
5364 /* Ask for an ack on retransmitted packets, on every other packet
5365 * if the peer doesn't support slow start. Ask for an ack on every
5366 * packet until the congestion window reaches the ack rate. */
5367 if (list[i]->header.serial) {
5370 /* improved RTO calculation- not Karn */
5371 list[i]->firstSent = *now;
5372 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5373 || (!(call->flags & RX_CALL_SLOW_START_OK)
5374 && (list[i]->header.seq & 1)))) {
5379 /* Tag this packet as not being the last in this group,
5380 * for the receiver's benefit */
5381 if (i < len - 1 || moreFlag) {
5382 list[i]->header.flags |= RX_MORE_PACKETS;
5385 /* Install the new retransmit time for the packet, and
5386 * record the time sent */
5387 list[i]->timeSent = *now;
5391 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5394 /* Since we're about to send a data packet to the peer, it's
5395 * safe to nuke any scheduled end-of-packets ack */
5396 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5398 MUTEX_EXIT(&call->lock);
5399 MUTEX_ENTER(&rx_refcnt_mutex);
5400 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5401 MUTEX_EXIT(&rx_refcnt_mutex);
5403 rxi_SendPacketList(call, conn, list, len, istack);
5405 rxi_SendPacket(call, conn, list[0], istack);
5407 MUTEX_ENTER(&call->lock);
5408 MUTEX_ENTER(&rx_refcnt_mutex);
5409 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5410 MUTEX_EXIT(&rx_refcnt_mutex);
5412 /* Update last send time for this call (for keep-alive
5413 * processing), and for the connection (so that we can discover
5414 * idle connections) */
5415 conn->lastSendTime = call->lastSendTime = clock_Sec();
5416 /* Let a set of retransmits trigger an idle timeout */
5418 call->lastSendData = call->lastSendTime;
5421 /* When sending packets we need to follow these rules:
5422 * 1. Never send more than maxDgramPackets in a jumbogram.
5423 * 2. Never send a packet with more than two iovecs in a jumbogram.
5424 * 3. Never send a retransmitted packet in a jumbogram.
5425 * 4. Never send more than cwind/4 packets in a jumbogram
5426 * We always keep the last list we should have sent so we
5427 * can set the RX_MORE_PACKETS flags correctly.
5430 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5431 int istack, struct clock *now, struct clock *retryTime,
5434 int i, cnt, lastCnt = 0;
5435 struct rx_packet **listP, **lastP = 0;
5436 struct rx_peer *peer = call->conn->peer;
5437 int morePackets = 0;
5439 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5440 /* Does the current packet force us to flush the current list? */
5442 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5443 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5445 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5447 /* If the call enters an error state stop sending, or if
5448 * we entered congestion recovery mode, stop sending */
5449 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5457 /* Add the current packet to the list if it hasn't been acked.
5458 * Otherwise adjust the list pointer to skip the current packet. */
5459 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5461 /* Do we need to flush the list? */
5462 if (cnt >= (int)peer->maxDgramPackets
5463 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5464 || list[i]->header.serial
5465 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5467 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5468 retryTime, resending);
5469 /* If the call enters an error state stop sending, or if
5470 * we entered congestion recovery mode, stop sending */
5472 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5477 listP = &list[i + 1];
5482 osi_Panic("rxi_SendList error");
5484 listP = &list[i + 1];
5488 /* Send the whole list when the call is in receive mode, when
5489 * the call is in eof mode, when we are in fast recovery mode,
5490 * and when we have the last packet */
5491 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5492 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5493 || (call->flags & RX_CALL_FAST_RECOVER)) {
5494 /* Check for the case where the current list contains
5495 * an acked packet. Since we always send retransmissions
5496 * in a separate packet, we only need to check the first
5497 * packet in the list */
5498 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5502 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5503 retryTime, resending);
5504 /* If the call enters an error state stop sending, or if
5505 * we entered congestion recovery mode, stop sending */
5506 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5510 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5513 } else if (lastCnt > 0) {
5514 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5519 #ifdef RX_ENABLE_LOCKS
5520 /* Call rxi_Start, below, but with the call lock held. */
5522 rxi_StartUnlocked(struct rxevent *event,
5523 void *arg0, void *arg1, int istack)
5525 struct rx_call *call = arg0;
5527 MUTEX_ENTER(&call->lock);
5528 rxi_Start(event, call, arg1, istack);
5529 MUTEX_EXIT(&call->lock);
5531 #endif /* RX_ENABLE_LOCKS */
5533 /* This routine is called when new packets are readied for
5534 * transmission and when retransmission may be necessary, or when the
5535 * transmission window or burst count are favourable. This should be
5536 * better optimized for new packets, the usual case, now that we've
5537 * got rid of queues of send packets. XXXXXXXXXXX */
5539 rxi_Start(struct rxevent *event,
5540 void *arg0, void *arg1, int istack)
5542 struct rx_call *call = arg0;
5544 struct rx_packet *p;
5545 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5546 struct rx_peer *peer = call->conn->peer;
5547 struct clock now, usenow, retryTime;
5551 struct rx_packet **xmitList;
5554 /* If rxi_Start is being called as a result of a resend event,
5555 * then make sure that the event pointer is removed from the call
5556 * structure, since there is no longer a per-call retransmission
5558 if (event && event == call->resendEvent) {
5559 MUTEX_ENTER(&rx_refcnt_mutex);
5560 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5561 MUTEX_EXIT(&rx_refcnt_mutex);
5562 call->resendEvent = NULL;
5564 if (queue_IsEmpty(&call->tq)) {
5568 /* Timeouts trigger congestion recovery */
5569 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5570 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5571 /* someone else is waiting to start recovery */
5574 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5575 rxi_WaitforTQBusy(call);
5576 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5577 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5578 call->flags |= RX_CALL_FAST_RECOVER;
5579 if (peer->maxDgramPackets > 1) {
5580 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5582 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5584 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5585 call->nDgramPackets = 1;
5587 call->nextCwind = 1;
5590 MUTEX_ENTER(&peer->peer_lock);
5591 peer->MTU = call->MTU;
5592 peer->cwind = call->cwind;
5593 peer->nDgramPackets = 1;
5595 call->congestSeq = peer->congestSeq;
5596 MUTEX_EXIT(&peer->peer_lock);
5597 /* Clear retry times on packets. Otherwise, it's possible for
5598 * some packets in the queue to force resends at rates faster
5599 * than recovery rates.
5601 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5602 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5603 clock_Zero(&p->retryTime);
5608 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5609 if (rx_stats_active)
5610 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5615 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5616 /* Get clock to compute the re-transmit time for any packets
5617 * in this burst. Note, if we back off, it's reasonable to
5618 * back off all of the packets in the same manner, even if
5619 * some of them have been retransmitted more times than more
5621 * Do a dance to avoid blocking after setting now. */
5622 MUTEX_ENTER(&peer->peer_lock);
5623 retryTime = peer->timeout;
5624 MUTEX_EXIT(&peer->peer_lock);
5626 clock_GetTime(&now);
5627 clock_Add(&retryTime, &now);
5629 /* Send (or resend) any packets that need it, subject to
5630 * window restrictions and congestion burst control
5631 * restrictions. Ask for an ack on the last packet sent in
5632 * this burst. For now, we're relying upon the window being
5633 * considerably bigger than the largest number of packets that
5634 * are typically sent at once by one initial call to
5635 * rxi_Start. This is probably bogus (perhaps we should ask
5636 * for an ack when we're half way through the current
5637 * window?). Also, for non file transfer applications, this
5638 * may end up asking for an ack for every packet. Bogus. XXXX
5641 * But check whether we're here recursively, and let the other guy
5644 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5645 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5646 call->flags |= RX_CALL_TQ_BUSY;
5648 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5650 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5651 call->flags &= ~RX_CALL_NEED_START;
5652 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5654 maxXmitPackets = MIN(call->twind, call->cwind);
5655 xmitList = (struct rx_packet **)
5656 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5657 /* XXXX else we must drop any mtx we hold */
5658 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5660 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5662 if (xmitList == NULL)
5663 osi_Panic("rxi_Start, failed to allocate xmit list");
5664 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5665 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5666 /* We shouldn't be sending packets if a thread is waiting
5667 * to initiate congestion recovery */
5668 dpf(("call %d waiting to initiate fast recovery\n",
5669 *(call->callNumber)));
5673 && (call->flags & RX_CALL_FAST_RECOVER)) {
5674 /* Only send one packet during fast recovery */
5675 dpf(("call %d restricted to one packet per send during fast recovery\n",
5676 *(call->callNumber)));
5679 #ifdef RX_TRACK_PACKETS
5680 if ((p->flags & RX_PKTFLAG_FREE)
5681 || (!queue_IsEnd(&call->tq, nxp)
5682 && (nxp->flags & RX_PKTFLAG_FREE))
5683 || (p == (struct rx_packet *)&rx_freePacketQueue)
5684 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5685 osi_Panic("rxi_Start: xmit queue clobbered");
5688 if (p->flags & RX_PKTFLAG_ACKED) {
5689 /* Since we may block, don't trust this */
5690 usenow.sec = usenow.usec = 0;
5691 if (rx_stats_active)
5692 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5693 continue; /* Ignore this packet if it has been acknowledged */
5696 /* Turn off all flags except these ones, which are the same
5697 * on each transmission */
5698 p->header.flags &= RX_PRESET_FLAGS;
5700 if (p->header.seq >=
5701 call->tfirst + MIN((int)call->twind,
5702 (int)(call->nSoftAcked +
5704 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5705 /* Note: if we're waiting for more window space, we can
5706 * still send retransmits; hence we don't return here, but
5707 * break out to schedule a retransmit event */
5708 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5709 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5714 /* Transmit the packet if it needs to be sent. */
5715 if (!clock_Lt(&now, &p->retryTime)) {
5716 if (nXmitPackets == maxXmitPackets) {
5717 rxi_SendXmitList(call, xmitList, nXmitPackets,
5718 istack, &now, &retryTime,
5720 osi_Free(xmitList, maxXmitPackets *
5721 sizeof(struct rx_packet *));
5724 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u nextRetry %u.%06u\n",
5725 *(call->callNumber), p,
5727 p->retryTime.sec, p->retryTime.usec,
5728 retryTime.sec, retryTime.usec));
5729 xmitList[nXmitPackets++] = p;
5733 /* xmitList now hold pointers to all of the packets that are
5734 * ready to send. Now we loop to send the packets */
5735 if (nXmitPackets > 0) {
5736 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5737 &now, &retryTime, resending);
5740 maxXmitPackets * sizeof(struct rx_packet *));
5742 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5744 * TQ references no longer protected by this flag; they must remain
5745 * protected by the global lock.
5747 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5748 call->flags &= ~RX_CALL_TQ_BUSY;
5749 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5750 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5751 call, call->tqWaiters, call->flags));
5752 #ifdef RX_ENABLE_LOCKS
5753 osirx_AssertMine(&call->lock, "rxi_Start start");
5754 CV_BROADCAST(&call->cv_tq);
5755 #else /* RX_ENABLE_LOCKS */
5756 osi_rxWakeup(&call->tq);
5757 #endif /* RX_ENABLE_LOCKS */
5762 /* We went into the error state while sending packets. Now is
5763 * the time to reset the call. This will also inform the using
5764 * process that the call is in an error state.
5766 if (rx_stats_active)
5767 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
5768 call->flags &= ~RX_CALL_TQ_BUSY;
5769 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5770 dpf(("call error %d while xmit %p has %d waiters and flags %d\n",
5771 call->error, call, call->tqWaiters, call->flags));
5772 #ifdef RX_ENABLE_LOCKS
5773 osirx_AssertMine(&call->lock, "rxi_Start middle");
5774 CV_BROADCAST(&call->cv_tq);
5775 #else /* RX_ENABLE_LOCKS */
5776 osi_rxWakeup(&call->tq);
5777 #endif /* RX_ENABLE_LOCKS */
5779 rxi_CallError(call, call->error);
5782 #ifdef RX_ENABLE_LOCKS
5783 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5785 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5786 /* Some packets have received acks. If they all have, we can clear
5787 * the transmit queue.
5790 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5791 if (p->header.seq < call->tfirst
5792 && (p->flags & RX_PKTFLAG_ACKED)) {
5794 #ifdef RX_TRACK_PACKETS
5795 p->flags &= ~RX_PKTFLAG_TQ;
5797 #ifdef RXDEBUG_PACKET
5805 call->flags |= RX_CALL_TQ_CLEARME;
5807 #endif /* RX_ENABLE_LOCKS */
5808 /* Don't bother doing retransmits if the TQ is cleared. */
5809 if (call->flags & RX_CALL_TQ_CLEARME) {
5810 rxi_ClearTransmitQueue(call, 1);
5812 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5815 /* Always post a resend event, if there is anything in the
5816 * queue, and resend is possible. There should be at least
5817 * one unacknowledged packet in the queue ... otherwise none
5818 * of these packets should be on the queue in the first place.
5820 if (call->resendEvent) {
5821 /* Cancel the existing event and post a new one */
5822 rxevent_Cancel(call->resendEvent, call,
5823 RX_CALL_REFCOUNT_RESEND);
5826 /* The retry time is the retry time on the first unacknowledged
5827 * packet inside the current window */
5829 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5830 /* Don't set timers for packets outside the window */
5831 if (p->header.seq >= call->tfirst + call->twind) {
5835 if (!(p->flags & RX_PKTFLAG_ACKED)
5836 && !clock_IsZero(&p->retryTime)) {
5838 retryTime = p->retryTime;
5843 /* Post a new event to re-run rxi_Start when retries may be needed */
5844 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5845 #ifdef RX_ENABLE_LOCKS
5846 MUTEX_ENTER(&rx_refcnt_mutex);
5847 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5848 MUTEX_EXIT(&rx_refcnt_mutex);
5850 rxevent_PostNow2(&retryTime, &usenow,
5852 (void *)call, 0, istack);
5853 #else /* RX_ENABLE_LOCKS */
5855 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5856 (void *)call, 0, istack);
5857 #endif /* RX_ENABLE_LOCKS */
5860 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5861 } while (call->flags & RX_CALL_NEED_START);
5863 * TQ references no longer protected by this flag; they must remain
5864 * protected by the global lock.
5866 call->flags &= ~RX_CALL_TQ_BUSY;
5867 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5868 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5869 call, call->tqWaiters, call->flags));
5870 #ifdef RX_ENABLE_LOCKS
5871 osirx_AssertMine(&call->lock, "rxi_Start end");
5872 CV_BROADCAST(&call->cv_tq);
5873 #else /* RX_ENABLE_LOCKS */
5874 osi_rxWakeup(&call->tq);
5875 #endif /* RX_ENABLE_LOCKS */
5878 call->flags |= RX_CALL_NEED_START;
5880 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5882 if (call->resendEvent) {
5883 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5888 /* Also adjusts the keep alive parameters for the call, to reflect
5889 * that we have just sent a packet (so keep alives aren't sent
5892 rxi_Send(struct rx_call *call, struct rx_packet *p,
5895 struct rx_connection *conn = call->conn;
5897 /* Stamp each packet with the user supplied status */
5898 p->header.userStatus = call->localStatus;
5900 /* Allow the security object controlling this call's security to
5901 * make any last-minute changes to the packet */
5902 RXS_SendPacket(conn->securityObject, call, p);
5904 /* Since we're about to send SOME sort of packet to the peer, it's
5905 * safe to nuke any scheduled end-of-packets ack */
5906 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5908 /* Actually send the packet, filling in more connection-specific fields */
5909 MUTEX_EXIT(&call->lock);
5910 MUTEX_ENTER(&rx_refcnt_mutex);
5911 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5912 MUTEX_EXIT(&rx_refcnt_mutex);
5913 rxi_SendPacket(call, conn, p, istack);
5914 MUTEX_ENTER(&rx_refcnt_mutex);
5915 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5916 MUTEX_EXIT(&rx_refcnt_mutex);
5917 MUTEX_ENTER(&call->lock);
5919 /* Update last send time for this call (for keep-alive
5920 * processing), and for the connection (so that we can discover
5921 * idle connections) */
5922 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5923 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
5924 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
5926 conn->lastSendTime = call->lastSendTime = clock_Sec();
5927 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
5928 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5929 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
5930 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
5931 RX_ACK_PING_RESPONSE)))
5932 call->lastSendData = call->lastSendTime;
5936 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5937 * that things are fine. Also called periodically to guarantee that nothing
5938 * falls through the cracks (e.g. (error + dally) connections have keepalive
5939 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5941 * haveCTLock Set if calling from rxi_ReapConnections
5943 #ifdef RX_ENABLE_LOCKS
5945 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5946 #else /* RX_ENABLE_LOCKS */
5948 rxi_CheckCall(struct rx_call *call)
5949 #endif /* RX_ENABLE_LOCKS */
5951 struct rx_connection *conn = call->conn;
5953 afs_uint32 deadTime;
5957 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5958 if (call->flags & RX_CALL_TQ_BUSY) {
5959 /* Call is active and will be reset by rxi_Start if it's
5960 * in an error state.
5965 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5967 (((afs_uint32) conn->secondsUntilDead << 10) +
5968 ((afs_uint32) conn->peer->rtt >> 3) +
5969 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5971 /* These are computed to the second (+- 1 second). But that's
5972 * good enough for these values, which should be a significant
5973 * number of seconds. */
5974 if (now > (call->lastReceiveTime + deadTime)) {
5975 if (call->state == RX_STATE_ACTIVE) {
5977 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5979 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5980 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5981 ip_stack_t *ipst = ns->netstack_ip;
5983 ire = ire_cache_lookup(conn->peer->host
5984 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5986 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5988 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5995 if (ire && ire->ire_max_frag > 0)
5996 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
5998 #if defined(GLOBAL_NETSTACKID)
6002 #endif /* ADAPT_PMTU */
6003 cerror = RX_CALL_DEAD;
6006 #ifdef RX_ENABLE_LOCKS
6007 /* Cancel pending events */
6008 rxevent_Cancel(call->delayedAckEvent, call,
6009 RX_CALL_REFCOUNT_DELAY);
6010 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6011 rxevent_Cancel(call->keepAliveEvent, call,
6012 RX_CALL_REFCOUNT_ALIVE);
6013 MUTEX_ENTER(&rx_refcnt_mutex);
6014 if (call->refCount == 0) {
6015 rxi_FreeCall(call, haveCTLock);
6016 MUTEX_EXIT(&rx_refcnt_mutex);
6019 MUTEX_EXIT(&rx_refcnt_mutex);
6021 #else /* RX_ENABLE_LOCKS */
6022 rxi_FreeCall(call, 0);
6024 #endif /* RX_ENABLE_LOCKS */
6026 /* Non-active calls are destroyed if they are not responding
6027 * to pings; active calls are simply flagged in error, so the
6028 * attached process can die reasonably gracefully. */
6030 /* see if we have a non-activity timeout */
6031 if (call->startWait && conn->idleDeadTime
6032 && ((call->startWait + conn->idleDeadTime) < now) &&
6033 (call->flags & RX_CALL_READER_WAIT)) {
6034 if (call->state == RX_STATE_ACTIVE) {
6035 cerror = RX_CALL_TIMEOUT;
6039 if (call->lastSendData && conn->idleDeadTime && (conn->idleDeadErr != 0)
6040 && ((call->lastSendData + conn->idleDeadTime) < now)) {
6041 if (call->state == RX_STATE_ACTIVE) {
6042 cerror = conn->idleDeadErr;
6046 /* see if we have a hard timeout */
6047 if (conn->hardDeadTime
6048 && (now > (conn->hardDeadTime + call->startTime.sec))) {
6049 if (call->state == RX_STATE_ACTIVE)
6050 rxi_CallError(call, RX_CALL_TIMEOUT);
6055 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6056 && call->lastReceiveTime) {
6057 int oldMTU = conn->peer->ifMTU;
6059 /* if we thought we could send more, perhaps things got worse */
6060 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6061 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6062 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6063 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6065 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6067 /* minimum capped in SetPeerMtu */
6068 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6071 conn->lastPacketSize = 0;
6073 /* needed so ResetCall doesn't clobber us. */
6074 call->MTU = conn->peer->ifMTU;
6076 /* if we never succeeded, let the error pass out as-is */
6077 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6078 cerror = conn->msgsizeRetryErr;
6081 rxi_CallError(call, cerror);
6086 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6088 struct rx_connection *conn = arg1;
6089 struct rx_header theader;
6091 struct sockaddr_in taddr;
6094 struct iovec tmpiov[2];
6097 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6100 tp = &tbuffer[sizeof(struct rx_header)];
6101 taddr.sin_family = AF_INET;
6102 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6103 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6104 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6105 taddr.sin_len = sizeof(struct sockaddr_in);
6107 memset(&theader, 0, sizeof(theader));
6108 theader.epoch = htonl(999);
6110 theader.callNumber = 0;
6113 theader.type = RX_PACKET_TYPE_VERSION;
6114 theader.flags = RX_LAST_PACKET;
6115 theader.serviceId = 0;
6117 memcpy(tbuffer, &theader, sizeof(theader));
6118 memcpy(tp, &a, sizeof(a));
6119 tmpiov[0].iov_base = tbuffer;
6120 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6122 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6124 MUTEX_ENTER(&conn->conn_data_lock);
6125 MUTEX_ENTER(&rx_refcnt_mutex);
6126 /* Only reschedule ourselves if the connection would not be destroyed */
6127 if (conn->refCount <= 1) {
6128 conn->natKeepAliveEvent = NULL;
6129 MUTEX_EXIT(&rx_refcnt_mutex);
6130 MUTEX_EXIT(&conn->conn_data_lock);
6131 rx_DestroyConnection(conn); /* drop the reference for this */
6133 conn->refCount--; /* drop the reference for this */
6134 MUTEX_EXIT(&rx_refcnt_mutex);
6135 conn->natKeepAliveEvent = NULL;
6136 rxi_ScheduleNatKeepAliveEvent(conn);
6137 MUTEX_EXIT(&conn->conn_data_lock);
6142 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6144 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6145 struct clock when, now;
6146 clock_GetTime(&now);
6148 when.sec += conn->secondsUntilNatPing;
6149 MUTEX_ENTER(&rx_refcnt_mutex);
6150 conn->refCount++; /* hold a reference for this */
6151 MUTEX_EXIT(&rx_refcnt_mutex);
6152 conn->natKeepAliveEvent =
6153 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6158 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6160 MUTEX_ENTER(&conn->conn_data_lock);
6161 conn->secondsUntilNatPing = seconds;
6163 rxi_ScheduleNatKeepAliveEvent(conn);
6164 MUTEX_EXIT(&conn->conn_data_lock);
6168 rxi_NatKeepAliveOn(struct rx_connection *conn)
6170 MUTEX_ENTER(&conn->conn_data_lock);
6171 rxi_ScheduleNatKeepAliveEvent(conn);
6172 MUTEX_EXIT(&conn->conn_data_lock);
6175 /* When a call is in progress, this routine is called occasionally to
6176 * make sure that some traffic has arrived (or been sent to) the peer.
6177 * If nothing has arrived in a reasonable amount of time, the call is
6178 * declared dead; if nothing has been sent for a while, we send a
6179 * keep-alive packet (if we're actually trying to keep the call alive)
6182 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6184 struct rx_call *call = arg1;
6185 struct rx_connection *conn;
6188 MUTEX_ENTER(&rx_refcnt_mutex);
6189 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6190 MUTEX_EXIT(&rx_refcnt_mutex);
6191 MUTEX_ENTER(&call->lock);
6192 if (event == call->keepAliveEvent)
6193 call->keepAliveEvent = NULL;
6196 #ifdef RX_ENABLE_LOCKS
6197 if (rxi_CheckCall(call, 0)) {
6198 MUTEX_EXIT(&call->lock);
6201 #else /* RX_ENABLE_LOCKS */
6202 if (rxi_CheckCall(call))
6204 #endif /* RX_ENABLE_LOCKS */
6206 /* Don't try to keep alive dallying calls */
6207 if (call->state == RX_STATE_DALLY) {
6208 MUTEX_EXIT(&call->lock);
6213 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6214 /* Don't try to send keepalives if there is unacknowledged data */
6215 /* the rexmit code should be good enough, this little hack
6216 * doesn't quite work XXX */
6217 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6219 rxi_ScheduleKeepAliveEvent(call);
6220 MUTEX_EXIT(&call->lock);
6223 /* Does what's on the nameplate. */
6225 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6227 struct rx_call *call = arg1;
6228 struct rx_connection *conn;
6230 MUTEX_ENTER(&rx_refcnt_mutex);
6231 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6232 MUTEX_EXIT(&rx_refcnt_mutex);
6233 MUTEX_ENTER(&call->lock);
6235 if (event == call->growMTUEvent)
6236 call->growMTUEvent = NULL;
6238 #ifdef RX_ENABLE_LOCKS
6239 if (rxi_CheckCall(call, 0)) {
6240 MUTEX_EXIT(&call->lock);
6243 #else /* RX_ENABLE_LOCKS */
6244 if (rxi_CheckCall(call))
6246 #endif /* RX_ENABLE_LOCKS */
6248 /* Don't bother with dallying calls */
6249 if (call->state == RX_STATE_DALLY) {
6250 MUTEX_EXIT(&call->lock);
6257 * keep being scheduled, just don't do anything if we're at peak,
6258 * or we're not set up to be properly handled (idle timeout required)
6260 if ((conn->peer->maxPacketSize != 0) &&
6261 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6262 (conn->idleDeadErr))
6263 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6264 rxi_ScheduleGrowMTUEvent(call, 0);
6265 MUTEX_EXIT(&call->lock);
6269 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6271 if (!call->keepAliveEvent) {
6272 struct clock when, now;
6273 clock_GetTime(&now);
6275 when.sec += call->conn->secondsUntilPing;
6276 MUTEX_ENTER(&rx_refcnt_mutex);
6277 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6278 MUTEX_EXIT(&rx_refcnt_mutex);
6279 call->keepAliveEvent =
6280 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6285 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6287 if (!call->growMTUEvent) {
6288 struct clock when, now;
6290 clock_GetTime(&now);
6293 if (call->conn->secondsUntilPing)
6294 secs = (6*call->conn->secondsUntilPing)-1;
6296 if (call->conn->secondsUntilDead)
6297 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6301 MUTEX_ENTER(&rx_refcnt_mutex);
6302 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6303 MUTEX_EXIT(&rx_refcnt_mutex);
6304 call->growMTUEvent =
6305 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6309 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6311 rxi_KeepAliveOn(struct rx_call *call)
6313 /* Pretend last packet received was received now--i.e. if another
6314 * packet isn't received within the keep alive time, then the call
6315 * will die; Initialize last send time to the current time--even
6316 * if a packet hasn't been sent yet. This will guarantee that a
6317 * keep-alive is sent within the ping time */
6318 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6319 rxi_ScheduleKeepAliveEvent(call);
6323 rxi_GrowMTUOn(struct rx_call *call)
6325 struct rx_connection *conn = call->conn;
6326 MUTEX_ENTER(&conn->conn_data_lock);
6327 conn->lastPingSizeSer = conn->lastPingSize = 0;
6328 MUTEX_EXIT(&conn->conn_data_lock);
6329 rxi_ScheduleGrowMTUEvent(call, 1);
6332 /* This routine is called to send connection abort messages
6333 * that have been delayed to throttle looping clients. */
6335 rxi_SendDelayedConnAbort(struct rxevent *event,
6336 void *arg1, void *unused)
6338 struct rx_connection *conn = arg1;
6341 struct rx_packet *packet;
6343 MUTEX_ENTER(&conn->conn_data_lock);
6344 conn->delayedAbortEvent = NULL;
6345 error = htonl(conn->error);
6347 MUTEX_EXIT(&conn->conn_data_lock);
6348 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6351 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6352 RX_PACKET_TYPE_ABORT, (char *)&error,
6354 rxi_FreePacket(packet);
6358 /* This routine is called to send call abort messages
6359 * that have been delayed to throttle looping clients. */
6361 rxi_SendDelayedCallAbort(struct rxevent *event,
6362 void *arg1, void *dummy)
6364 struct rx_call *call = arg1;
6367 struct rx_packet *packet;
6369 MUTEX_ENTER(&call->lock);
6370 call->delayedAbortEvent = NULL;
6371 error = htonl(call->error);
6373 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6376 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6377 (char *)&error, sizeof(error), 0);
6378 rxi_FreePacket(packet);
6380 MUTEX_EXIT(&call->lock);
6381 MUTEX_ENTER(&rx_refcnt_mutex);
6382 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6383 MUTEX_EXIT(&rx_refcnt_mutex);
6386 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6387 * seconds) to ask the client to authenticate itself. The routine
6388 * issues a challenge to the client, which is obtained from the
6389 * security object associated with the connection */
6391 rxi_ChallengeEvent(struct rxevent *event,
6392 void *arg0, void *arg1, int tries)
6394 struct rx_connection *conn = arg0;
6396 conn->challengeEvent = NULL;
6397 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6398 struct rx_packet *packet;
6399 struct clock when, now;
6402 /* We've failed to authenticate for too long.
6403 * Reset any calls waiting for authentication;
6404 * they are all in RX_STATE_PRECALL.
6408 MUTEX_ENTER(&conn->conn_call_lock);
6409 for (i = 0; i < RX_MAXCALLS; i++) {
6410 struct rx_call *call = conn->call[i];
6412 MUTEX_ENTER(&call->lock);
6413 if (call->state == RX_STATE_PRECALL) {
6414 rxi_CallError(call, RX_CALL_DEAD);
6415 rxi_SendCallAbort(call, NULL, 0, 0);
6417 MUTEX_EXIT(&call->lock);
6420 MUTEX_EXIT(&conn->conn_call_lock);
6424 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6426 /* If there's no packet available, do this later. */
6427 RXS_GetChallenge(conn->securityObject, conn, packet);
6428 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6429 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6430 rxi_FreePacket(packet);
6432 clock_GetTime(&now);
6434 when.sec += RX_CHALLENGE_TIMEOUT;
6435 conn->challengeEvent =
6436 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6441 /* Call this routine to start requesting the client to authenticate
6442 * itself. This will continue until authentication is established,
6443 * the call times out, or an invalid response is returned. The
6444 * security object associated with the connection is asked to create
6445 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6446 * defined earlier. */
6448 rxi_ChallengeOn(struct rx_connection *conn)
6450 if (!conn->challengeEvent) {
6451 RXS_CreateChallenge(conn->securityObject, conn);
6452 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6457 /* Compute round trip time of the packet provided, in *rttp.
6460 /* rxi_ComputeRoundTripTime is called with peer locked. */
6461 /* sentp and/or peer may be null */
6463 rxi_ComputeRoundTripTime(struct rx_packet *p,
6464 struct clock *sentp,
6465 struct rx_peer *peer)
6467 struct clock thisRtt, *rttp = &thisRtt;
6471 clock_GetTime(rttp);
6473 if (clock_Lt(rttp, sentp)) {
6475 return; /* somebody set the clock back, don't count this time. */
6477 clock_Sub(rttp, sentp);
6478 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6479 p->header.callNumber, p, rttp->sec, rttp->usec));
6481 if (rttp->sec == 0 && rttp->usec == 0) {
6483 * The actual round trip time is shorter than the
6484 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6485 * Since we can't tell which at the moment we will assume 1ms.
6490 if (rx_stats_active) {
6491 MUTEX_ENTER(&rx_stats_mutex);
6492 if (clock_Lt(rttp, &rx_stats.minRtt))
6493 rx_stats.minRtt = *rttp;
6494 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
6495 if (rttp->sec > 60) {
6496 MUTEX_EXIT(&rx_stats_mutex);
6497 return; /* somebody set the clock ahead */
6499 rx_stats.maxRtt = *rttp;
6501 clock_Add(&rx_stats.totalRtt, rttp);
6502 rx_atomic_inc(&rx_stats.nRttSamples);
6503 MUTEX_EXIT(&rx_stats_mutex);
6506 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6508 /* Apply VanJacobson round-trip estimations */
6513 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6514 * srtt is stored as fixed point with 3 bits after the binary
6515 * point (i.e., scaled by 8). The following magic is
6516 * equivalent to the smoothing algorithm in rfc793 with an
6517 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6518 * srtt'*8 = rtt + srtt*7
6519 * srtt'*8 = srtt*8 + rtt - srtt
6520 * srtt' = srtt + rtt/8 - srtt/8
6521 * srtt' = srtt + (rtt - srtt)/8
6524 delta = _8THMSEC(rttp) - peer->rtt;
6525 peer->rtt += (delta >> 3);
6528 * We accumulate a smoothed rtt variance (actually, a smoothed
6529 * mean difference), then set the retransmit timer to smoothed
6530 * rtt + 4 times the smoothed variance (was 2x in van's original
6531 * paper, but 4x works better for me, and apparently for him as
6533 * rttvar is stored as
6534 * fixed point with 2 bits after the binary point (scaled by
6535 * 4). The following is equivalent to rfc793 smoothing with
6536 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6537 * rttvar'*4 = rttvar*3 + |delta|
6538 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6539 * rttvar' = rttvar + |delta|/4 - rttvar/4
6540 * rttvar' = rttvar + (|delta| - rttvar)/4
6541 * This replaces rfc793's wired-in beta.
6542 * dev*4 = dev*4 + (|actual - expected| - dev)
6548 delta -= (peer->rtt_dev << 1);
6549 peer->rtt_dev += (delta >> 3);
6551 /* I don't have a stored RTT so I start with this value. Since I'm
6552 * probably just starting a call, and will be pushing more data down
6553 * this, I expect congestion to increase rapidly. So I fudge a
6554 * little, and I set deviance to half the rtt. In practice,
6555 * deviance tends to approach something a little less than
6556 * half the smoothed rtt. */
6557 peer->rtt = _8THMSEC(rttp) + 8;
6558 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6560 /* the timeout is RTT + 4*MDEV but no less than rx_minPeerTimeout msec.
6561 * This is because one end or the other of these connections is usually
6562 * in a user process, and can be switched and/or swapped out. So on fast,
6563 * reliable networks, the timeout would otherwise be too short. */
6564 rtt_timeout = MAX(((peer->rtt >> 3) + peer->rtt_dev), rx_minPeerTimeout);
6565 clock_Zero(&(peer->timeout));
6566 clock_Addmsec(&(peer->timeout), rtt_timeout);
6568 /* Reset the backedOff flag since we just computed a new timeout value */
6569 peer->backedOff = 0;
6571 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6572 p->header.callNumber, p, MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6576 /* Find all server connections that have not been active for a long time, and
6579 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6581 struct clock now, when;
6582 clock_GetTime(&now);
6584 /* Find server connection structures that haven't been used for
6585 * greater than rx_idleConnectionTime */
6587 struct rx_connection **conn_ptr, **conn_end;
6588 int i, havecalls = 0;
6589 MUTEX_ENTER(&rx_connHashTable_lock);
6590 for (conn_ptr = &rx_connHashTable[0], conn_end =
6591 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6593 struct rx_connection *conn, *next;
6594 struct rx_call *call;
6598 for (conn = *conn_ptr; conn; conn = next) {
6599 /* XXX -- Shouldn't the connection be locked? */
6602 for (i = 0; i < RX_MAXCALLS; i++) {
6603 call = conn->call[i];
6607 code = MUTEX_TRYENTER(&call->lock);
6610 #ifdef RX_ENABLE_LOCKS
6611 result = rxi_CheckCall(call, 1);
6612 #else /* RX_ENABLE_LOCKS */
6613 result = rxi_CheckCall(call);
6614 #endif /* RX_ENABLE_LOCKS */
6615 MUTEX_EXIT(&call->lock);
6617 /* If CheckCall freed the call, it might
6618 * have destroyed the connection as well,
6619 * which screws up the linked lists.
6625 if (conn->type == RX_SERVER_CONNECTION) {
6626 /* This only actually destroys the connection if
6627 * there are no outstanding calls */
6628 MUTEX_ENTER(&conn->conn_data_lock);
6629 MUTEX_ENTER(&rx_refcnt_mutex);
6630 if (!havecalls && !conn->refCount
6631 && ((conn->lastSendTime + rx_idleConnectionTime) <
6633 conn->refCount++; /* it will be decr in rx_DestroyConn */
6634 MUTEX_EXIT(&rx_refcnt_mutex);
6635 MUTEX_EXIT(&conn->conn_data_lock);
6636 #ifdef RX_ENABLE_LOCKS
6637 rxi_DestroyConnectionNoLock(conn);
6638 #else /* RX_ENABLE_LOCKS */
6639 rxi_DestroyConnection(conn);
6640 #endif /* RX_ENABLE_LOCKS */
6642 #ifdef RX_ENABLE_LOCKS
6644 MUTEX_EXIT(&rx_refcnt_mutex);
6645 MUTEX_EXIT(&conn->conn_data_lock);
6647 #endif /* RX_ENABLE_LOCKS */
6651 #ifdef RX_ENABLE_LOCKS
6652 while (rx_connCleanup_list) {
6653 struct rx_connection *conn;
6654 conn = rx_connCleanup_list;
6655 rx_connCleanup_list = rx_connCleanup_list->next;
6656 MUTEX_EXIT(&rx_connHashTable_lock);
6657 rxi_CleanupConnection(conn);
6658 MUTEX_ENTER(&rx_connHashTable_lock);
6660 MUTEX_EXIT(&rx_connHashTable_lock);
6661 #endif /* RX_ENABLE_LOCKS */
6664 /* Find any peer structures that haven't been used (haven't had an
6665 * associated connection) for greater than rx_idlePeerTime */
6667 struct rx_peer **peer_ptr, **peer_end;
6671 * Why do we need to hold the rx_peerHashTable_lock across
6672 * the incrementing of peer_ptr since the rx_peerHashTable
6673 * array is not changing? We don't.
6675 * By dropping the lock periodically we can permit other
6676 * activities to be performed while a rxi_ReapConnections
6677 * call is in progress. The goal of reap connections
6678 * is to clean up quickly without causing large amounts
6679 * of contention. Therefore, it is important that global
6680 * mutexes not be held for extended periods of time.
6682 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6683 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6685 struct rx_peer *peer, *next, *prev;
6687 MUTEX_ENTER(&rx_peerHashTable_lock);
6688 for (prev = peer = *peer_ptr; peer; peer = next) {
6690 code = MUTEX_TRYENTER(&peer->peer_lock);
6691 if ((code) && (peer->refCount == 0)
6692 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6693 rx_interface_stat_p rpc_stat, nrpc_stat;
6697 * now know that this peer object is one to be
6698 * removed from the hash table. Once it is removed
6699 * it can't be referenced by other threads.
6700 * Lets remove it first and decrement the struct
6701 * nPeerStructs count.
6703 if (peer == *peer_ptr) {
6709 if (rx_stats_active)
6710 rx_atomic_dec(&rx_stats.nPeerStructs);
6713 * Now if we hold references on 'prev' and 'next'
6714 * we can safely drop the rx_peerHashTable_lock
6715 * while we destroy this 'peer' object.
6721 MUTEX_EXIT(&rx_peerHashTable_lock);
6723 MUTEX_EXIT(&peer->peer_lock);
6724 MUTEX_DESTROY(&peer->peer_lock);
6726 (&peer->rpcStats, rpc_stat, nrpc_stat,
6727 rx_interface_stat)) {
6728 unsigned int num_funcs;
6731 queue_Remove(&rpc_stat->queue_header);
6732 queue_Remove(&rpc_stat->all_peers);
6733 num_funcs = rpc_stat->stats[0].func_total;
6735 sizeof(rx_interface_stat_t) +
6736 rpc_stat->stats[0].func_total *
6737 sizeof(rx_function_entry_v1_t);
6739 rxi_Free(rpc_stat, space);
6741 MUTEX_ENTER(&rx_rpc_stats);
6742 rxi_rpc_peer_stat_cnt -= num_funcs;
6743 MUTEX_EXIT(&rx_rpc_stats);
6748 * Regain the rx_peerHashTable_lock and
6749 * decrement the reference count on 'prev'
6752 MUTEX_ENTER(&rx_peerHashTable_lock);
6759 MUTEX_EXIT(&peer->peer_lock);
6764 MUTEX_EXIT(&rx_peerHashTable_lock);
6768 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6769 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6770 * GC, just below. Really, we shouldn't have to keep moving packets from
6771 * one place to another, but instead ought to always know if we can
6772 * afford to hold onto a packet in its particular use. */
6773 MUTEX_ENTER(&rx_freePktQ_lock);
6774 if (rx_waitingForPackets) {
6775 rx_waitingForPackets = 0;
6776 #ifdef RX_ENABLE_LOCKS
6777 CV_BROADCAST(&rx_waitingForPackets_cv);
6779 osi_rxWakeup(&rx_waitingForPackets);
6782 MUTEX_EXIT(&rx_freePktQ_lock);
6785 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6786 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6790 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6791 * rx.h is sort of strange this is better. This is called with a security
6792 * object before it is discarded. Each connection using a security object has
6793 * its own refcount to the object so it won't actually be freed until the last
6794 * connection is destroyed.
6796 * This is the only rxs module call. A hold could also be written but no one
6800 rxs_Release(struct rx_securityClass *aobj)
6802 return RXS_Close(aobj);
6806 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6807 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6808 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6809 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6811 /* Adjust our estimate of the transmission rate to this peer, given
6812 * that the packet p was just acked. We can adjust peer->timeout and
6813 * call->twind. Pragmatically, this is called
6814 * only with packets of maximal length.
6815 * Called with peer and call locked.
6819 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6820 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6822 afs_int32 xferSize, xferMs;
6826 /* Count down packets */
6827 if (peer->rateFlag > 0)
6829 /* Do nothing until we're enabled */
6830 if (peer->rateFlag != 0)
6835 /* Count only when the ack seems legitimate */
6836 switch (ackReason) {
6837 case RX_ACK_REQUESTED:
6839 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6843 case RX_ACK_PING_RESPONSE:
6844 if (p) /* want the response to ping-request, not data send */
6846 clock_GetTime(&newTO);
6847 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6848 clock_Sub(&newTO, &call->pingRequestTime);
6849 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6853 xferSize = rx_AckDataSize(rx_maxSendWindow) + RX_HEADER_SIZE;
6860 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)",
6861 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
6862 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6864 /* Track only packets that are big enough. */
6865 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6869 /* absorb RTT data (in milliseconds) for these big packets */
6870 if (peer->smRtt == 0) {
6871 peer->smRtt = xferMs;
6873 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6878 if (peer->countDown) {
6882 peer->countDown = 10; /* recalculate only every so often */
6884 /* In practice, we can measure only the RTT for full packets,
6885 * because of the way Rx acks the data that it receives. (If it's
6886 * smaller than a full packet, it often gets implicitly acked
6887 * either by the call response (from a server) or by the next call
6888 * (from a client), and either case confuses transmission times
6889 * with processing times.) Therefore, replace the above
6890 * more-sophisticated processing with a simpler version, where the
6891 * smoothed RTT is kept for full-size packets, and the time to
6892 * transmit a windowful of full-size packets is simply RTT *
6893 * windowSize. Again, we take two steps:
6894 - ensure the timeout is large enough for a single packet's RTT;
6895 - ensure that the window is small enough to fit in the desired timeout.*/
6897 /* First, the timeout check. */
6898 minTime = peer->smRtt;
6899 /* Get a reasonable estimate for a timeout period */
6901 newTO.sec = minTime / 1000;
6902 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6904 /* Increase the timeout period so that we can always do at least
6905 * one packet exchange */
6906 if (clock_Gt(&newTO, &peer->timeout)) {
6908 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u)",
6909 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
6910 newTO.sec, newTO.usec, peer->smRtt));
6912 peer->timeout = newTO;
6915 /* Now, get an estimate for the transmit window size. */
6916 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6917 /* Now, convert to the number of full packets that could fit in a
6918 * reasonable fraction of that interval */
6919 minTime /= (peer->smRtt << 1);
6920 minTime = MAX(minTime, rx_minPeerTimeout);
6921 xferSize = minTime; /* (make a copy) */
6923 /* Now clamp the size to reasonable bounds. */
6926 else if (minTime > rx_maxSendWindow)
6927 minTime = rx_maxSendWindow;
6928 /* if (minTime != peer->maxWindow) {
6929 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u)",
6930 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6931 peer->timeout.sec, peer->timeout.usec, peer->smRtt));
6932 peer->maxWindow = minTime;
6933 elide... call->twind = minTime;
6937 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6938 * Discern this by calculating the timeout necessary for rx_Window
6940 if ((xferSize > rx_maxSendWindow) && (peer->timeout.sec >= 3)) {
6941 /* calculate estimate for transmission interval in milliseconds */
6942 minTime = rx_maxSendWindow * peer->smRtt;
6943 if (minTime < 1000) {
6944 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u)",
6945 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6946 peer->timeout.usec, peer->smRtt));
6948 newTO.sec = 0; /* cut back on timeout by half a second */
6949 newTO.usec = 500000;
6950 clock_Sub(&peer->timeout, &newTO);
6955 } /* end of rxi_ComputeRate */
6956 #endif /* ADAPT_WINDOW */
6964 #define TRACE_OPTION_RX_DEBUG 16
6972 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6973 0, KEY_QUERY_VALUE, &parmKey);
6974 if (code != ERROR_SUCCESS)
6977 dummyLen = sizeof(TraceOption);
6978 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6979 (BYTE *) &TraceOption, &dummyLen);
6980 if (code == ERROR_SUCCESS) {
6981 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6983 RegCloseKey (parmKey);
6984 #endif /* AFS_NT40_ENV */
6989 rx_DebugOnOff(int on)
6993 rxdebug_active = on;
6999 rx_StatsOnOff(int on)
7002 rx_stats_active = on;
7007 /* Don't call this debugging routine directly; use dpf */
7009 rxi_DebugPrint(char *format, ...)
7018 va_start(ap, format);
7020 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7023 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7025 if (msg[len-1] != '\n') {
7029 OutputDebugString(msg);
7036 va_start(ap, format);
7038 clock_GetTime(&now);
7039 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7040 (unsigned int)now.usec);
7041 vfprintf(rx_Log, format, ap);
7050 * This function is used to process the rx_stats structure that is local
7051 * to a process as well as an rx_stats structure received from a remote
7052 * process (via rxdebug). Therefore, it needs to do minimal version
7056 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7057 afs_int32 freePackets, char version)
7061 if (size != sizeof(struct rx_statistics)) {
7063 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7064 size, sizeof(struct rx_statistics));
7067 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7070 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7071 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7072 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7073 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7074 s->specialPktAllocFailures);
7076 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7077 s->receivePktAllocFailures, s->sendPktAllocFailures,
7078 s->specialPktAllocFailures);
7082 " greedy %u, " "bogusReads %u (last from host %x), "
7083 "noPackets %u, " "noBuffers %u, " "selects %u, "
7084 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7085 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7086 s->selects, s->sendSelects);
7088 fprintf(file, " packets read: ");
7089 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7090 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7092 fprintf(file, "\n");
7095 " other read counters: data %u, " "ack %u, " "dup %u "
7096 "spurious %u " "dally %u\n", s->dataPacketsRead,
7097 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7098 s->ignorePacketDally);
7100 fprintf(file, " packets sent: ");
7101 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7102 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7104 fprintf(file, "\n");
7107 " other send counters: ack %u, " "data %u (not resends), "
7108 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7109 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7110 s->dataPacketsPushed, s->ignoreAckedPacket);
7113 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7114 s->netSendFailures, (int)s->fatalErrors);
7116 if (s->nRttSamples) {
7117 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7118 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7120 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7121 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7125 " %d server connections, " "%d client connections, "
7126 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7127 s->nServerConns, s->nClientConns, s->nPeerStructs,
7128 s->nCallStructs, s->nFreeCallStructs);
7130 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7131 fprintf(file, " %d clock updates\n", clock_nUpdates);
7135 /* for backward compatibility */
7137 rx_PrintStats(FILE * file)
7139 MUTEX_ENTER(&rx_stats_mutex);
7140 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7141 sizeof(rx_stats), rx_nFreePackets,
7143 MUTEX_EXIT(&rx_stats_mutex);
7147 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7149 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7150 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7151 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7154 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7155 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7156 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7159 " Packet size %d, " "max in packet skew %d, "
7160 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7161 (int)peer->outPacketSkew);
7165 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7167 * This mutex protects the following static variables:
7171 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7172 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7174 #define LOCK_RX_DEBUG
7175 #define UNLOCK_RX_DEBUG
7176 #endif /* AFS_PTHREAD_ENV */
7178 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7180 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7181 u_char type, void *inputData, size_t inputLength,
7182 void *outputData, size_t outputLength)
7184 static afs_int32 counter = 100;
7185 time_t waitTime, waitCount;
7186 struct rx_header theader;
7189 struct timeval tv_now, tv_wake, tv_delta;
7190 struct sockaddr_in taddr, faddr;
7204 tp = &tbuffer[sizeof(struct rx_header)];
7205 taddr.sin_family = AF_INET;
7206 taddr.sin_port = remotePort;
7207 taddr.sin_addr.s_addr = remoteAddr;
7208 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7209 taddr.sin_len = sizeof(struct sockaddr_in);
7212 memset(&theader, 0, sizeof(theader));
7213 theader.epoch = htonl(999);
7215 theader.callNumber = htonl(counter);
7218 theader.type = type;
7219 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7220 theader.serviceId = 0;
7222 memcpy(tbuffer, &theader, sizeof(theader));
7223 memcpy(tp, inputData, inputLength);
7225 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7226 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7228 /* see if there's a packet available */
7229 gettimeofday(&tv_wake,0);
7230 tv_wake.tv_sec += waitTime;
7233 FD_SET(socket, &imask);
7234 tv_delta.tv_sec = tv_wake.tv_sec;
7235 tv_delta.tv_usec = tv_wake.tv_usec;
7236 gettimeofday(&tv_now, 0);
7238 if (tv_delta.tv_usec < tv_now.tv_usec) {
7240 tv_delta.tv_usec += 1000000;
7243 tv_delta.tv_usec -= tv_now.tv_usec;
7245 if (tv_delta.tv_sec < tv_now.tv_sec) {
7249 tv_delta.tv_sec -= tv_now.tv_sec;
7252 code = select(0, &imask, 0, 0, &tv_delta);
7253 #else /* AFS_NT40_ENV */
7254 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7255 #endif /* AFS_NT40_ENV */
7256 if (code == 1 && FD_ISSET(socket, &imask)) {
7257 /* now receive a packet */
7258 faddrLen = sizeof(struct sockaddr_in);
7260 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7261 (struct sockaddr *)&faddr, &faddrLen);
7264 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7265 if (counter == ntohl(theader.callNumber))
7273 /* see if we've timed out */
7281 code -= sizeof(struct rx_header);
7282 if (code > outputLength)
7283 code = outputLength;
7284 memcpy(outputData, tp, code);
7287 #endif /* RXDEBUG */
7290 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7291 afs_uint16 remotePort, struct rx_debugStats * stat,
7292 afs_uint32 * supportedValues)
7294 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7296 struct rx_debugIn in;
7298 *supportedValues = 0;
7299 in.type = htonl(RX_DEBUGI_GETSTATS);
7302 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7303 &in, sizeof(in), stat, sizeof(*stat));
7306 * If the call was successful, fixup the version and indicate
7307 * what contents of the stat structure are valid.
7308 * Also do net to host conversion of fields here.
7312 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7313 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7315 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7316 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7318 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7319 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7321 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7322 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7324 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7325 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7327 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7328 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7330 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7331 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7333 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7334 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7336 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7337 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7339 stat->nFreePackets = ntohl(stat->nFreePackets);
7340 stat->packetReclaims = ntohl(stat->packetReclaims);
7341 stat->callsExecuted = ntohl(stat->callsExecuted);
7342 stat->nWaiting = ntohl(stat->nWaiting);
7343 stat->idleThreads = ntohl(stat->idleThreads);
7344 stat->nWaited = ntohl(stat->nWaited);
7345 stat->nPackets = ntohl(stat->nPackets);
7354 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7355 afs_uint16 remotePort, struct rx_statistics * stat,
7356 afs_uint32 * supportedValues)
7358 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7360 struct rx_debugIn in;
7361 afs_int32 *lp = (afs_int32 *) stat;
7365 * supportedValues is currently unused, but added to allow future
7366 * versioning of this function.
7369 *supportedValues = 0;
7370 in.type = htonl(RX_DEBUGI_RXSTATS);
7372 memset(stat, 0, sizeof(*stat));
7374 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7375 &in, sizeof(in), stat, sizeof(*stat));
7380 * Do net to host conversion here
7383 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7394 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7395 afs_uint16 remotePort, size_t version_length,
7398 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7400 return MakeDebugCall(socket, remoteAddr, remotePort,
7401 RX_PACKET_TYPE_VERSION, a, 1, version,
7409 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7410 afs_uint16 remotePort, afs_int32 * nextConnection,
7411 int allConnections, afs_uint32 debugSupportedValues,
7412 struct rx_debugConn * conn,
7413 afs_uint32 * supportedValues)
7415 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7417 struct rx_debugIn in;
7421 * supportedValues is currently unused, but added to allow future
7422 * versioning of this function.
7425 *supportedValues = 0;
7426 if (allConnections) {
7427 in.type = htonl(RX_DEBUGI_GETALLCONN);
7429 in.type = htonl(RX_DEBUGI_GETCONN);
7431 in.index = htonl(*nextConnection);
7432 memset(conn, 0, sizeof(*conn));
7434 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7435 &in, sizeof(in), conn, sizeof(*conn));
7438 *nextConnection += 1;
7441 * Convert old connection format to new structure.
7444 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7445 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7446 #define MOVEvL(a) (conn->a = vL->a)
7448 /* any old or unrecognized version... */
7449 for (i = 0; i < RX_MAXCALLS; i++) {
7450 MOVEvL(callState[i]);
7451 MOVEvL(callMode[i]);
7452 MOVEvL(callFlags[i]);
7453 MOVEvL(callOther[i]);
7455 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7456 MOVEvL(secStats.type);
7457 MOVEvL(secStats.level);
7458 MOVEvL(secStats.flags);
7459 MOVEvL(secStats.expires);
7460 MOVEvL(secStats.packetsReceived);
7461 MOVEvL(secStats.packetsSent);
7462 MOVEvL(secStats.bytesReceived);
7463 MOVEvL(secStats.bytesSent);
7468 * Do net to host conversion here
7470 * I don't convert host or port since we are most likely
7471 * going to want these in NBO.
7473 conn->cid = ntohl(conn->cid);
7474 conn->serial = ntohl(conn->serial);
7475 for (i = 0; i < RX_MAXCALLS; i++) {
7476 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7478 conn->error = ntohl(conn->error);
7479 conn->secStats.flags = ntohl(conn->secStats.flags);
7480 conn->secStats.expires = ntohl(conn->secStats.expires);
7481 conn->secStats.packetsReceived =
7482 ntohl(conn->secStats.packetsReceived);
7483 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7484 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7485 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7486 conn->epoch = ntohl(conn->epoch);
7487 conn->natMTU = ntohl(conn->natMTU);
7496 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7497 afs_uint16 remotePort, afs_int32 * nextPeer,
7498 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7499 afs_uint32 * supportedValues)
7501 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7503 struct rx_debugIn in;
7506 * supportedValues is currently unused, but added to allow future
7507 * versioning of this function.
7510 *supportedValues = 0;
7511 in.type = htonl(RX_DEBUGI_GETPEER);
7512 in.index = htonl(*nextPeer);
7513 memset(peer, 0, sizeof(*peer));
7515 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7516 &in, sizeof(in), peer, sizeof(*peer));
7522 * Do net to host conversion here
7524 * I don't convert host or port since we are most likely
7525 * going to want these in NBO.
7527 peer->ifMTU = ntohs(peer->ifMTU);
7528 peer->idleWhen = ntohl(peer->idleWhen);
7529 peer->refCount = ntohs(peer->refCount);
7530 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7531 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7532 peer->rtt = ntohl(peer->rtt);
7533 peer->rtt_dev = ntohl(peer->rtt_dev);
7534 peer->timeout.sec = ntohl(peer->timeout.sec);
7535 peer->timeout.usec = ntohl(peer->timeout.usec);
7536 peer->nSent = ntohl(peer->nSent);
7537 peer->reSends = ntohl(peer->reSends);
7538 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7539 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7540 peer->rateFlag = ntohl(peer->rateFlag);
7541 peer->natMTU = ntohs(peer->natMTU);
7542 peer->maxMTU = ntohs(peer->maxMTU);
7543 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7544 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7545 peer->MTU = ntohs(peer->MTU);
7546 peer->cwind = ntohs(peer->cwind);
7547 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7548 peer->congestSeq = ntohs(peer->congestSeq);
7549 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7550 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7551 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7552 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7561 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7562 struct rx_debugPeer * peerStats)
7565 afs_int32 error = 1; /* default to "did not succeed" */
7566 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7568 MUTEX_ENTER(&rx_peerHashTable_lock);
7569 for(tp = rx_peerHashTable[hashValue];
7570 tp != NULL; tp = tp->next) {
7571 if (tp->host == peerHost)
7577 MUTEX_EXIT(&rx_peerHashTable_lock);
7581 MUTEX_ENTER(&tp->peer_lock);
7582 peerStats->host = tp->host;
7583 peerStats->port = tp->port;
7584 peerStats->ifMTU = tp->ifMTU;
7585 peerStats->idleWhen = tp->idleWhen;
7586 peerStats->refCount = tp->refCount;
7587 peerStats->burstSize = tp->burstSize;
7588 peerStats->burst = tp->burst;
7589 peerStats->burstWait.sec = tp->burstWait.sec;
7590 peerStats->burstWait.usec = tp->burstWait.usec;
7591 peerStats->rtt = tp->rtt;
7592 peerStats->rtt_dev = tp->rtt_dev;
7593 peerStats->timeout.sec = tp->timeout.sec;
7594 peerStats->timeout.usec = tp->timeout.usec;
7595 peerStats->nSent = tp->nSent;
7596 peerStats->reSends = tp->reSends;
7597 peerStats->inPacketSkew = tp->inPacketSkew;
7598 peerStats->outPacketSkew = tp->outPacketSkew;
7599 peerStats->rateFlag = tp->rateFlag;
7600 peerStats->natMTU = tp->natMTU;
7601 peerStats->maxMTU = tp->maxMTU;
7602 peerStats->maxDgramPackets = tp->maxDgramPackets;
7603 peerStats->ifDgramPackets = tp->ifDgramPackets;
7604 peerStats->MTU = tp->MTU;
7605 peerStats->cwind = tp->cwind;
7606 peerStats->nDgramPackets = tp->nDgramPackets;
7607 peerStats->congestSeq = tp->congestSeq;
7608 peerStats->bytesSent.high = tp->bytesSent.high;
7609 peerStats->bytesSent.low = tp->bytesSent.low;
7610 peerStats->bytesReceived.high = tp->bytesReceived.high;
7611 peerStats->bytesReceived.low = tp->bytesReceived.low;
7612 MUTEX_EXIT(&tp->peer_lock);
7614 MUTEX_ENTER(&rx_peerHashTable_lock);
7617 MUTEX_EXIT(&rx_peerHashTable_lock);
7625 struct rx_serverQueueEntry *np;
7628 struct rx_call *call;
7629 struct rx_serverQueueEntry *sq;
7633 if (rxinit_status == 1) {
7635 return; /* Already shutdown. */
7639 #ifndef AFS_PTHREAD_ENV
7640 FD_ZERO(&rx_selectMask);
7641 #endif /* AFS_PTHREAD_ENV */
7642 rxi_dataQuota = RX_MAX_QUOTA;
7643 #ifndef AFS_PTHREAD_ENV
7645 #endif /* AFS_PTHREAD_ENV */
7648 #ifndef AFS_PTHREAD_ENV
7649 #ifndef AFS_USE_GETTIMEOFDAY
7651 #endif /* AFS_USE_GETTIMEOFDAY */
7652 #endif /* AFS_PTHREAD_ENV */
7654 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7655 call = queue_First(&rx_freeCallQueue, rx_call);
7657 rxi_Free(call, sizeof(struct rx_call));
7660 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7661 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7667 struct rx_peer **peer_ptr, **peer_end;
7668 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7669 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7671 struct rx_peer *peer, *next;
7673 MUTEX_ENTER(&rx_peerHashTable_lock);
7674 for (peer = *peer_ptr; peer; peer = next) {
7675 rx_interface_stat_p rpc_stat, nrpc_stat;
7678 MUTEX_ENTER(&rx_rpc_stats);
7679 MUTEX_ENTER(&peer->peer_lock);
7681 (&peer->rpcStats, rpc_stat, nrpc_stat,
7682 rx_interface_stat)) {
7683 unsigned int num_funcs;
7686 queue_Remove(&rpc_stat->queue_header);
7687 queue_Remove(&rpc_stat->all_peers);
7688 num_funcs = rpc_stat->stats[0].func_total;
7690 sizeof(rx_interface_stat_t) +
7691 rpc_stat->stats[0].func_total *
7692 sizeof(rx_function_entry_v1_t);
7694 rxi_Free(rpc_stat, space);
7696 /* rx_rpc_stats must be held */
7697 rxi_rpc_peer_stat_cnt -= num_funcs;
7699 MUTEX_EXIT(&peer->peer_lock);
7700 MUTEX_EXIT(&rx_rpc_stats);
7704 if (rx_stats_active)
7705 rx_atomic_dec(&rx_stats.nPeerStructs);
7707 MUTEX_EXIT(&rx_peerHashTable_lock);
7710 for (i = 0; i < RX_MAX_SERVICES; i++) {
7712 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7714 for (i = 0; i < rx_hashTableSize; i++) {
7715 struct rx_connection *tc, *ntc;
7716 MUTEX_ENTER(&rx_connHashTable_lock);
7717 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7719 for (j = 0; j < RX_MAXCALLS; j++) {
7721 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7724 rxi_Free(tc, sizeof(*tc));
7726 MUTEX_EXIT(&rx_connHashTable_lock);
7729 MUTEX_ENTER(&freeSQEList_lock);
7731 while ((np = rx_FreeSQEList)) {
7732 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7733 MUTEX_DESTROY(&np->lock);
7734 rxi_Free(np, sizeof(*np));
7737 MUTEX_EXIT(&freeSQEList_lock);
7738 MUTEX_DESTROY(&freeSQEList_lock);
7739 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7740 MUTEX_DESTROY(&rx_connHashTable_lock);
7741 MUTEX_DESTROY(&rx_peerHashTable_lock);
7742 MUTEX_DESTROY(&rx_serverPool_lock);
7744 osi_Free(rx_connHashTable,
7745 rx_hashTableSize * sizeof(struct rx_connection *));
7746 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7748 UNPIN(rx_connHashTable,
7749 rx_hashTableSize * sizeof(struct rx_connection *));
7750 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7752 rxi_FreeAllPackets();
7754 MUTEX_ENTER(&rx_quota_mutex);
7755 rxi_dataQuota = RX_MAX_QUOTA;
7756 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7757 MUTEX_EXIT(&rx_quota_mutex);
7762 #ifdef RX_ENABLE_LOCKS
7764 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7766 if (!MUTEX_ISMINE(lockaddr))
7767 osi_Panic("Lock not held: %s", msg);
7769 #endif /* RX_ENABLE_LOCKS */
7774 * Routines to implement connection specific data.
7778 rx_KeyCreate(rx_destructor_t rtn)
7781 MUTEX_ENTER(&rxi_keyCreate_lock);
7782 key = rxi_keyCreate_counter++;
7783 rxi_keyCreate_destructor = (rx_destructor_t *)
7784 realloc((void *)rxi_keyCreate_destructor,
7785 (key + 1) * sizeof(rx_destructor_t));
7786 rxi_keyCreate_destructor[key] = rtn;
7787 MUTEX_EXIT(&rxi_keyCreate_lock);
7792 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7795 MUTEX_ENTER(&conn->conn_data_lock);
7796 if (!conn->specific) {
7797 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7798 for (i = 0; i < key; i++)
7799 conn->specific[i] = NULL;
7800 conn->nSpecific = key + 1;
7801 conn->specific[key] = ptr;
7802 } else if (key >= conn->nSpecific) {
7803 conn->specific = (void **)
7804 realloc(conn->specific, (key + 1) * sizeof(void *));
7805 for (i = conn->nSpecific; i < key; i++)
7806 conn->specific[i] = NULL;
7807 conn->nSpecific = key + 1;
7808 conn->specific[key] = ptr;
7810 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7811 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7812 conn->specific[key] = ptr;
7814 MUTEX_EXIT(&conn->conn_data_lock);
7818 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7821 MUTEX_ENTER(&svc->svc_data_lock);
7822 if (!svc->specific) {
7823 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7824 for (i = 0; i < key; i++)
7825 svc->specific[i] = NULL;
7826 svc->nSpecific = key + 1;
7827 svc->specific[key] = ptr;
7828 } else if (key >= svc->nSpecific) {
7829 svc->specific = (void **)
7830 realloc(svc->specific, (key + 1) * sizeof(void *));
7831 for (i = svc->nSpecific; i < key; i++)
7832 svc->specific[i] = NULL;
7833 svc->nSpecific = key + 1;
7834 svc->specific[key] = ptr;
7836 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7837 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7838 svc->specific[key] = ptr;
7840 MUTEX_EXIT(&svc->svc_data_lock);
7844 rx_GetSpecific(struct rx_connection *conn, int key)
7847 MUTEX_ENTER(&conn->conn_data_lock);
7848 if (key >= conn->nSpecific)
7851 ptr = conn->specific[key];
7852 MUTEX_EXIT(&conn->conn_data_lock);
7857 rx_GetServiceSpecific(struct rx_service *svc, int key)
7860 MUTEX_ENTER(&svc->svc_data_lock);
7861 if (key >= svc->nSpecific)
7864 ptr = svc->specific[key];
7865 MUTEX_EXIT(&svc->svc_data_lock);
7870 #endif /* !KERNEL */
7873 * processStats is a queue used to store the statistics for the local
7874 * process. Its contents are similar to the contents of the rpcStats
7875 * queue on a rx_peer structure, but the actual data stored within
7876 * this queue contains totals across the lifetime of the process (assuming
7877 * the stats have not been reset) - unlike the per peer structures
7878 * which can come and go based upon the peer lifetime.
7881 static struct rx_queue processStats = { &processStats, &processStats };
7884 * peerStats is a queue used to store the statistics for all peer structs.
7885 * Its contents are the union of all the peer rpcStats queues.
7888 static struct rx_queue peerStats = { &peerStats, &peerStats };
7891 * rxi_monitor_processStats is used to turn process wide stat collection
7895 static int rxi_monitor_processStats = 0;
7898 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7901 static int rxi_monitor_peerStats = 0;
7904 * rxi_AddRpcStat - given all of the information for a particular rpc
7905 * call, create (if needed) and update the stat totals for the rpc.
7909 * IN stats - the queue of stats that will be updated with the new value
7911 * IN rxInterface - a unique number that identifies the rpc interface
7913 * IN currentFunc - the index of the function being invoked
7915 * IN totalFunc - the total number of functions in this interface
7917 * IN queueTime - the amount of time this function waited for a thread
7919 * IN execTime - the amount of time this function invocation took to execute
7921 * IN bytesSent - the number bytes sent by this invocation
7923 * IN bytesRcvd - the number bytes received by this invocation
7925 * IN isServer - if true, this invocation was made to a server
7927 * IN remoteHost - the ip address of the remote host
7929 * IN remotePort - the port of the remote host
7931 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7933 * INOUT counter - if a new stats structure is allocated, the counter will
7934 * be updated with the new number of allocated stat structures
7942 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7943 afs_uint32 currentFunc, afs_uint32 totalFunc,
7944 struct clock *queueTime, struct clock *execTime,
7945 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7946 afs_uint32 remoteHost, afs_uint32 remotePort,
7947 int addToPeerList, unsigned int *counter)
7950 rx_interface_stat_p rpc_stat, nrpc_stat;
7953 * See if there's already a structure for this interface
7956 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7957 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7958 && (rpc_stat->stats[0].remote_is_server == isServer))
7963 * Didn't find a match so allocate a new structure and add it to the
7967 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7968 || (rpc_stat->stats[0].interfaceId != rxInterface)
7969 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7974 sizeof(rx_interface_stat_t) +
7975 totalFunc * sizeof(rx_function_entry_v1_t);
7977 rpc_stat = rxi_Alloc(space);
7978 if (rpc_stat == NULL) {
7982 *counter += totalFunc;
7983 for (i = 0; i < totalFunc; i++) {
7984 rpc_stat->stats[i].remote_peer = remoteHost;
7985 rpc_stat->stats[i].remote_port = remotePort;
7986 rpc_stat->stats[i].remote_is_server = isServer;
7987 rpc_stat->stats[i].interfaceId = rxInterface;
7988 rpc_stat->stats[i].func_total = totalFunc;
7989 rpc_stat->stats[i].func_index = i;
7990 hzero(rpc_stat->stats[i].invocations);
7991 hzero(rpc_stat->stats[i].bytes_sent);
7992 hzero(rpc_stat->stats[i].bytes_rcvd);
7993 rpc_stat->stats[i].queue_time_sum.sec = 0;
7994 rpc_stat->stats[i].queue_time_sum.usec = 0;
7995 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7996 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7997 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7998 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7999 rpc_stat->stats[i].queue_time_max.sec = 0;
8000 rpc_stat->stats[i].queue_time_max.usec = 0;
8001 rpc_stat->stats[i].execution_time_sum.sec = 0;
8002 rpc_stat->stats[i].execution_time_sum.usec = 0;
8003 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8004 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8005 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8006 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8007 rpc_stat->stats[i].execution_time_max.sec = 0;
8008 rpc_stat->stats[i].execution_time_max.usec = 0;
8010 queue_Prepend(stats, rpc_stat);
8011 if (addToPeerList) {
8012 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8017 * Increment the stats for this function
8020 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8021 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8022 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8023 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8024 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8025 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8026 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8028 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8029 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8031 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8032 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8034 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8035 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8037 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8038 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8046 * rx_IncrementTimeAndCount - increment the times and count for a particular
8051 * IN peer - the peer who invoked the rpc
8053 * IN rxInterface - a unique number that identifies the rpc interface
8055 * IN currentFunc - the index of the function being invoked
8057 * IN totalFunc - the total number of functions in this interface
8059 * IN queueTime - the amount of time this function waited for a thread
8061 * IN execTime - the amount of time this function invocation took to execute
8063 * IN bytesSent - the number bytes sent by this invocation
8065 * IN bytesRcvd - the number bytes received by this invocation
8067 * IN isServer - if true, this invocation was made to a server
8075 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8076 afs_uint32 currentFunc, afs_uint32 totalFunc,
8077 struct clock *queueTime, struct clock *execTime,
8078 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8082 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8085 MUTEX_ENTER(&rx_rpc_stats);
8087 if (rxi_monitor_peerStats) {
8088 MUTEX_ENTER(&peer->peer_lock);
8089 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8090 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8091 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8092 MUTEX_EXIT(&peer->peer_lock);
8095 if (rxi_monitor_processStats) {
8096 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8097 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8098 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8101 MUTEX_EXIT(&rx_rpc_stats);
8106 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8110 * IN callerVersion - the rpc stat version of the caller.
8112 * IN count - the number of entries to marshall.
8114 * IN stats - pointer to stats to be marshalled.
8116 * OUT ptr - Where to store the marshalled data.
8123 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8124 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8130 * We only support the first version
8132 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8133 *(ptr++) = stats->remote_peer;
8134 *(ptr++) = stats->remote_port;
8135 *(ptr++) = stats->remote_is_server;
8136 *(ptr++) = stats->interfaceId;
8137 *(ptr++) = stats->func_total;
8138 *(ptr++) = stats->func_index;
8139 *(ptr++) = hgethi(stats->invocations);
8140 *(ptr++) = hgetlo(stats->invocations);
8141 *(ptr++) = hgethi(stats->bytes_sent);
8142 *(ptr++) = hgetlo(stats->bytes_sent);
8143 *(ptr++) = hgethi(stats->bytes_rcvd);
8144 *(ptr++) = hgetlo(stats->bytes_rcvd);
8145 *(ptr++) = stats->queue_time_sum.sec;
8146 *(ptr++) = stats->queue_time_sum.usec;
8147 *(ptr++) = stats->queue_time_sum_sqr.sec;
8148 *(ptr++) = stats->queue_time_sum_sqr.usec;
8149 *(ptr++) = stats->queue_time_min.sec;
8150 *(ptr++) = stats->queue_time_min.usec;
8151 *(ptr++) = stats->queue_time_max.sec;
8152 *(ptr++) = stats->queue_time_max.usec;
8153 *(ptr++) = stats->execution_time_sum.sec;
8154 *(ptr++) = stats->execution_time_sum.usec;
8155 *(ptr++) = stats->execution_time_sum_sqr.sec;
8156 *(ptr++) = stats->execution_time_sum_sqr.usec;
8157 *(ptr++) = stats->execution_time_min.sec;
8158 *(ptr++) = stats->execution_time_min.usec;
8159 *(ptr++) = stats->execution_time_max.sec;
8160 *(ptr++) = stats->execution_time_max.usec;
8166 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8171 * IN callerVersion - the rpc stat version of the caller
8173 * OUT myVersion - the rpc stat version of this function
8175 * OUT clock_sec - local time seconds
8177 * OUT clock_usec - local time microseconds
8179 * OUT allocSize - the number of bytes allocated to contain stats
8181 * OUT statCount - the number stats retrieved from this process.
8183 * OUT stats - the actual stats retrieved from this process.
8187 * Returns void. If successful, stats will != NULL.
8191 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8192 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8193 size_t * allocSize, afs_uint32 * statCount,
8194 afs_uint32 ** stats)
8204 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8207 * Check to see if stats are enabled
8210 MUTEX_ENTER(&rx_rpc_stats);
8211 if (!rxi_monitor_processStats) {
8212 MUTEX_EXIT(&rx_rpc_stats);
8216 clock_GetTime(&now);
8217 *clock_sec = now.sec;
8218 *clock_usec = now.usec;
8221 * Allocate the space based upon the caller version
8223 * If the client is at an older version than we are,
8224 * we return the statistic data in the older data format, but
8225 * we still return our version number so the client knows we
8226 * are maintaining more data than it can retrieve.
8229 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8230 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8231 *statCount = rxi_rpc_process_stat_cnt;
8234 * This can't happen yet, but in the future version changes
8235 * can be handled by adding additional code here
8239 if (space > (size_t) 0) {
8241 ptr = *stats = rxi_Alloc(space);
8244 rx_interface_stat_p rpc_stat, nrpc_stat;
8248 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8250 * Copy the data based upon the caller version
8252 rx_MarshallProcessRPCStats(callerVersion,
8253 rpc_stat->stats[0].func_total,
8254 rpc_stat->stats, &ptr);
8260 MUTEX_EXIT(&rx_rpc_stats);
8265 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8269 * IN callerVersion - the rpc stat version of the caller
8271 * OUT myVersion - the rpc stat version of this function
8273 * OUT clock_sec - local time seconds
8275 * OUT clock_usec - local time microseconds
8277 * OUT allocSize - the number of bytes allocated to contain stats
8279 * OUT statCount - the number of stats retrieved from the individual
8282 * OUT stats - the actual stats retrieved from the individual peer structures.
8286 * Returns void. If successful, stats will != NULL.
8290 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8291 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8292 size_t * allocSize, afs_uint32 * statCount,
8293 afs_uint32 ** stats)
8303 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8306 * Check to see if stats are enabled
8309 MUTEX_ENTER(&rx_rpc_stats);
8310 if (!rxi_monitor_peerStats) {
8311 MUTEX_EXIT(&rx_rpc_stats);
8315 clock_GetTime(&now);
8316 *clock_sec = now.sec;
8317 *clock_usec = now.usec;
8320 * Allocate the space based upon the caller version
8322 * If the client is at an older version than we are,
8323 * we return the statistic data in the older data format, but
8324 * we still return our version number so the client knows we
8325 * are maintaining more data than it can retrieve.
8328 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8329 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8330 *statCount = rxi_rpc_peer_stat_cnt;
8333 * This can't happen yet, but in the future version changes
8334 * can be handled by adding additional code here
8338 if (space > (size_t) 0) {
8340 ptr = *stats = rxi_Alloc(space);
8343 rx_interface_stat_p rpc_stat, nrpc_stat;
8347 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8349 * We have to fix the offset of rpc_stat since we are
8350 * keeping this structure on two rx_queues. The rx_queue
8351 * package assumes that the rx_queue member is the first
8352 * member of the structure. That is, rx_queue assumes that
8353 * any one item is only on one queue at a time. We are
8354 * breaking that assumption and so we have to do a little
8355 * math to fix our pointers.
8358 fix_offset = (char *)rpc_stat;
8359 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8360 rpc_stat = (rx_interface_stat_p) fix_offset;
8363 * Copy the data based upon the caller version
8365 rx_MarshallProcessRPCStats(callerVersion,
8366 rpc_stat->stats[0].func_total,
8367 rpc_stat->stats, &ptr);
8373 MUTEX_EXIT(&rx_rpc_stats);
8378 * rx_FreeRPCStats - free memory allocated by
8379 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8383 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8384 * rx_RetrievePeerRPCStats
8386 * IN allocSize - the number of bytes in stats.
8394 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8396 rxi_Free(stats, allocSize);
8400 * rx_queryProcessRPCStats - see if process rpc stat collection is
8401 * currently enabled.
8407 * Returns 0 if stats are not enabled != 0 otherwise
8411 rx_queryProcessRPCStats(void)
8414 MUTEX_ENTER(&rx_rpc_stats);
8415 rc = rxi_monitor_processStats;
8416 MUTEX_EXIT(&rx_rpc_stats);
8421 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8427 * Returns 0 if stats are not enabled != 0 otherwise
8431 rx_queryPeerRPCStats(void)
8434 MUTEX_ENTER(&rx_rpc_stats);
8435 rc = rxi_monitor_peerStats;
8436 MUTEX_EXIT(&rx_rpc_stats);
8441 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8451 rx_enableProcessRPCStats(void)
8453 MUTEX_ENTER(&rx_rpc_stats);
8454 rx_enable_stats = 1;
8455 rxi_monitor_processStats = 1;
8456 MUTEX_EXIT(&rx_rpc_stats);
8460 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8470 rx_enablePeerRPCStats(void)
8472 MUTEX_ENTER(&rx_rpc_stats);
8473 rx_enable_stats = 1;
8474 rxi_monitor_peerStats = 1;
8475 MUTEX_EXIT(&rx_rpc_stats);
8479 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8489 rx_disableProcessRPCStats(void)
8491 rx_interface_stat_p rpc_stat, nrpc_stat;
8494 MUTEX_ENTER(&rx_rpc_stats);
8497 * Turn off process statistics and if peer stats is also off, turn
8501 rxi_monitor_processStats = 0;
8502 if (rxi_monitor_peerStats == 0) {
8503 rx_enable_stats = 0;
8506 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8507 unsigned int num_funcs = 0;
8510 queue_Remove(rpc_stat);
8511 num_funcs = rpc_stat->stats[0].func_total;
8513 sizeof(rx_interface_stat_t) +
8514 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8516 rxi_Free(rpc_stat, space);
8517 rxi_rpc_process_stat_cnt -= num_funcs;
8519 MUTEX_EXIT(&rx_rpc_stats);
8523 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8533 rx_disablePeerRPCStats(void)
8535 struct rx_peer **peer_ptr, **peer_end;
8539 * Turn off peer statistics and if process stats is also off, turn
8543 rxi_monitor_peerStats = 0;
8544 if (rxi_monitor_processStats == 0) {
8545 rx_enable_stats = 0;
8548 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8549 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8551 struct rx_peer *peer, *next, *prev;
8553 MUTEX_ENTER(&rx_peerHashTable_lock);
8554 MUTEX_ENTER(&rx_rpc_stats);
8555 for (prev = peer = *peer_ptr; peer; peer = next) {
8557 code = MUTEX_TRYENTER(&peer->peer_lock);
8559 rx_interface_stat_p rpc_stat, nrpc_stat;
8562 if (prev == *peer_ptr) {
8573 MUTEX_EXIT(&rx_peerHashTable_lock);
8576 (&peer->rpcStats, rpc_stat, nrpc_stat,
8577 rx_interface_stat)) {
8578 unsigned int num_funcs = 0;
8581 queue_Remove(&rpc_stat->queue_header);
8582 queue_Remove(&rpc_stat->all_peers);
8583 num_funcs = rpc_stat->stats[0].func_total;
8585 sizeof(rx_interface_stat_t) +
8586 rpc_stat->stats[0].func_total *
8587 sizeof(rx_function_entry_v1_t);
8589 rxi_Free(rpc_stat, space);
8590 rxi_rpc_peer_stat_cnt -= num_funcs;
8592 MUTEX_EXIT(&peer->peer_lock);
8594 MUTEX_ENTER(&rx_peerHashTable_lock);
8604 MUTEX_EXIT(&rx_rpc_stats);
8605 MUTEX_EXIT(&rx_peerHashTable_lock);
8610 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8615 * IN clearFlag - flag indicating which stats to clear
8623 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8625 rx_interface_stat_p rpc_stat, nrpc_stat;
8627 MUTEX_ENTER(&rx_rpc_stats);
8629 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8630 unsigned int num_funcs = 0, i;
8631 num_funcs = rpc_stat->stats[0].func_total;
8632 for (i = 0; i < num_funcs; i++) {
8633 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8634 hzero(rpc_stat->stats[i].invocations);
8636 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8637 hzero(rpc_stat->stats[i].bytes_sent);
8639 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8640 hzero(rpc_stat->stats[i].bytes_rcvd);
8642 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8643 rpc_stat->stats[i].queue_time_sum.sec = 0;
8644 rpc_stat->stats[i].queue_time_sum.usec = 0;
8646 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8647 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8648 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8650 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8651 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8652 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8654 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8655 rpc_stat->stats[i].queue_time_max.sec = 0;
8656 rpc_stat->stats[i].queue_time_max.usec = 0;
8658 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8659 rpc_stat->stats[i].execution_time_sum.sec = 0;
8660 rpc_stat->stats[i].execution_time_sum.usec = 0;
8662 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8663 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8664 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8666 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8667 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8668 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8670 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8671 rpc_stat->stats[i].execution_time_max.sec = 0;
8672 rpc_stat->stats[i].execution_time_max.usec = 0;
8677 MUTEX_EXIT(&rx_rpc_stats);
8681 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8686 * IN clearFlag - flag indicating which stats to clear
8694 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8696 rx_interface_stat_p rpc_stat, nrpc_stat;
8698 MUTEX_ENTER(&rx_rpc_stats);
8700 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8701 unsigned int num_funcs = 0, i;
8704 * We have to fix the offset of rpc_stat since we are
8705 * keeping this structure on two rx_queues. The rx_queue
8706 * package assumes that the rx_queue member is the first
8707 * member of the structure. That is, rx_queue assumes that
8708 * any one item is only on one queue at a time. We are
8709 * breaking that assumption and so we have to do a little
8710 * math to fix our pointers.
8713 fix_offset = (char *)rpc_stat;
8714 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8715 rpc_stat = (rx_interface_stat_p) fix_offset;
8717 num_funcs = rpc_stat->stats[0].func_total;
8718 for (i = 0; i < num_funcs; i++) {
8719 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8720 hzero(rpc_stat->stats[i].invocations);
8722 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8723 hzero(rpc_stat->stats[i].bytes_sent);
8725 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8726 hzero(rpc_stat->stats[i].bytes_rcvd);
8728 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8729 rpc_stat->stats[i].queue_time_sum.sec = 0;
8730 rpc_stat->stats[i].queue_time_sum.usec = 0;
8732 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8733 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8734 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8736 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8737 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8738 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8740 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8741 rpc_stat->stats[i].queue_time_max.sec = 0;
8742 rpc_stat->stats[i].queue_time_max.usec = 0;
8744 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8745 rpc_stat->stats[i].execution_time_sum.sec = 0;
8746 rpc_stat->stats[i].execution_time_sum.usec = 0;
8748 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8749 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8750 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8752 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8753 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8754 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8756 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8757 rpc_stat->stats[i].execution_time_max.sec = 0;
8758 rpc_stat->stats[i].execution_time_max.usec = 0;
8763 MUTEX_EXIT(&rx_rpc_stats);
8767 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8768 * is authorized to enable/disable/clear RX statistics.
8770 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8773 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8775 rxi_rxstat_userok = proc;
8779 rx_RxStatUserOk(struct rx_call *call)
8781 if (!rxi_rxstat_userok)
8783 return rxi_rxstat_userok(call);
8788 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8789 * function in the MSVC runtime DLL (msvcrt.dll).
8791 * Note: the system serializes calls to this function.
8794 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8795 DWORD reason, /* reason function is being called */
8796 LPVOID reserved) /* reserved for future use */
8799 case DLL_PROCESS_ATTACH:
8800 /* library is being attached to a process */
8804 case DLL_PROCESS_DETACH:
8811 #endif /* AFS_NT40_ENV */
8814 int rx_DumpCalls(FILE *outputFile, char *cookie)
8816 #ifdef RXDEBUG_PACKET
8817 #ifdef KDUMP_RX_LOCK
8818 struct rx_call_rx_lock *c;
8825 #define RXDPRINTF sprintf
8826 #define RXDPRINTOUT output
8828 #define RXDPRINTF fprintf
8829 #define RXDPRINTOUT outputFile
8832 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8834 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8837 for (c = rx_allCallsp; c; c = c->allNextp) {
8838 u_short rqc, tqc, iovqc;
8839 struct rx_packet *p, *np;
8841 MUTEX_ENTER(&c->lock);
8842 queue_Count(&c->rq, p, np, rx_packet, rqc);
8843 queue_Count(&c->tq, p, np, rx_packet, tqc);
8844 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8846 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, "
8847 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8848 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8849 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8850 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8851 #ifdef RX_ENABLE_LOCKS
8854 #ifdef RX_REFCOUNT_CHECK
8855 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8856 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8859 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,
8860 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8861 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8862 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8863 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8864 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8865 #ifdef RX_ENABLE_LOCKS
8866 , (afs_uint32)c->refCount
8868 #ifdef RX_REFCOUNT_CHECK
8869 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8872 MUTEX_EXIT(&c->lock);
8875 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8878 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8880 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8882 #endif /* RXDEBUG_PACKET */