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>
13 #include "afs/param.h"
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
30 # include "inet/common.h"
32 # include "inet/ip_ire.h"
34 # include "afs/afs_args.h"
35 # include "afs/afs_osi.h"
36 # ifdef RX_KERNEL_TRACE
37 # include "rx_kcommon.h"
39 # if defined(AFS_AIX_ENV)
43 # undef RXDEBUG /* turn off debugging */
45 # if defined(AFS_SGI_ENV)
46 # include "sys/debug.h"
49 # include "afs/sysincludes.h"
50 # include "afsincludes.h"
51 # endif /* !UKERNEL */
52 # include "afs/lock.h"
53 # include "rx_kmutex.h"
54 # include "rx_kernel.h"
55 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
56 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
57 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
58 extern afs_int32 afs_termState;
60 # include "sys/lockl.h"
61 # include "sys/lock_def.h"
62 # endif /* AFS_AIX41_ENV */
63 # include "afs/rxgen_consts.h"
66 # include <sys/types.h>
76 # include <afs/afsutil.h>
77 # include <WINNT\afsreg.h>
79 # include <sys/socket.h>
80 # include <sys/file.h>
82 # include <sys/stat.h>
83 # include <netinet/in.h>
84 # include <sys/time.h>
92 #include "rx_atomic.h"
93 #include "rx_globals.h"
95 #include "rx_internal.h"
98 #include <afs/rxgen_consts.h>
101 #ifdef AFS_PTHREAD_ENV
103 int (*registerProgram) (pid_t, char *) = 0;
104 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
107 int (*registerProgram) (PROCESS, char *) = 0;
108 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
112 /* Local static routines */
113 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
114 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
115 struct rx_peer *, struct clock *);
117 #ifdef RX_ENABLE_LOCKS
118 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
121 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
123 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
124 rx_atomic_t rxi_start_in_error;
126 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
129 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
130 * currently allocated within rx. This number is used to allocate the
131 * memory required to return the statistics when queried.
132 * Protected by the rx_rpc_stats mutex.
135 static unsigned int rxi_rpc_peer_stat_cnt;
138 * rxi_rpc_process_stat_cnt counts the total number of local process stat
139 * structures currently allocated within rx. The number is used to allocate
140 * the memory required to return the statistics when queried.
141 * Protected by the rx_rpc_stats mutex.
144 static unsigned int rxi_rpc_process_stat_cnt;
146 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
147 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
149 #if !defined(offsetof)
150 #include <stddef.h> /* for definition of offsetof() */
153 #ifdef RX_ENABLE_LOCKS
154 afs_kmutex_t rx_atomic_mutex;
157 #ifdef AFS_PTHREAD_ENV
160 * Use procedural initialization of mutexes/condition variables
164 extern afs_kmutex_t rx_quota_mutex;
165 extern afs_kmutex_t rx_pthread_mutex;
166 extern afs_kmutex_t rx_packets_mutex;
167 extern afs_kmutex_t rx_refcnt_mutex;
168 extern afs_kmutex_t des_init_mutex;
169 extern afs_kmutex_t des_random_mutex;
170 extern afs_kmutex_t rx_clock_mutex;
171 extern afs_kmutex_t rxi_connCacheMutex;
172 extern afs_kmutex_t rx_event_mutex;
173 extern afs_kmutex_t osi_malloc_mutex;
174 extern afs_kmutex_t event_handler_mutex;
175 extern afs_kmutex_t listener_mutex;
176 extern afs_kmutex_t rx_if_init_mutex;
177 extern afs_kmutex_t rx_if_mutex;
178 extern afs_kmutex_t rxkad_client_uid_mutex;
179 extern afs_kmutex_t rxkad_random_mutex;
181 extern afs_kcondvar_t rx_event_handler_cond;
182 extern afs_kcondvar_t rx_listener_cond;
184 static afs_kmutex_t epoch_mutex;
185 static afs_kmutex_t rx_init_mutex;
186 static afs_kmutex_t rx_debug_mutex;
187 static afs_kmutex_t rx_rpc_stats;
190 rxi_InitPthread(void)
192 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
193 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
194 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
212 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
213 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
215 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
216 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
218 rxkad_global_stats_init();
220 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
222 #ifdef RX_ENABLE_LOCKS
225 #endif /* RX_LOCKS_DB */
226 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
229 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
231 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
233 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
235 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
236 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
237 #endif /* RX_ENABLE_LOCKS */
240 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
241 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
243 * The rx_stats_mutex mutex protects the following global variables:
244 * rxi_lowConnRefCount
245 * rxi_lowPeerRefCount
254 * The rx_quota_mutex mutex protects the following global variables:
262 * The rx_freePktQ_lock protects the following global variables:
267 * The rx_packets_mutex mutex protects the following global variables:
275 * The rx_pthread_mutex mutex protects the following global variables:
276 * rxi_fcfs_thread_num
279 #define INIT_PTHREAD_LOCKS
283 /* Variables for handling the minProcs implementation. availProcs gives the
284 * number of threads available in the pool at this moment (not counting dudes
285 * executing right now). totalMin gives the total number of procs required
286 * for handling all minProcs requests. minDeficit is a dynamic variable
287 * tracking the # of procs required to satisfy all of the remaining minProcs
289 * For fine grain locking to work, the quota check and the reservation of
290 * a server thread has to come while rxi_availProcs and rxi_minDeficit
291 * are locked. To this end, the code has been modified under #ifdef
292 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
293 * same time. A new function, ReturnToServerPool() returns the allocation.
295 * A call can be on several queue's (but only one at a time). When
296 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
297 * that no one else is touching the queue. To this end, we store the address
298 * of the queue lock in the call structure (under the call lock) when we
299 * put the call on a queue, and we clear the call_queue_lock when the
300 * call is removed from a queue (once the call lock has been obtained).
301 * This allows rxi_ResetCall to safely synchronize with others wishing
302 * to manipulate the queue.
305 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
306 static afs_kmutex_t rx_rpc_stats;
307 void rxi_StartUnlocked(struct rxevent *event, void *call,
308 void *arg1, int istack);
311 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
312 ** pretty good that the next packet coming in is from the same connection
313 ** as the last packet, since we're send multiple packets in a transmit window.
315 struct rx_connection *rxLastConn = 0;
317 #ifdef RX_ENABLE_LOCKS
318 /* The locking hierarchy for rx fine grain locking is composed of these
321 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
322 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
323 * call->lock - locks call data fields.
324 * These are independent of each other:
325 * rx_freeCallQueue_lock
330 * serverQueueEntry->lock
331 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
333 * peer->lock - locks peer data fields.
334 * conn_data_lock - that more than one thread is not updating a conn data
335 * field at the same time.
346 * Do we need a lock to protect the peer field in the conn structure?
347 * conn->peer was previously a constant for all intents and so has no
348 * lock protecting this field. The multihomed client delta introduced
349 * a RX code change : change the peer field in the connection structure
350 * to that remote interface from which the last packet for this
351 * connection was sent out. This may become an issue if further changes
354 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
355 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
357 /* rxdb_fileID is used to identify the lock location, along with line#. */
358 static int rxdb_fileID = RXDB_FILE_RX;
359 #endif /* RX_LOCKS_DB */
360 #else /* RX_ENABLE_LOCKS */
361 #define SET_CALL_QUEUE_LOCK(C, L)
362 #define CLEAR_CALL_QUEUE_LOCK(C)
363 #endif /* RX_ENABLE_LOCKS */
364 struct rx_serverQueueEntry *rx_waitForPacket = 0;
365 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
367 /* ------------Exported Interfaces------------- */
369 /* This function allows rxkad to set the epoch to a suitably random number
370 * which rx_NewConnection will use in the future. The principle purpose is to
371 * get rxnull connections to use the same epoch as the rxkad connections do, at
372 * least once the first rxkad connection is established. This is important now
373 * that the host/port addresses aren't used in FindConnection: the uniqueness
374 * of epoch/cid matters and the start time won't do. */
376 #ifdef AFS_PTHREAD_ENV
378 * This mutex protects the following global variables:
382 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
383 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
387 #endif /* AFS_PTHREAD_ENV */
390 rx_SetEpoch(afs_uint32 epoch)
397 /* Initialize rx. A port number may be mentioned, in which case this
398 * becomes the default port number for any service installed later.
399 * If 0 is provided for the port number, a random port will be chosen
400 * by the kernel. Whether this will ever overlap anything in
401 * /etc/services is anybody's guess... Returns 0 on success, -1 on
406 int rxinit_status = 1;
407 #ifdef AFS_PTHREAD_ENV
409 * This mutex protects the following global variables:
413 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
414 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
417 #define UNLOCK_RX_INIT
421 rx_InitHost(u_int host, u_int port)
428 char *htable, *ptable;
435 if (rxinit_status == 0) {
436 tmp_status = rxinit_status;
438 return tmp_status; /* Already started; return previous error code. */
444 if (afs_winsockInit() < 0)
450 * Initialize anything necessary to provide a non-premptive threading
453 rxi_InitializeThreadSupport();
456 /* Allocate and initialize a socket for client and perhaps server
459 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
460 if (rx_socket == OSI_NULLSOCKET) {
464 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
467 #endif /* RX_LOCKS_DB */
468 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
469 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
470 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
471 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
472 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
478 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
480 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
482 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
484 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
485 #if defined(AFS_HPUX110_ENV)
487 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
488 #endif /* AFS_HPUX110_ENV */
489 #endif /* RX_ENABLE_LOCKS && KERNEL */
492 rx_connDeadTime = 12;
493 rx_tranquil = 0; /* reset flag */
494 rxi_ResetStatistics();
496 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
497 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
498 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
499 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
500 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
501 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
503 /* Malloc up a bunch of packets & buffers */
505 queue_Init(&rx_freePacketQueue);
506 rxi_NeedMorePackets = FALSE;
507 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
509 /* enforce a minimum number of allocated packets */
510 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
511 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
513 /* allocate the initial free packet pool */
514 #ifdef RX_ENABLE_TSFPQ
515 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
516 #else /* RX_ENABLE_TSFPQ */
517 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
518 #endif /* RX_ENABLE_TSFPQ */
525 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
526 tv.tv_sec = clock_now.sec;
527 tv.tv_usec = clock_now.usec;
528 srand((unsigned int)tv.tv_usec);
535 #if defined(KERNEL) && !defined(UKERNEL)
536 /* Really, this should never happen in a real kernel */
539 struct sockaddr_in addr;
541 int addrlen = sizeof(addr);
543 socklen_t addrlen = sizeof(addr);
545 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
549 rx_port = addr.sin_port;
552 rx_stats.minRtt.sec = 9999999;
554 rx_SetEpoch(tv.tv_sec | 0x80000000);
556 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
557 * will provide a randomer value. */
559 MUTEX_ENTER(&rx_quota_mutex);
560 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
561 MUTEX_EXIT(&rx_quota_mutex);
562 /* *Slightly* random start time for the cid. This is just to help
563 * out with the hashing function at the peer */
564 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
565 rx_connHashTable = (struct rx_connection **)htable;
566 rx_peerHashTable = (struct rx_peer **)ptable;
568 rx_lastAckDelay.sec = 0;
569 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
570 rx_hardAckDelay.sec = 0;
571 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
572 rx_softAckDelay.sec = 0;
573 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
575 rxevent_Init(20, rxi_ReScheduleEvents);
577 /* Initialize various global queues */
578 queue_Init(&rx_idleServerQueue);
579 queue_Init(&rx_incomingCallQueue);
580 queue_Init(&rx_freeCallQueue);
582 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
583 /* Initialize our list of usable IP addresses. */
587 /* Start listener process (exact function is dependent on the
588 * implementation environment--kernel or user space) */
592 tmp_status = rxinit_status = 0;
600 return rx_InitHost(htonl(INADDR_ANY), port);
603 /* called with unincremented nRequestsRunning to see if it is OK to start
604 * a new thread in this service. Could be "no" for two reasons: over the
605 * max quota, or would prevent others from reaching their min quota.
607 #ifdef RX_ENABLE_LOCKS
608 /* This verion of QuotaOK reserves quota if it's ok while the
609 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
612 QuotaOK(struct rx_service *aservice)
614 /* check if over max quota */
615 if (aservice->nRequestsRunning >= aservice->maxProcs) {
619 /* under min quota, we're OK */
620 /* otherwise, can use only if there are enough to allow everyone
621 * to go to their min quota after this guy starts.
624 MUTEX_ENTER(&rx_quota_mutex);
625 if ((aservice->nRequestsRunning < aservice->minProcs)
626 || (rxi_availProcs > rxi_minDeficit)) {
627 aservice->nRequestsRunning++;
628 /* just started call in minProcs pool, need fewer to maintain
630 if (aservice->nRequestsRunning <= aservice->minProcs)
633 MUTEX_EXIT(&rx_quota_mutex);
636 MUTEX_EXIT(&rx_quota_mutex);
642 ReturnToServerPool(struct rx_service *aservice)
644 aservice->nRequestsRunning--;
645 MUTEX_ENTER(&rx_quota_mutex);
646 if (aservice->nRequestsRunning < aservice->minProcs)
649 MUTEX_EXIT(&rx_quota_mutex);
652 #else /* RX_ENABLE_LOCKS */
654 QuotaOK(struct rx_service *aservice)
657 /* under min quota, we're OK */
658 if (aservice->nRequestsRunning < aservice->minProcs)
661 /* check if over max quota */
662 if (aservice->nRequestsRunning >= aservice->maxProcs)
665 /* otherwise, can use only if there are enough to allow everyone
666 * to go to their min quota after this guy starts.
668 MUTEX_ENTER(&rx_quota_mutex);
669 if (rxi_availProcs > rxi_minDeficit)
671 MUTEX_EXIT(&rx_quota_mutex);
674 #endif /* RX_ENABLE_LOCKS */
677 /* Called by rx_StartServer to start up lwp's to service calls.
678 NExistingProcs gives the number of procs already existing, and which
679 therefore needn't be created. */
681 rxi_StartServerProcs(int nExistingProcs)
683 struct rx_service *service;
688 /* For each service, reserve N processes, where N is the "minimum"
689 * number of processes that MUST be able to execute a request in parallel,
690 * at any time, for that process. Also compute the maximum difference
691 * between any service's maximum number of processes that can run
692 * (i.e. the maximum number that ever will be run, and a guarantee
693 * that this number will run if other services aren't running), and its
694 * minimum number. The result is the extra number of processes that
695 * we need in order to provide the latter guarantee */
696 for (i = 0; i < RX_MAX_SERVICES; i++) {
698 service = rx_services[i];
699 if (service == (struct rx_service *)0)
701 nProcs += service->minProcs;
702 diff = service->maxProcs - service->minProcs;
706 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
707 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
708 for (i = 0; i < nProcs; i++) {
709 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
715 /* This routine is only required on Windows */
717 rx_StartClientThread(void)
719 #ifdef AFS_PTHREAD_ENV
721 pid = pthread_self();
722 #endif /* AFS_PTHREAD_ENV */
724 #endif /* AFS_NT40_ENV */
726 /* This routine must be called if any services are exported. If the
727 * donateMe flag is set, the calling process is donated to the server
730 rx_StartServer(int donateMe)
732 struct rx_service *service;
738 /* Start server processes, if necessary (exact function is dependent
739 * on the implementation environment--kernel or user space). DonateMe
740 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
741 * case, one less new proc will be created rx_StartServerProcs.
743 rxi_StartServerProcs(donateMe);
745 /* count up the # of threads in minProcs, and add set the min deficit to
746 * be that value, too.
748 for (i = 0; i < RX_MAX_SERVICES; i++) {
749 service = rx_services[i];
750 if (service == (struct rx_service *)0)
752 MUTEX_ENTER(&rx_quota_mutex);
753 rxi_totalMin += service->minProcs;
754 /* below works even if a thread is running, since minDeficit would
755 * still have been decremented and later re-incremented.
757 rxi_minDeficit += service->minProcs;
758 MUTEX_EXIT(&rx_quota_mutex);
761 /* Turn on reaping of idle server connections */
762 rxi_ReapConnections(NULL, NULL, NULL);
771 #ifdef AFS_PTHREAD_ENV
773 pid = afs_pointer_to_int(pthread_self());
774 #else /* AFS_PTHREAD_ENV */
776 LWP_CurrentProcess(&pid);
777 #endif /* AFS_PTHREAD_ENV */
779 sprintf(name, "srv_%d", ++nProcs);
781 (*registerProgram) (pid, name);
783 #endif /* AFS_NT40_ENV */
784 rx_ServerProc(NULL); /* Never returns */
786 #ifdef RX_ENABLE_TSFPQ
787 /* no use leaving packets around in this thread's local queue if
788 * it isn't getting donated to the server thread pool.
790 rxi_FlushLocalPacketsTSFPQ();
791 #endif /* RX_ENABLE_TSFPQ */
795 /* Create a new client connection to the specified service, using the
796 * specified security object to implement the security model for this
798 struct rx_connection *
799 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
800 struct rx_securityClass *securityObject,
801 int serviceSecurityIndex)
805 struct rx_connection *conn;
810 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
811 "serviceSecurityIndex %d)\n",
812 ntohl(shost), ntohs(sport), sservice, securityObject,
813 serviceSecurityIndex));
815 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
816 * the case of kmem_alloc? */
817 conn = rxi_AllocConnection();
818 #ifdef RX_ENABLE_LOCKS
819 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
820 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
821 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
824 MUTEX_ENTER(&rx_connHashTable_lock);
825 cid = (rx_nextCid += RX_MAXCALLS);
826 conn->type = RX_CLIENT_CONNECTION;
828 conn->epoch = rx_epoch;
829 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
830 conn->serviceId = sservice;
831 conn->securityObject = securityObject;
832 conn->securityData = (void *) 0;
833 conn->securityIndex = serviceSecurityIndex;
834 rx_SetConnDeadTime(conn, rx_connDeadTime);
835 rx_SetConnSecondsUntilNatPing(conn, 0);
836 conn->ackRate = RX_FAST_ACK_RATE;
838 conn->specific = NULL;
839 conn->challengeEvent = NULL;
840 conn->delayedAbortEvent = NULL;
841 conn->abortCount = 0;
843 for (i = 0; i < RX_MAXCALLS; i++) {
844 conn->twind[i] = rx_initSendWindow;
845 conn->rwind[i] = rx_initReceiveWindow;
846 conn->lastBusy[i] = 0;
849 RXS_NewConnection(securityObject, conn);
851 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
853 conn->refCount++; /* no lock required since only this thread knows... */
854 conn->next = rx_connHashTable[hashindex];
855 rx_connHashTable[hashindex] = conn;
857 rx_atomic_inc(&rx_stats.nClientConns);
858 MUTEX_EXIT(&rx_connHashTable_lock);
864 * Ensure a connection's timeout values are valid.
866 * @param[in] conn The connection to check
868 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
869 * unless idleDeadTime and/or hardDeadTime are not set
873 rxi_CheckConnTimeouts(struct rx_connection *conn)
875 /* a connection's timeouts must have the relationship
876 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
877 * total loss of network to a peer may cause an idle timeout instead of a
878 * dead timeout, simply because the idle timeout gets hit first. Also set
879 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
880 /* this logic is slightly complicated by the fact that
881 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
883 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
884 if (conn->idleDeadTime) {
885 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
887 if (conn->hardDeadTime) {
888 if (conn->idleDeadTime) {
889 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
891 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
897 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
899 /* The idea is to set the dead time to a value that allows several
900 * keepalives to be dropped without timing out the connection. */
901 conn->secondsUntilDead = seconds;
902 rxi_CheckConnTimeouts(conn);
903 conn->secondsUntilPing = conn->secondsUntilDead / 6;
907 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
909 conn->hardDeadTime = seconds;
910 rxi_CheckConnTimeouts(conn);
914 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
916 conn->idleDeadTime = seconds;
917 rxi_CheckConnTimeouts(conn);
920 int rxi_lowPeerRefCount = 0;
921 int rxi_lowConnRefCount = 0;
924 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
925 * NOTE: must not be called with rx_connHashTable_lock held.
928 rxi_CleanupConnection(struct rx_connection *conn)
930 /* Notify the service exporter, if requested, that this connection
931 * is being destroyed */
932 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
933 (*conn->service->destroyConnProc) (conn);
935 /* Notify the security module that this connection is being destroyed */
936 RXS_DestroyConnection(conn->securityObject, conn);
938 /* If this is the last connection using the rx_peer struct, set its
939 * idle time to now. rxi_ReapConnections will reap it if it's still
940 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
942 MUTEX_ENTER(&rx_peerHashTable_lock);
943 if (conn->peer->refCount < 2) {
944 conn->peer->idleWhen = clock_Sec();
945 if (conn->peer->refCount < 1) {
946 conn->peer->refCount = 1;
947 if (rx_stats_active) {
948 MUTEX_ENTER(&rx_stats_mutex);
949 rxi_lowPeerRefCount++;
950 MUTEX_EXIT(&rx_stats_mutex);
954 conn->peer->refCount--;
955 MUTEX_EXIT(&rx_peerHashTable_lock);
959 if (conn->type == RX_SERVER_CONNECTION)
960 rx_atomic_dec(&rx_stats.nServerConns);
962 rx_atomic_dec(&rx_stats.nClientConns);
965 if (conn->specific) {
967 for (i = 0; i < conn->nSpecific; i++) {
968 if (conn->specific[i] && rxi_keyCreate_destructor[i])
969 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
970 conn->specific[i] = NULL;
972 free(conn->specific);
974 conn->specific = NULL;
978 MUTEX_DESTROY(&conn->conn_call_lock);
979 MUTEX_DESTROY(&conn->conn_data_lock);
980 CV_DESTROY(&conn->conn_call_cv);
982 rxi_FreeConnection(conn);
985 /* Destroy the specified connection */
987 rxi_DestroyConnection(struct rx_connection *conn)
989 MUTEX_ENTER(&rx_connHashTable_lock);
990 rxi_DestroyConnectionNoLock(conn);
991 /* conn should be at the head of the cleanup list */
992 if (conn == rx_connCleanup_list) {
993 rx_connCleanup_list = rx_connCleanup_list->next;
994 MUTEX_EXIT(&rx_connHashTable_lock);
995 rxi_CleanupConnection(conn);
997 #ifdef RX_ENABLE_LOCKS
999 MUTEX_EXIT(&rx_connHashTable_lock);
1001 #endif /* RX_ENABLE_LOCKS */
1005 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1007 struct rx_connection **conn_ptr;
1009 struct rx_packet *packet;
1016 MUTEX_ENTER(&conn->conn_data_lock);
1017 MUTEX_ENTER(&rx_refcnt_mutex);
1018 if (conn->refCount > 0)
1021 if (rx_stats_active) {
1022 MUTEX_ENTER(&rx_stats_mutex);
1023 rxi_lowConnRefCount++;
1024 MUTEX_EXIT(&rx_stats_mutex);
1028 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1029 /* Busy; wait till the last guy before proceeding */
1030 MUTEX_EXIT(&rx_refcnt_mutex);
1031 MUTEX_EXIT(&conn->conn_data_lock);
1036 /* If the client previously called rx_NewCall, but it is still
1037 * waiting, treat this as a running call, and wait to destroy the
1038 * connection later when the call completes. */
1039 if ((conn->type == RX_CLIENT_CONNECTION)
1040 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1041 conn->flags |= RX_CONN_DESTROY_ME;
1042 MUTEX_EXIT(&conn->conn_data_lock);
1046 MUTEX_EXIT(&rx_refcnt_mutex);
1047 MUTEX_EXIT(&conn->conn_data_lock);
1049 /* Check for extant references to this connection */
1050 for (i = 0; i < RX_MAXCALLS; i++) {
1051 struct rx_call *call = conn->call[i];
1054 if (conn->type == RX_CLIENT_CONNECTION) {
1055 MUTEX_ENTER(&call->lock);
1056 if (call->delayedAckEvent) {
1057 /* Push the final acknowledgment out now--there
1058 * won't be a subsequent call to acknowledge the
1059 * last reply packets */
1060 rxevent_Cancel(call->delayedAckEvent, call,
1061 RX_CALL_REFCOUNT_DELAY);
1062 if (call->state == RX_STATE_PRECALL
1063 || call->state == RX_STATE_ACTIVE) {
1064 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1066 rxi_AckAll(NULL, call, 0);
1069 MUTEX_EXIT(&call->lock);
1073 #ifdef RX_ENABLE_LOCKS
1075 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1076 MUTEX_EXIT(&conn->conn_data_lock);
1078 /* Someone is accessing a packet right now. */
1082 #endif /* RX_ENABLE_LOCKS */
1085 /* Don't destroy the connection if there are any call
1086 * structures still in use */
1087 MUTEX_ENTER(&conn->conn_data_lock);
1088 conn->flags |= RX_CONN_DESTROY_ME;
1089 MUTEX_EXIT(&conn->conn_data_lock);
1094 if (conn->natKeepAliveEvent) {
1095 rxi_NatKeepAliveOff(conn);
1098 if (conn->delayedAbortEvent) {
1099 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1100 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1102 MUTEX_ENTER(&conn->conn_data_lock);
1103 rxi_SendConnectionAbort(conn, packet, 0, 1);
1104 MUTEX_EXIT(&conn->conn_data_lock);
1105 rxi_FreePacket(packet);
1109 /* Remove from connection hash table before proceeding */
1111 &rx_connHashTable[CONN_HASH
1112 (peer->host, peer->port, conn->cid, conn->epoch,
1114 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1115 if (*conn_ptr == conn) {
1116 *conn_ptr = conn->next;
1120 /* if the conn that we are destroying was the last connection, then we
1121 * clear rxLastConn as well */
1122 if (rxLastConn == conn)
1125 /* Make sure the connection is completely reset before deleting it. */
1126 /* get rid of pending events that could zap us later */
1127 if (conn->challengeEvent)
1128 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1129 if (conn->checkReachEvent)
1130 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1131 if (conn->natKeepAliveEvent)
1132 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1134 /* Add the connection to the list of destroyed connections that
1135 * need to be cleaned up. This is necessary to avoid deadlocks
1136 * in the routines we call to inform others that this connection is
1137 * being destroyed. */
1138 conn->next = rx_connCleanup_list;
1139 rx_connCleanup_list = conn;
1142 /* Externally available version */
1144 rx_DestroyConnection(struct rx_connection *conn)
1149 rxi_DestroyConnection(conn);
1154 rx_GetConnection(struct rx_connection *conn)
1159 MUTEX_ENTER(&rx_refcnt_mutex);
1161 MUTEX_EXIT(&rx_refcnt_mutex);
1165 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1166 /* Wait for the transmit queue to no longer be busy.
1167 * requires the call->lock to be held */
1169 rxi_WaitforTQBusy(struct rx_call *call) {
1170 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1171 call->flags |= RX_CALL_TQ_WAIT;
1173 #ifdef RX_ENABLE_LOCKS
1174 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1175 CV_WAIT(&call->cv_tq, &call->lock);
1176 #else /* RX_ENABLE_LOCKS */
1177 osi_rxSleep(&call->tq);
1178 #endif /* RX_ENABLE_LOCKS */
1180 if (call->tqWaiters == 0) {
1181 call->flags &= ~RX_CALL_TQ_WAIT;
1188 rxi_WakeUpTransmitQueue(struct rx_call *call)
1190 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1191 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1192 call, call->tqWaiters, call->flags));
1193 #ifdef RX_ENABLE_LOCKS
1194 osirx_AssertMine(&call->lock, "rxi_Start start");
1195 CV_BROADCAST(&call->cv_tq);
1196 #else /* RX_ENABLE_LOCKS */
1197 osi_rxWakeup(&call->tq);
1198 #endif /* RX_ENABLE_LOCKS */
1202 /* Start a new rx remote procedure call, on the specified connection.
1203 * If wait is set to 1, wait for a free call channel; otherwise return
1204 * 0. Maxtime gives the maximum number of seconds this call may take,
1205 * after rx_NewCall returns. After this time interval, a call to any
1206 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1207 * For fine grain locking, we hold the conn_call_lock in order to
1208 * to ensure that we don't get signalle after we found a call in an active
1209 * state and before we go to sleep.
1212 rx_NewCall(struct rx_connection *conn)
1214 int i, wait, ignoreBusy = 1;
1215 struct rx_call *call;
1216 struct clock queueTime;
1217 afs_uint32 leastBusy = 0;
1221 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1224 clock_GetTime(&queueTime);
1226 * Check if there are others waiting for a new call.
1227 * If so, let them go first to avoid starving them.
1228 * This is a fairly simple scheme, and might not be
1229 * a complete solution for large numbers of waiters.
1231 * makeCallWaiters keeps track of the number of
1232 * threads waiting to make calls and the
1233 * RX_CONN_MAKECALL_WAITING flag bit is used to
1234 * indicate that there are indeed calls waiting.
1235 * The flag is set when the waiter is incremented.
1236 * It is only cleared when makeCallWaiters is 0.
1237 * This prevents us from accidently destroying the
1238 * connection while it is potentially about to be used.
1240 MUTEX_ENTER(&conn->conn_call_lock);
1241 MUTEX_ENTER(&conn->conn_data_lock);
1242 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1243 conn->flags |= RX_CONN_MAKECALL_WAITING;
1244 conn->makeCallWaiters++;
1245 MUTEX_EXIT(&conn->conn_data_lock);
1247 #ifdef RX_ENABLE_LOCKS
1248 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1252 MUTEX_ENTER(&conn->conn_data_lock);
1253 conn->makeCallWaiters--;
1254 if (conn->makeCallWaiters == 0)
1255 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1258 /* We are now the active thread in rx_NewCall */
1259 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1260 MUTEX_EXIT(&conn->conn_data_lock);
1265 for (i = 0; i < RX_MAXCALLS; i++) {
1266 call = conn->call[i];
1268 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1269 /* we're not ignoring busy call slots; only look at the
1270 * call slot that is the "least" busy */
1274 if (call->state == RX_STATE_DALLY) {
1275 MUTEX_ENTER(&call->lock);
1276 if (call->state == RX_STATE_DALLY) {
1277 if (ignoreBusy && conn->lastBusy[i]) {
1278 /* if we're ignoring busy call slots, skip any ones that
1279 * have lastBusy set */
1280 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1281 leastBusy = conn->lastBusy[i];
1283 MUTEX_EXIT(&call->lock);
1288 * We are setting the state to RX_STATE_RESET to
1289 * ensure that no one else will attempt to use this
1290 * call once we drop the conn->conn_call_lock and
1291 * call->lock. We must drop the conn->conn_call_lock
1292 * before calling rxi_ResetCall because the process
1293 * of clearing the transmit queue can block for an
1294 * extended period of time. If we block while holding
1295 * the conn->conn_call_lock, then all rx_EndCall
1296 * processing will block as well. This has a detrimental
1297 * effect on overall system performance.
1299 call->state = RX_STATE_RESET;
1300 MUTEX_EXIT(&conn->conn_call_lock);
1301 MUTEX_ENTER(&rx_refcnt_mutex);
1302 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1303 MUTEX_EXIT(&rx_refcnt_mutex);
1304 rxi_ResetCall(call, 0);
1305 (*call->callNumber)++;
1306 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1310 * If we failed to be able to safely obtain the
1311 * conn->conn_call_lock we will have to drop the
1312 * call->lock to avoid a deadlock. When the call->lock
1313 * is released the state of the call can change. If it
1314 * is no longer RX_STATE_RESET then some other thread is
1317 MUTEX_EXIT(&call->lock);
1318 MUTEX_ENTER(&conn->conn_call_lock);
1319 MUTEX_ENTER(&call->lock);
1321 if (call->state == RX_STATE_RESET)
1325 * If we get here it means that after dropping
1326 * the conn->conn_call_lock and call->lock that
1327 * the call is no longer ours. If we can't find
1328 * a free call in the remaining slots we should
1329 * not go immediately to RX_CONN_MAKECALL_WAITING
1330 * because by dropping the conn->conn_call_lock
1331 * we have given up synchronization with rx_EndCall.
1332 * Instead, cycle through one more time to see if
1333 * we can find a call that can call our own.
1335 MUTEX_ENTER(&rx_refcnt_mutex);
1336 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1337 MUTEX_EXIT(&rx_refcnt_mutex);
1340 MUTEX_EXIT(&call->lock);
1343 if (ignoreBusy && conn->lastBusy[i]) {
1344 /* if we're ignoring busy call slots, skip any ones that
1345 * have lastBusy set */
1346 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1347 leastBusy = conn->lastBusy[i];
1352 /* rxi_NewCall returns with mutex locked */
1353 call = rxi_NewCall(conn, i);
1354 MUTEX_ENTER(&rx_refcnt_mutex);
1355 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1356 MUTEX_EXIT(&rx_refcnt_mutex);
1360 if (i < RX_MAXCALLS) {
1361 conn->lastBusy[i] = 0;
1366 if (leastBusy && ignoreBusy) {
1367 /* we didn't find a useable call slot, but we did see at least one
1368 * 'busy' slot; look again and only use a slot with the 'least
1374 MUTEX_ENTER(&conn->conn_data_lock);
1375 conn->flags |= RX_CONN_MAKECALL_WAITING;
1376 conn->makeCallWaiters++;
1377 MUTEX_EXIT(&conn->conn_data_lock);
1379 #ifdef RX_ENABLE_LOCKS
1380 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1384 MUTEX_ENTER(&conn->conn_data_lock);
1385 conn->makeCallWaiters--;
1386 if (conn->makeCallWaiters == 0)
1387 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1388 MUTEX_EXIT(&conn->conn_data_lock);
1390 /* Client is initially in send mode */
1391 call->state = RX_STATE_ACTIVE;
1392 call->error = conn->error;
1394 call->mode = RX_MODE_ERROR;
1396 call->mode = RX_MODE_SENDING;
1398 /* remember start time for call in case we have hard dead time limit */
1399 call->queueTime = queueTime;
1400 clock_GetTime(&call->startTime);
1401 hzero(call->bytesSent);
1402 hzero(call->bytesRcvd);
1404 /* Turn on busy protocol. */
1405 rxi_KeepAliveOn(call);
1407 /* Attempt MTU discovery */
1408 rxi_GrowMTUOn(call);
1411 * We are no longer the active thread in rx_NewCall
1413 MUTEX_ENTER(&conn->conn_data_lock);
1414 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1415 MUTEX_EXIT(&conn->conn_data_lock);
1418 * Wake up anyone else who might be giving us a chance to
1419 * run (see code above that avoids resource starvation).
1421 #ifdef RX_ENABLE_LOCKS
1422 CV_BROADCAST(&conn->conn_call_cv);
1426 MUTEX_EXIT(&conn->conn_call_lock);
1428 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1429 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1430 osi_Panic("rx_NewCall call about to be used without an empty tq");
1432 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1434 MUTEX_EXIT(&call->lock);
1437 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1442 rxi_HasActiveCalls(struct rx_connection *aconn)
1445 struct rx_call *tcall;
1449 for (i = 0; i < RX_MAXCALLS; i++) {
1450 if ((tcall = aconn->call[i])) {
1451 if ((tcall->state == RX_STATE_ACTIVE)
1452 || (tcall->state == RX_STATE_PRECALL)) {
1463 rxi_GetCallNumberVector(struct rx_connection *aconn,
1464 afs_int32 * aint32s)
1467 struct rx_call *tcall;
1471 for (i = 0; i < RX_MAXCALLS; i++) {
1472 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1473 aint32s[i] = aconn->callNumber[i] + 1;
1475 aint32s[i] = aconn->callNumber[i];
1482 rxi_SetCallNumberVector(struct rx_connection *aconn,
1483 afs_int32 * aint32s)
1486 struct rx_call *tcall;
1490 for (i = 0; i < RX_MAXCALLS; i++) {
1491 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1492 aconn->callNumber[i] = aint32s[i] - 1;
1494 aconn->callNumber[i] = aint32s[i];
1500 /* Advertise a new service. A service is named locally by a UDP port
1501 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1504 char *serviceName; Name for identification purposes (e.g. the
1505 service name might be used for probing for
1508 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1509 char *serviceName, struct rx_securityClass **securityObjects,
1510 int nSecurityObjects,
1511 afs_int32(*serviceProc) (struct rx_call * acall))
1513 osi_socket socket = OSI_NULLSOCKET;
1514 struct rx_service *tservice;
1520 if (serviceId == 0) {
1522 "rx_NewService: service id for service %s is not non-zero.\n",
1529 "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",
1537 tservice = rxi_AllocService();
1540 #ifdef RX_ENABLE_LOCKS
1541 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1544 for (i = 0; i < RX_MAX_SERVICES; i++) {
1545 struct rx_service *service = rx_services[i];
1547 if (port == service->servicePort && host == service->serviceHost) {
1548 if (service->serviceId == serviceId) {
1549 /* The identical service has already been
1550 * installed; if the caller was intending to
1551 * change the security classes used by this
1552 * service, he/she loses. */
1554 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1555 serviceName, serviceId, service->serviceName);
1557 rxi_FreeService(tservice);
1560 /* Different service, same port: re-use the socket
1561 * which is bound to the same port */
1562 socket = service->socket;
1565 if (socket == OSI_NULLSOCKET) {
1566 /* If we don't already have a socket (from another
1567 * service on same port) get a new one */
1568 socket = rxi_GetHostUDPSocket(host, port);
1569 if (socket == OSI_NULLSOCKET) {
1571 rxi_FreeService(tservice);
1576 service->socket = socket;
1577 service->serviceHost = host;
1578 service->servicePort = port;
1579 service->serviceId = serviceId;
1580 service->serviceName = serviceName;
1581 service->nSecurityObjects = nSecurityObjects;
1582 service->securityObjects = securityObjects;
1583 service->minProcs = 0;
1584 service->maxProcs = 1;
1585 service->idleDeadTime = 60;
1586 service->idleDeadErr = 0;
1587 service->connDeadTime = rx_connDeadTime;
1588 service->executeRequestProc = serviceProc;
1589 service->checkReach = 0;
1590 service->nSpecific = 0;
1591 service->specific = NULL;
1592 rx_services[i] = service; /* not visible until now */
1598 rxi_FreeService(tservice);
1599 (osi_Msg "rx_NewService: cannot support > %d services\n",
1604 /* Set configuration options for all of a service's security objects */
1607 rx_SetSecurityConfiguration(struct rx_service *service,
1608 rx_securityConfigVariables type,
1612 for (i = 0; i<service->nSecurityObjects; i++) {
1613 if (service->securityObjects[i]) {
1614 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1622 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1623 struct rx_securityClass **securityObjects, int nSecurityObjects,
1624 afs_int32(*serviceProc) (struct rx_call * acall))
1626 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1629 /* Generic request processing loop. This routine should be called
1630 * by the implementation dependent rx_ServerProc. If socketp is
1631 * non-null, it will be set to the file descriptor that this thread
1632 * is now listening on. If socketp is null, this routine will never
1635 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1637 struct rx_call *call;
1639 struct rx_service *tservice = NULL;
1646 call = rx_GetCall(threadID, tservice, socketp);
1647 if (socketp && *socketp != OSI_NULLSOCKET) {
1648 /* We are now a listener thread */
1653 /* if server is restarting( typically smooth shutdown) then do not
1654 * allow any new calls.
1657 if (rx_tranquil && (call != NULL)) {
1661 MUTEX_ENTER(&call->lock);
1663 rxi_CallError(call, RX_RESTARTING);
1664 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1666 MUTEX_EXIT(&call->lock);
1670 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1671 #ifdef RX_ENABLE_LOCKS
1673 #endif /* RX_ENABLE_LOCKS */
1674 afs_termState = AFSOP_STOP_AFS;
1675 afs_osi_Wakeup(&afs_termState);
1676 #ifdef RX_ENABLE_LOCKS
1678 #endif /* RX_ENABLE_LOCKS */
1683 tservice = call->conn->service;
1685 if (tservice->beforeProc)
1686 (*tservice->beforeProc) (call);
1688 code = tservice->executeRequestProc(call);
1690 if (tservice->afterProc)
1691 (*tservice->afterProc) (call, code);
1693 rx_EndCall(call, code);
1694 if (rx_stats_active) {
1695 MUTEX_ENTER(&rx_stats_mutex);
1697 MUTEX_EXIT(&rx_stats_mutex);
1704 rx_WakeupServerProcs(void)
1706 struct rx_serverQueueEntry *np, *tqp;
1710 MUTEX_ENTER(&rx_serverPool_lock);
1712 #ifdef RX_ENABLE_LOCKS
1713 if (rx_waitForPacket)
1714 CV_BROADCAST(&rx_waitForPacket->cv);
1715 #else /* RX_ENABLE_LOCKS */
1716 if (rx_waitForPacket)
1717 osi_rxWakeup(rx_waitForPacket);
1718 #endif /* RX_ENABLE_LOCKS */
1719 MUTEX_ENTER(&freeSQEList_lock);
1720 for (np = rx_FreeSQEList; np; np = tqp) {
1721 tqp = *(struct rx_serverQueueEntry **)np;
1722 #ifdef RX_ENABLE_LOCKS
1723 CV_BROADCAST(&np->cv);
1724 #else /* RX_ENABLE_LOCKS */
1726 #endif /* RX_ENABLE_LOCKS */
1728 MUTEX_EXIT(&freeSQEList_lock);
1729 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1730 #ifdef RX_ENABLE_LOCKS
1731 CV_BROADCAST(&np->cv);
1732 #else /* RX_ENABLE_LOCKS */
1734 #endif /* RX_ENABLE_LOCKS */
1736 MUTEX_EXIT(&rx_serverPool_lock);
1741 * One thing that seems to happen is that all the server threads get
1742 * tied up on some empty or slow call, and then a whole bunch of calls
1743 * arrive at once, using up the packet pool, so now there are more
1744 * empty calls. The most critical resources here are server threads
1745 * and the free packet pool. The "doreclaim" code seems to help in
1746 * general. I think that eventually we arrive in this state: there
1747 * are lots of pending calls which do have all their packets present,
1748 * so they won't be reclaimed, are multi-packet calls, so they won't
1749 * be scheduled until later, and thus are tying up most of the free
1750 * packet pool for a very long time.
1752 * 1. schedule multi-packet calls if all the packets are present.
1753 * Probably CPU-bound operation, useful to return packets to pool.
1754 * Do what if there is a full window, but the last packet isn't here?
1755 * 3. preserve one thread which *only* runs "best" calls, otherwise
1756 * it sleeps and waits for that type of call.
1757 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1758 * the current dataquota business is badly broken. The quota isn't adjusted
1759 * to reflect how many packets are presently queued for a running call.
1760 * So, when we schedule a queued call with a full window of packets queued
1761 * up for it, that *should* free up a window full of packets for other 2d-class
1762 * calls to be able to use from the packet pool. But it doesn't.
1764 * NB. Most of the time, this code doesn't run -- since idle server threads
1765 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1766 * as a new call arrives.
1768 /* Sleep until a call arrives. Returns a pointer to the call, ready
1769 * for an rx_Read. */
1770 #ifdef RX_ENABLE_LOCKS
1772 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1774 struct rx_serverQueueEntry *sq;
1775 struct rx_call *call = (struct rx_call *)0;
1776 struct rx_service *service = NULL;
1779 MUTEX_ENTER(&freeSQEList_lock);
1781 if ((sq = rx_FreeSQEList)) {
1782 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1783 MUTEX_EXIT(&freeSQEList_lock);
1784 } else { /* otherwise allocate a new one and return that */
1785 MUTEX_EXIT(&freeSQEList_lock);
1786 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1787 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1788 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1791 MUTEX_ENTER(&rx_serverPool_lock);
1792 if (cur_service != NULL) {
1793 ReturnToServerPool(cur_service);
1796 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1797 struct rx_call *tcall, *ncall, *choice2 = NULL;
1799 /* Scan for eligible incoming calls. A call is not eligible
1800 * if the maximum number of calls for its service type are
1801 * already executing */
1802 /* One thread will process calls FCFS (to prevent starvation),
1803 * while the other threads may run ahead looking for calls which
1804 * have all their input data available immediately. This helps
1805 * keep threads from blocking, waiting for data from the client. */
1806 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1807 service = tcall->conn->service;
1808 if (!QuotaOK(service)) {
1811 MUTEX_ENTER(&rx_pthread_mutex);
1812 if (tno == rxi_fcfs_thread_num
1813 || !tcall->queue_item_header.next) {
1814 MUTEX_EXIT(&rx_pthread_mutex);
1815 /* If we're the fcfs thread , then we'll just use
1816 * this call. If we haven't been able to find an optimal
1817 * choice, and we're at the end of the list, then use a
1818 * 2d choice if one has been identified. Otherwise... */
1819 call = (choice2 ? choice2 : tcall);
1820 service = call->conn->service;
1822 MUTEX_EXIT(&rx_pthread_mutex);
1823 if (!queue_IsEmpty(&tcall->rq)) {
1824 struct rx_packet *rp;
1825 rp = queue_First(&tcall->rq, rx_packet);
1826 if (rp->header.seq == 1) {
1828 || (rp->header.flags & RX_LAST_PACKET)) {
1830 } else if (rxi_2dchoice && !choice2
1831 && !(tcall->flags & RX_CALL_CLEARED)
1832 && (tcall->rprev > rxi_HardAckRate)) {
1842 ReturnToServerPool(service);
1849 MUTEX_EXIT(&rx_serverPool_lock);
1850 MUTEX_ENTER(&call->lock);
1852 if (call->flags & RX_CALL_WAIT_PROC) {
1853 call->flags &= ~RX_CALL_WAIT_PROC;
1854 rx_atomic_dec(&rx_nWaiting);
1857 if (call->state != RX_STATE_PRECALL || call->error) {
1858 MUTEX_EXIT(&call->lock);
1859 MUTEX_ENTER(&rx_serverPool_lock);
1860 ReturnToServerPool(service);
1865 if (queue_IsEmpty(&call->rq)
1866 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1867 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1869 CLEAR_CALL_QUEUE_LOCK(call);
1872 /* If there are no eligible incoming calls, add this process
1873 * to the idle server queue, to wait for one */
1877 *socketp = OSI_NULLSOCKET;
1879 sq->socketp = socketp;
1880 queue_Append(&rx_idleServerQueue, sq);
1881 #ifndef AFS_AIX41_ENV
1882 rx_waitForPacket = sq;
1884 rx_waitingForPacket = sq;
1885 #endif /* AFS_AIX41_ENV */
1887 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1889 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1890 MUTEX_EXIT(&rx_serverPool_lock);
1891 return (struct rx_call *)0;
1894 } while (!(call = sq->newcall)
1895 && !(socketp && *socketp != OSI_NULLSOCKET));
1896 MUTEX_EXIT(&rx_serverPool_lock);
1898 MUTEX_ENTER(&call->lock);
1904 MUTEX_ENTER(&freeSQEList_lock);
1905 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1906 rx_FreeSQEList = sq;
1907 MUTEX_EXIT(&freeSQEList_lock);
1910 clock_GetTime(&call->startTime);
1911 call->state = RX_STATE_ACTIVE;
1912 call->mode = RX_MODE_RECEIVING;
1913 #ifdef RX_KERNEL_TRACE
1914 if (ICL_SETACTIVE(afs_iclSetp)) {
1915 int glockOwner = ISAFS_GLOCK();
1918 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1919 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1926 rxi_calltrace(RX_CALL_START, call);
1927 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1928 call->conn->service->servicePort, call->conn->service->serviceId,
1931 MUTEX_EXIT(&call->lock);
1932 MUTEX_ENTER(&rx_refcnt_mutex);
1933 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1934 MUTEX_EXIT(&rx_refcnt_mutex);
1936 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1941 #else /* RX_ENABLE_LOCKS */
1943 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1945 struct rx_serverQueueEntry *sq;
1946 struct rx_call *call = (struct rx_call *)0, *choice2;
1947 struct rx_service *service = NULL;
1951 MUTEX_ENTER(&freeSQEList_lock);
1953 if ((sq = rx_FreeSQEList)) {
1954 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1955 MUTEX_EXIT(&freeSQEList_lock);
1956 } else { /* otherwise allocate a new one and return that */
1957 MUTEX_EXIT(&freeSQEList_lock);
1958 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1959 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1960 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1962 MUTEX_ENTER(&sq->lock);
1964 if (cur_service != NULL) {
1965 cur_service->nRequestsRunning--;
1966 MUTEX_ENTER(&rx_quota_mutex);
1967 if (cur_service->nRequestsRunning < cur_service->minProcs)
1970 MUTEX_EXIT(&rx_quota_mutex);
1972 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1973 struct rx_call *tcall, *ncall;
1974 /* Scan for eligible incoming calls. A call is not eligible
1975 * if the maximum number of calls for its service type are
1976 * already executing */
1977 /* One thread will process calls FCFS (to prevent starvation),
1978 * while the other threads may run ahead looking for calls which
1979 * have all their input data available immediately. This helps
1980 * keep threads from blocking, waiting for data from the client. */
1981 choice2 = (struct rx_call *)0;
1982 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1983 service = tcall->conn->service;
1984 if (QuotaOK(service)) {
1985 MUTEX_ENTER(&rx_pthread_mutex);
1986 if (tno == rxi_fcfs_thread_num
1987 || !tcall->queue_item_header.next) {
1988 MUTEX_EXIT(&rx_pthread_mutex);
1989 /* If we're the fcfs thread, then we'll just use
1990 * this call. If we haven't been able to find an optimal
1991 * choice, and we're at the end of the list, then use a
1992 * 2d choice if one has been identified. Otherwise... */
1993 call = (choice2 ? choice2 : tcall);
1994 service = call->conn->service;
1996 MUTEX_EXIT(&rx_pthread_mutex);
1997 if (!queue_IsEmpty(&tcall->rq)) {
1998 struct rx_packet *rp;
1999 rp = queue_First(&tcall->rq, rx_packet);
2000 if (rp->header.seq == 1
2002 || (rp->header.flags & RX_LAST_PACKET))) {
2004 } else if (rxi_2dchoice && !choice2
2005 && !(tcall->flags & RX_CALL_CLEARED)
2006 && (tcall->rprev > rxi_HardAckRate)) {
2020 /* we can't schedule a call if there's no data!!! */
2021 /* send an ack if there's no data, if we're missing the
2022 * first packet, or we're missing something between first
2023 * and last -- there's a "hole" in the incoming data. */
2024 if (queue_IsEmpty(&call->rq)
2025 || queue_First(&call->rq, rx_packet)->header.seq != 1
2026 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2027 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2029 call->flags &= (~RX_CALL_WAIT_PROC);
2030 service->nRequestsRunning++;
2031 /* just started call in minProcs pool, need fewer to maintain
2033 MUTEX_ENTER(&rx_quota_mutex);
2034 if (service->nRequestsRunning <= service->minProcs)
2037 MUTEX_EXIT(&rx_quota_mutex);
2038 rx_atomic_dec(&rx_nWaiting);
2039 /* MUTEX_EXIT(&call->lock); */
2041 /* If there are no eligible incoming calls, add this process
2042 * to the idle server queue, to wait for one */
2045 *socketp = OSI_NULLSOCKET;
2047 sq->socketp = socketp;
2048 queue_Append(&rx_idleServerQueue, sq);
2052 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2054 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2055 return (struct rx_call *)0;
2058 } while (!(call = sq->newcall)
2059 && !(socketp && *socketp != OSI_NULLSOCKET));
2061 MUTEX_EXIT(&sq->lock);
2063 MUTEX_ENTER(&freeSQEList_lock);
2064 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2065 rx_FreeSQEList = sq;
2066 MUTEX_EXIT(&freeSQEList_lock);
2069 clock_GetTime(&call->startTime);
2070 call->state = RX_STATE_ACTIVE;
2071 call->mode = RX_MODE_RECEIVING;
2072 #ifdef RX_KERNEL_TRACE
2073 if (ICL_SETACTIVE(afs_iclSetp)) {
2074 int glockOwner = ISAFS_GLOCK();
2077 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2078 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2085 rxi_calltrace(RX_CALL_START, call);
2086 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2087 call->conn->service->servicePort, call->conn->service->serviceId,
2090 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2097 #endif /* RX_ENABLE_LOCKS */
2101 /* Establish a procedure to be called when a packet arrives for a
2102 * call. This routine will be called at most once after each call,
2103 * and will also be called if there is an error condition on the or
2104 * the call is complete. Used by multi rx to build a selection
2105 * function which determines which of several calls is likely to be a
2106 * good one to read from.
2107 * NOTE: the way this is currently implemented it is probably only a
2108 * good idea to (1) use it immediately after a newcall (clients only)
2109 * and (2) only use it once. Other uses currently void your warranty
2112 rx_SetArrivalProc(struct rx_call *call,
2113 void (*proc) (struct rx_call * call,
2116 void * handle, int arg)
2118 call->arrivalProc = proc;
2119 call->arrivalProcHandle = handle;
2120 call->arrivalProcArg = arg;
2123 /* Call is finished (possibly prematurely). Return rc to the peer, if
2124 * appropriate, and return the final error code from the conversation
2128 rx_EndCall(struct rx_call *call, afs_int32 rc)
2130 struct rx_connection *conn = call->conn;
2134 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2135 call, rc, call->error, call->abortCode));
2138 MUTEX_ENTER(&call->lock);
2140 if (rc == 0 && call->error == 0) {
2141 call->abortCode = 0;
2142 call->abortCount = 0;
2145 call->arrivalProc = (void (*)())0;
2146 if (rc && call->error == 0) {
2147 rxi_CallError(call, rc);
2148 call->mode = RX_MODE_ERROR;
2149 /* Send an abort message to the peer if this error code has
2150 * only just been set. If it was set previously, assume the
2151 * peer has already been sent the error code or will request it
2153 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2155 if (conn->type == RX_SERVER_CONNECTION) {
2156 /* Make sure reply or at least dummy reply is sent */
2157 if (call->mode == RX_MODE_RECEIVING) {
2158 MUTEX_EXIT(&call->lock);
2159 rxi_WriteProc(call, 0, 0);
2160 MUTEX_ENTER(&call->lock);
2162 if (call->mode == RX_MODE_SENDING) {
2163 MUTEX_EXIT(&call->lock);
2164 rxi_FlushWrite(call);
2165 MUTEX_ENTER(&call->lock);
2167 rxi_calltrace(RX_CALL_END, call);
2168 /* Call goes to hold state until reply packets are acknowledged */
2169 if (call->tfirst + call->nSoftAcked < call->tnext) {
2170 call->state = RX_STATE_HOLD;
2172 call->state = RX_STATE_DALLY;
2173 rxi_ClearTransmitQueue(call, 0);
2174 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2175 rxevent_Cancel(call->keepAliveEvent, call,
2176 RX_CALL_REFCOUNT_ALIVE);
2178 } else { /* Client connection */
2180 /* Make sure server receives input packets, in the case where
2181 * no reply arguments are expected */
2182 if ((call->mode == RX_MODE_SENDING)
2183 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2184 MUTEX_EXIT(&call->lock);
2185 (void)rxi_ReadProc(call, &dummy, 1);
2186 MUTEX_ENTER(&call->lock);
2189 /* If we had an outstanding delayed ack, be nice to the server
2190 * and force-send it now.
2192 if (call->delayedAckEvent) {
2193 rxevent_Cancel(call->delayedAckEvent, call,
2194 RX_CALL_REFCOUNT_DELAY);
2195 call->delayedAckEvent = NULL;
2196 rxi_SendDelayedAck(NULL, call, NULL);
2199 /* We need to release the call lock since it's lower than the
2200 * conn_call_lock and we don't want to hold the conn_call_lock
2201 * over the rx_ReadProc call. The conn_call_lock needs to be held
2202 * here for the case where rx_NewCall is perusing the calls on
2203 * the connection structure. We don't want to signal until
2204 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2205 * have checked this call, found it active and by the time it
2206 * goes to sleep, will have missed the signal.
2208 MUTEX_EXIT(&call->lock);
2209 MUTEX_ENTER(&conn->conn_call_lock);
2210 MUTEX_ENTER(&call->lock);
2212 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2213 conn->lastBusy[call->channel] = 0;
2216 MUTEX_ENTER(&conn->conn_data_lock);
2217 conn->flags |= RX_CONN_BUSY;
2218 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2219 MUTEX_EXIT(&conn->conn_data_lock);
2220 #ifdef RX_ENABLE_LOCKS
2221 CV_BROADCAST(&conn->conn_call_cv);
2226 #ifdef RX_ENABLE_LOCKS
2228 MUTEX_EXIT(&conn->conn_data_lock);
2230 #endif /* RX_ENABLE_LOCKS */
2231 call->state = RX_STATE_DALLY;
2233 error = call->error;
2235 /* currentPacket, nLeft, and NFree must be zeroed here, because
2236 * ResetCall cannot: ResetCall may be called at splnet(), in the
2237 * kernel version, and may interrupt the macros rx_Read or
2238 * rx_Write, which run at normal priority for efficiency. */
2239 if (call->currentPacket) {
2240 #ifdef RX_TRACK_PACKETS
2241 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2243 rxi_FreePacket(call->currentPacket);
2244 call->currentPacket = (struct rx_packet *)0;
2247 call->nLeft = call->nFree = call->curlen = 0;
2249 /* Free any packets from the last call to ReadvProc/WritevProc */
2250 #ifdef RXDEBUG_PACKET
2252 #endif /* RXDEBUG_PACKET */
2253 rxi_FreePackets(0, &call->iovq);
2254 MUTEX_EXIT(&call->lock);
2256 MUTEX_ENTER(&rx_refcnt_mutex);
2257 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2258 MUTEX_EXIT(&rx_refcnt_mutex);
2259 if (conn->type == RX_CLIENT_CONNECTION) {
2260 MUTEX_ENTER(&conn->conn_data_lock);
2261 conn->flags &= ~RX_CONN_BUSY;
2262 MUTEX_EXIT(&conn->conn_data_lock);
2263 MUTEX_EXIT(&conn->conn_call_lock);
2267 * Map errors to the local host's errno.h format.
2269 error = ntoh_syserr_conv(error);
2273 #if !defined(KERNEL)
2275 /* Call this routine when shutting down a server or client (especially
2276 * clients). This will allow Rx to gracefully garbage collect server
2277 * connections, and reduce the number of retries that a server might
2278 * make to a dead client.
2279 * This is not quite right, since some calls may still be ongoing and
2280 * we can't lock them to destroy them. */
2284 struct rx_connection **conn_ptr, **conn_end;
2288 if (rxinit_status == 1) {
2290 return; /* Already shutdown. */
2292 rxi_DeleteCachedConnections();
2293 if (rx_connHashTable) {
2294 MUTEX_ENTER(&rx_connHashTable_lock);
2295 for (conn_ptr = &rx_connHashTable[0], conn_end =
2296 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2298 struct rx_connection *conn, *next;
2299 for (conn = *conn_ptr; conn; conn = next) {
2301 if (conn->type == RX_CLIENT_CONNECTION) {
2302 MUTEX_ENTER(&rx_refcnt_mutex);
2304 MUTEX_EXIT(&rx_refcnt_mutex);
2305 #ifdef RX_ENABLE_LOCKS
2306 rxi_DestroyConnectionNoLock(conn);
2307 #else /* RX_ENABLE_LOCKS */
2308 rxi_DestroyConnection(conn);
2309 #endif /* RX_ENABLE_LOCKS */
2313 #ifdef RX_ENABLE_LOCKS
2314 while (rx_connCleanup_list) {
2315 struct rx_connection *conn;
2316 conn = rx_connCleanup_list;
2317 rx_connCleanup_list = rx_connCleanup_list->next;
2318 MUTEX_EXIT(&rx_connHashTable_lock);
2319 rxi_CleanupConnection(conn);
2320 MUTEX_ENTER(&rx_connHashTable_lock);
2322 MUTEX_EXIT(&rx_connHashTable_lock);
2323 #endif /* RX_ENABLE_LOCKS */
2328 afs_winsockCleanup();
2336 /* if we wakeup packet waiter too often, can get in loop with two
2337 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2339 rxi_PacketsUnWait(void)
2341 if (!rx_waitingForPackets) {
2345 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2346 return; /* still over quota */
2349 rx_waitingForPackets = 0;
2350 #ifdef RX_ENABLE_LOCKS
2351 CV_BROADCAST(&rx_waitingForPackets_cv);
2353 osi_rxWakeup(&rx_waitingForPackets);
2359 /* ------------------Internal interfaces------------------------- */
2361 /* Return this process's service structure for the
2362 * specified socket and service */
2364 rxi_FindService(osi_socket socket, u_short serviceId)
2366 struct rx_service **sp;
2367 for (sp = &rx_services[0]; *sp; sp++) {
2368 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2374 #ifdef RXDEBUG_PACKET
2375 #ifdef KDUMP_RX_LOCK
2376 static struct rx_call_rx_lock *rx_allCallsp = 0;
2378 static struct rx_call *rx_allCallsp = 0;
2380 #endif /* RXDEBUG_PACKET */
2382 /* Allocate a call structure, for the indicated channel of the
2383 * supplied connection. The mode and state of the call must be set by
2384 * the caller. Returns the call with mutex locked. */
2386 rxi_NewCall(struct rx_connection *conn, int channel)
2388 struct rx_call *call;
2389 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2390 struct rx_call *cp; /* Call pointer temp */
2391 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2392 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2394 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2396 /* Grab an existing call structure, or allocate a new one.
2397 * Existing call structures are assumed to have been left reset by
2399 MUTEX_ENTER(&rx_freeCallQueue_lock);
2401 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2403 * EXCEPT that the TQ might not yet be cleared out.
2404 * Skip over those with in-use TQs.
2407 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2408 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2414 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2415 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2416 call = queue_First(&rx_freeCallQueue, rx_call);
2417 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2419 if (rx_stats_active)
2420 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2421 MUTEX_EXIT(&rx_freeCallQueue_lock);
2422 MUTEX_ENTER(&call->lock);
2423 CLEAR_CALL_QUEUE_LOCK(call);
2424 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2425 /* Now, if TQ wasn't cleared earlier, do it now. */
2426 rxi_WaitforTQBusy(call);
2427 if (call->flags & RX_CALL_TQ_CLEARME) {
2428 rxi_ClearTransmitQueue(call, 1);
2429 /*queue_Init(&call->tq);*/
2431 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2432 /* Bind the call to its connection structure */
2434 rxi_ResetCall(call, 1);
2437 call = rxi_Alloc(sizeof(struct rx_call));
2438 #ifdef RXDEBUG_PACKET
2439 call->allNextp = rx_allCallsp;
2440 rx_allCallsp = call;
2442 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2443 #else /* RXDEBUG_PACKET */
2444 rx_atomic_inc(&rx_stats.nCallStructs);
2445 #endif /* RXDEBUG_PACKET */
2447 MUTEX_EXIT(&rx_freeCallQueue_lock);
2448 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2449 MUTEX_ENTER(&call->lock);
2450 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2451 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2452 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2454 /* Initialize once-only items */
2455 queue_Init(&call->tq);
2456 queue_Init(&call->rq);
2457 queue_Init(&call->iovq);
2458 #ifdef RXDEBUG_PACKET
2459 call->rqc = call->tqc = call->iovqc = 0;
2460 #endif /* RXDEBUG_PACKET */
2461 /* Bind the call to its connection structure (prereq for reset) */
2463 rxi_ResetCall(call, 1);
2465 call->channel = channel;
2466 call->callNumber = &conn->callNumber[channel];
2467 call->rwind = conn->rwind[channel];
2468 call->twind = conn->twind[channel];
2469 /* Note that the next expected call number is retained (in
2470 * conn->callNumber[i]), even if we reallocate the call structure
2472 conn->call[channel] = call;
2473 /* if the channel's never been used (== 0), we should start at 1, otherwise
2474 * the call number is valid from the last time this channel was used */
2475 if (*call->callNumber == 0)
2476 *call->callNumber = 1;
2481 /* A call has been inactive long enough that so we can throw away
2482 * state, including the call structure, which is placed on the call
2485 * call->lock amd rx_refcnt_mutex are held upon entry.
2486 * haveCTLock is set when called from rxi_ReapConnections.
2489 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2491 int channel = call->channel;
2492 struct rx_connection *conn = call->conn;
2495 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2496 (*call->callNumber)++;
2498 * We are setting the state to RX_STATE_RESET to
2499 * ensure that no one else will attempt to use this
2500 * call once we drop the refcnt lock. We must drop
2501 * the refcnt lock before calling rxi_ResetCall
2502 * because it cannot be held across acquiring the
2503 * freepktQ lock. NewCall does the same.
2505 call->state = RX_STATE_RESET;
2506 MUTEX_EXIT(&rx_refcnt_mutex);
2507 rxi_ResetCall(call, 0);
2508 call->conn->call[channel] = (struct rx_call *)0;
2510 MUTEX_ENTER(&rx_freeCallQueue_lock);
2511 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2512 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2513 /* A call may be free even though its transmit queue is still in use.
2514 * Since we search the call list from head to tail, put busy calls at
2515 * the head of the list, and idle calls at the tail.
2517 if (call->flags & RX_CALL_TQ_BUSY)
2518 queue_Prepend(&rx_freeCallQueue, call);
2520 queue_Append(&rx_freeCallQueue, call);
2521 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2522 queue_Append(&rx_freeCallQueue, call);
2523 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2524 if (rx_stats_active)
2525 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2526 MUTEX_EXIT(&rx_freeCallQueue_lock);
2528 /* Destroy the connection if it was previously slated for
2529 * destruction, i.e. the Rx client code previously called
2530 * rx_DestroyConnection (client connections), or
2531 * rxi_ReapConnections called the same routine (server
2532 * connections). Only do this, however, if there are no
2533 * outstanding calls. Note that for fine grain locking, there appears
2534 * to be a deadlock in that rxi_FreeCall has a call locked and
2535 * DestroyConnectionNoLock locks each call in the conn. But note a
2536 * few lines up where we have removed this call from the conn.
2537 * If someone else destroys a connection, they either have no
2538 * call lock held or are going through this section of code.
2540 MUTEX_ENTER(&conn->conn_data_lock);
2541 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2542 MUTEX_ENTER(&rx_refcnt_mutex);
2544 MUTEX_EXIT(&rx_refcnt_mutex);
2545 MUTEX_EXIT(&conn->conn_data_lock);
2546 #ifdef RX_ENABLE_LOCKS
2548 rxi_DestroyConnectionNoLock(conn);
2550 rxi_DestroyConnection(conn);
2551 #else /* RX_ENABLE_LOCKS */
2552 rxi_DestroyConnection(conn);
2553 #endif /* RX_ENABLE_LOCKS */
2555 MUTEX_EXIT(&conn->conn_data_lock);
2557 MUTEX_ENTER(&rx_refcnt_mutex);
2560 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2561 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2564 rxi_Alloc(size_t size)
2568 if (rx_stats_active) {
2569 rx_atomic_add(&rxi_Allocsize, (int) size);
2570 rx_atomic_inc(&rxi_Alloccnt);
2574 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2575 afs_osi_Alloc_NoSleep(size);
2580 osi_Panic("rxi_Alloc error");
2586 rxi_Free(void *addr, size_t size)
2588 if (rx_stats_active) {
2589 rx_atomic_sub(&rxi_Allocsize, (int) size);
2590 rx_atomic_dec(&rxi_Alloccnt);
2592 osi_Free(addr, size);
2596 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2598 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2599 struct rx_peer *next = NULL;
2603 MUTEX_ENTER(&rx_peerHashTable_lock);
2605 peer_ptr = &rx_peerHashTable[0];
2606 peer_end = &rx_peerHashTable[rx_hashTableSize];
2609 for ( ; peer_ptr < peer_end; peer_ptr++) {
2612 for ( ; peer; peer = next) {
2614 if (host == peer->host)
2619 hashIndex = PEER_HASH(host, port);
2620 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2621 if ((peer->host == host) && (peer->port == port))
2626 MUTEX_ENTER(&rx_peerHashTable_lock);
2631 MUTEX_EXIT(&rx_peerHashTable_lock);
2633 MUTEX_ENTER(&peer->peer_lock);
2634 /* We don't handle dropping below min, so don't */
2635 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2636 peer->ifMTU=MIN(mtu, peer->ifMTU);
2637 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2638 /* if we tweaked this down, need to tune our peer MTU too */
2639 peer->MTU = MIN(peer->MTU, peer->natMTU);
2640 /* if we discovered a sub-1500 mtu, degrade */
2641 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2642 peer->maxDgramPackets = 1;
2643 /* We no longer have valid peer packet information */
2644 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2645 peer->maxPacketSize = 0;
2646 MUTEX_EXIT(&peer->peer_lock);
2648 MUTEX_ENTER(&rx_peerHashTable_lock);
2650 if (host && !port) {
2652 /* pick up where we left off */
2656 MUTEX_EXIT(&rx_peerHashTable_lock);
2659 /* Find the peer process represented by the supplied (host,port)
2660 * combination. If there is no appropriate active peer structure, a
2661 * new one will be allocated and initialized
2662 * The origPeer, if set, is a pointer to a peer structure on which the
2663 * refcount will be be decremented. This is used to replace the peer
2664 * structure hanging off a connection structure */
2666 rxi_FindPeer(afs_uint32 host, u_short port,
2667 struct rx_peer *origPeer, int create)
2671 hashIndex = PEER_HASH(host, port);
2672 MUTEX_ENTER(&rx_peerHashTable_lock);
2673 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2674 if ((pp->host == host) && (pp->port == port))
2679 pp = rxi_AllocPeer(); /* This bzero's *pp */
2680 pp->host = host; /* set here or in InitPeerParams is zero */
2682 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2683 queue_Init(&pp->congestionQueue);
2684 queue_Init(&pp->rpcStats);
2685 pp->next = rx_peerHashTable[hashIndex];
2686 rx_peerHashTable[hashIndex] = pp;
2687 rxi_InitPeerParams(pp);
2688 if (rx_stats_active)
2689 rx_atomic_inc(&rx_stats.nPeerStructs);
2696 origPeer->refCount--;
2697 MUTEX_EXIT(&rx_peerHashTable_lock);
2702 /* Find the connection at (host, port) started at epoch, and with the
2703 * given connection id. Creates the server connection if necessary.
2704 * The type specifies whether a client connection or a server
2705 * connection is desired. In both cases, (host, port) specify the
2706 * peer's (host, pair) pair. Client connections are not made
2707 * automatically by this routine. The parameter socket gives the
2708 * socket descriptor on which the packet was received. This is used,
2709 * in the case of server connections, to check that *new* connections
2710 * come via a valid (port, serviceId). Finally, the securityIndex
2711 * parameter must match the existing index for the connection. If a
2712 * server connection is created, it will be created using the supplied
2713 * index, if the index is valid for this service */
2714 struct rx_connection *
2715 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2716 u_short port, u_short serviceId, afs_uint32 cid,
2717 afs_uint32 epoch, int type, u_int securityIndex)
2719 int hashindex, flag, i;
2720 struct rx_connection *conn;
2721 hashindex = CONN_HASH(host, port, cid, epoch, type);
2722 MUTEX_ENTER(&rx_connHashTable_lock);
2723 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2724 rx_connHashTable[hashindex],
2727 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2728 && (epoch == conn->epoch)) {
2729 struct rx_peer *pp = conn->peer;
2730 if (securityIndex != conn->securityIndex) {
2731 /* this isn't supposed to happen, but someone could forge a packet
2732 * like this, and there seems to be some CM bug that makes this
2733 * happen from time to time -- in which case, the fileserver
2735 MUTEX_EXIT(&rx_connHashTable_lock);
2736 return (struct rx_connection *)0;
2738 if (pp->host == host && pp->port == port)
2740 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2742 /* So what happens when it's a callback connection? */
2743 if ( /*type == RX_CLIENT_CONNECTION && */
2744 (conn->epoch & 0x80000000))
2748 /* the connection rxLastConn that was used the last time is not the
2749 ** one we are looking for now. Hence, start searching in the hash */
2751 conn = rx_connHashTable[hashindex];
2756 struct rx_service *service;
2757 if (type == RX_CLIENT_CONNECTION) {
2758 MUTEX_EXIT(&rx_connHashTable_lock);
2759 return (struct rx_connection *)0;
2761 service = rxi_FindService(socket, serviceId);
2762 if (!service || (securityIndex >= service->nSecurityObjects)
2763 || (service->securityObjects[securityIndex] == 0)) {
2764 MUTEX_EXIT(&rx_connHashTable_lock);
2765 return (struct rx_connection *)0;
2767 conn = rxi_AllocConnection(); /* This bzero's the connection */
2768 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2769 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2770 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2771 conn->next = rx_connHashTable[hashindex];
2772 rx_connHashTable[hashindex] = conn;
2773 conn->peer = rxi_FindPeer(host, port, 0, 1);
2774 conn->type = RX_SERVER_CONNECTION;
2775 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2776 conn->epoch = epoch;
2777 conn->cid = cid & RX_CIDMASK;
2778 /* conn->serial = conn->lastSerial = 0; */
2779 /* conn->timeout = 0; */
2780 conn->ackRate = RX_FAST_ACK_RATE;
2781 conn->service = service;
2782 conn->serviceId = serviceId;
2783 conn->securityIndex = securityIndex;
2784 conn->securityObject = service->securityObjects[securityIndex];
2785 conn->nSpecific = 0;
2786 conn->specific = NULL;
2787 rx_SetConnDeadTime(conn, service->connDeadTime);
2788 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2789 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2790 for (i = 0; i < RX_MAXCALLS; i++) {
2791 conn->twind[i] = rx_initSendWindow;
2792 conn->rwind[i] = rx_initReceiveWindow;
2794 /* Notify security object of the new connection */
2795 RXS_NewConnection(conn->securityObject, conn);
2796 /* XXXX Connection timeout? */
2797 if (service->newConnProc)
2798 (*service->newConnProc) (conn);
2799 if (rx_stats_active)
2800 rx_atomic_inc(&rx_stats.nServerConns);
2803 MUTEX_ENTER(&rx_refcnt_mutex);
2805 MUTEX_EXIT(&rx_refcnt_mutex);
2807 rxLastConn = conn; /* store this connection as the last conn used */
2808 MUTEX_EXIT(&rx_connHashTable_lock);
2813 * Timeout a call on a busy call channel if appropriate.
2815 * @param[in] call The busy call.
2817 * @pre 'call' is marked as busy (namely,
2818 * call->conn->lastBusy[call->channel] != 0)
2820 * @pre call->lock is held
2822 * @note call->lock is dropped and reacquired
2825 rxi_CheckBusy(struct rx_call *call)
2827 struct rx_connection *conn = call->conn;
2828 int channel = call->channel;
2829 int freechannel = 0;
2831 afs_uint32 callNumber = *call->callNumber;
2833 MUTEX_EXIT(&call->lock);
2835 MUTEX_ENTER(&conn->conn_call_lock);
2837 /* Are there any other call slots on this conn that we should try? Look for
2838 * slots that are empty and are either non-busy, or were marked as busy
2839 * longer than conn->secondsUntilDead seconds before this call started. */
2841 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
2843 /* only look at channels that aren't us */
2847 if (conn->lastBusy[i]) {
2848 /* if this channel looked busy too recently, don't look at it */
2849 if (conn->lastBusy[i] >= call->startTime.sec) {
2852 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
2857 if (conn->call[i]) {
2858 struct rx_call *tcall = conn->call[i];
2859 MUTEX_ENTER(&tcall->lock);
2860 if (tcall->state == RX_STATE_DALLY) {
2863 MUTEX_EXIT(&tcall->lock);
2869 MUTEX_EXIT(&conn->conn_call_lock);
2871 MUTEX_ENTER(&call->lock);
2873 /* Since the call->lock and conn->conn_call_lock have been released it is
2874 * possible that (1) the call may no longer be busy and/or (2) the call may
2875 * have been reused by another waiting thread. Therefore, we must confirm
2876 * that the call state has not changed when deciding whether or not to
2877 * force this application thread to retry by forcing a Timeout error. */
2879 if (freechannel && *call->callNumber == callNumber &&
2880 (call->flags & RX_CALL_PEER_BUSY)) {
2881 /* Since 'freechannel' is set, there exists another channel in this
2882 * rx_conn that the application thread might be able to use. We know
2883 * that we have the correct call since callNumber is unchanged, and we
2884 * know that the call is still busy. So, set the call error state to
2885 * RX_CALL_TIMEOUT so the application can retry the request, presumably
2886 * on a less-busy call channel. */
2888 rxi_CallError(call, RX_CALL_TIMEOUT);
2892 /* There are two packet tracing routines available for testing and monitoring
2893 * Rx. One is called just after every packet is received and the other is
2894 * called just before every packet is sent. Received packets, have had their
2895 * headers decoded, and packets to be sent have not yet had their headers
2896 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2897 * containing the network address. Both can be modified. The return value, if
2898 * non-zero, indicates that the packet should be dropped. */
2900 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2901 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2903 /* A packet has been received off the interface. Np is the packet, socket is
2904 * the socket number it was received from (useful in determining which service
2905 * this packet corresponds to), and (host, port) reflect the host,port of the
2906 * sender. This call returns the packet to the caller if it is finished with
2907 * it, rather than de-allocating it, just as a small performance hack */
2910 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2911 afs_uint32 host, u_short port, int *tnop,
2912 struct rx_call **newcallp)
2914 struct rx_call *call;
2915 struct rx_connection *conn;
2917 afs_uint32 currentCallNumber;
2923 struct rx_packet *tnp;
2926 /* We don't print out the packet until now because (1) the time may not be
2927 * accurate enough until now in the lwp implementation (rx_Listener only gets
2928 * the time after the packet is read) and (2) from a protocol point of view,
2929 * this is the first time the packet has been seen */
2930 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2931 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2932 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2933 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2934 np->header.epoch, np->header.cid, np->header.callNumber,
2935 np->header.seq, np->header.flags, np));
2938 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2939 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2942 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2943 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2946 /* If an input tracer function is defined, call it with the packet and
2947 * network address. Note this function may modify its arguments. */
2948 if (rx_justReceived) {
2949 struct sockaddr_in addr;
2951 addr.sin_family = AF_INET;
2952 addr.sin_port = port;
2953 addr.sin_addr.s_addr = host;
2954 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2955 addr.sin_len = sizeof(addr);
2956 #endif /* AFS_OSF_ENV */
2957 drop = (*rx_justReceived) (np, &addr);
2958 /* drop packet if return value is non-zero */
2961 port = addr.sin_port; /* in case fcn changed addr */
2962 host = addr.sin_addr.s_addr;
2966 /* If packet was not sent by the client, then *we* must be the client */
2967 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2968 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2970 /* Find the connection (or fabricate one, if we're the server & if
2971 * necessary) associated with this packet */
2973 rxi_FindConnection(socket, host, port, np->header.serviceId,
2974 np->header.cid, np->header.epoch, type,
2975 np->header.securityIndex);
2978 /* If no connection found or fabricated, just ignore the packet.
2979 * (An argument could be made for sending an abort packet for
2984 MUTEX_ENTER(&conn->conn_data_lock);
2985 if (conn->maxSerial < np->header.serial)
2986 conn->maxSerial = np->header.serial;
2987 MUTEX_EXIT(&conn->conn_data_lock);
2989 /* If the connection is in an error state, send an abort packet and ignore
2990 * the incoming packet */
2992 /* Don't respond to an abort packet--we don't want loops! */
2993 MUTEX_ENTER(&conn->conn_data_lock);
2994 if (np->header.type != RX_PACKET_TYPE_ABORT)
2995 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2996 MUTEX_ENTER(&rx_refcnt_mutex);
2998 MUTEX_EXIT(&rx_refcnt_mutex);
2999 MUTEX_EXIT(&conn->conn_data_lock);
3003 /* Check for connection-only requests (i.e. not call specific). */
3004 if (np->header.callNumber == 0) {
3005 switch (np->header.type) {
3006 case RX_PACKET_TYPE_ABORT: {
3007 /* What if the supplied error is zero? */
3008 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3009 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3010 rxi_ConnectionError(conn, errcode);
3011 MUTEX_ENTER(&rx_refcnt_mutex);
3013 MUTEX_EXIT(&rx_refcnt_mutex);
3016 case RX_PACKET_TYPE_CHALLENGE:
3017 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3018 MUTEX_ENTER(&rx_refcnt_mutex);
3020 MUTEX_EXIT(&rx_refcnt_mutex);
3022 case RX_PACKET_TYPE_RESPONSE:
3023 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3024 MUTEX_ENTER(&rx_refcnt_mutex);
3026 MUTEX_EXIT(&rx_refcnt_mutex);
3028 case RX_PACKET_TYPE_PARAMS:
3029 case RX_PACKET_TYPE_PARAMS + 1:
3030 case RX_PACKET_TYPE_PARAMS + 2:
3031 /* ignore these packet types for now */
3032 MUTEX_ENTER(&rx_refcnt_mutex);
3034 MUTEX_EXIT(&rx_refcnt_mutex);
3039 /* Should not reach here, unless the peer is broken: send an
3041 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3042 MUTEX_ENTER(&conn->conn_data_lock);
3043 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3044 MUTEX_ENTER(&rx_refcnt_mutex);
3046 MUTEX_EXIT(&rx_refcnt_mutex);
3047 MUTEX_EXIT(&conn->conn_data_lock);
3052 channel = np->header.cid & RX_CHANNELMASK;
3053 call = conn->call[channel];
3054 #ifdef RX_ENABLE_LOCKS
3056 MUTEX_ENTER(&call->lock);
3057 /* Test to see if call struct is still attached to conn. */
3058 if (call != conn->call[channel]) {
3060 MUTEX_EXIT(&call->lock);
3061 if (type == RX_SERVER_CONNECTION) {
3062 call = conn->call[channel];
3063 /* If we started with no call attached and there is one now,
3064 * another thread is also running this routine and has gotten
3065 * the connection channel. We should drop this packet in the tests
3066 * below. If there was a call on this connection and it's now
3067 * gone, then we'll be making a new call below.
3068 * If there was previously a call and it's now different then
3069 * the old call was freed and another thread running this routine
3070 * has created a call on this channel. One of these two threads
3071 * has a packet for the old call and the code below handles those
3075 MUTEX_ENTER(&call->lock);
3077 /* This packet can't be for this call. If the new call address is
3078 * 0 then no call is running on this channel. If there is a call
3079 * then, since this is a client connection we're getting data for
3080 * it must be for the previous call.
3082 if (rx_stats_active)
3083 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3084 MUTEX_ENTER(&rx_refcnt_mutex);
3086 MUTEX_EXIT(&rx_refcnt_mutex);
3091 currentCallNumber = conn->callNumber[channel];
3093 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3094 if (np->header.callNumber < currentCallNumber) {
3095 if (rx_stats_active)
3096 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3097 #ifdef RX_ENABLE_LOCKS
3099 MUTEX_EXIT(&call->lock);
3101 MUTEX_ENTER(&rx_refcnt_mutex);
3103 MUTEX_EXIT(&rx_refcnt_mutex);
3107 MUTEX_ENTER(&conn->conn_call_lock);
3108 call = rxi_NewCall(conn, channel);
3109 MUTEX_EXIT(&conn->conn_call_lock);
3110 *call->callNumber = np->header.callNumber;
3112 if (np->header.callNumber == 0)
3113 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d\n",
3114 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3115 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3116 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
3118 call->state = RX_STATE_PRECALL;
3119 clock_GetTime(&call->queueTime);
3120 hzero(call->bytesSent);
3121 hzero(call->bytesRcvd);
3123 * If the number of queued calls exceeds the overload
3124 * threshold then abort this call.
3126 if ((rx_BusyThreshold > 0) &&
3127 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3128 struct rx_packet *tp;
3130 rxi_CallError(call, rx_BusyError);
3131 tp = rxi_SendCallAbort(call, np, 1, 0);
3132 MUTEX_EXIT(&call->lock);
3133 MUTEX_ENTER(&rx_refcnt_mutex);
3135 MUTEX_EXIT(&rx_refcnt_mutex);
3136 if (rx_stats_active)
3137 rx_atomic_inc(&rx_stats.nBusies);
3140 rxi_KeepAliveOn(call);
3141 } else if (np->header.callNumber != currentCallNumber) {
3142 /* Wait until the transmit queue is idle before deciding
3143 * whether to reset the current call. Chances are that the
3144 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3147 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3148 if (call->state == RX_STATE_ACTIVE) {
3149 rxi_WaitforTQBusy(call);
3151 * If we entered error state while waiting,
3152 * must call rxi_CallError to permit rxi_ResetCall
3153 * to processed when the tqWaiter count hits zero.
3156 rxi_CallError(call, call->error);
3157 MUTEX_EXIT(&call->lock);
3158 MUTEX_ENTER(&rx_refcnt_mutex);
3160 MUTEX_EXIT(&rx_refcnt_mutex);
3164 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3165 /* If the new call cannot be taken right now send a busy and set
3166 * the error condition in this call, so that it terminates as
3167 * quickly as possible */
3168 if (call->state == RX_STATE_ACTIVE) {
3169 struct rx_packet *tp;
3171 rxi_CallError(call, RX_CALL_DEAD);
3172 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3174 MUTEX_EXIT(&call->lock);
3175 MUTEX_ENTER(&rx_refcnt_mutex);
3177 MUTEX_EXIT(&rx_refcnt_mutex);
3180 rxi_ResetCall(call, 0);
3181 *call->callNumber = np->header.callNumber;
3183 if (np->header.callNumber == 0)
3184 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d\n",
3185 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3186 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3187 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3189 call->state = RX_STATE_PRECALL;
3190 clock_GetTime(&call->queueTime);
3191 hzero(call->bytesSent);
3192 hzero(call->bytesRcvd);
3194 * If the number of queued calls exceeds the overload
3195 * threshold then abort this call.
3197 if ((rx_BusyThreshold > 0) &&
3198 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3199 struct rx_packet *tp;
3201 rxi_CallError(call, rx_BusyError);
3202 tp = rxi_SendCallAbort(call, np, 1, 0);
3203 MUTEX_EXIT(&call->lock);
3204 MUTEX_ENTER(&rx_refcnt_mutex);
3206 MUTEX_EXIT(&rx_refcnt_mutex);
3207 if (rx_stats_active)
3208 rx_atomic_inc(&rx_stats.nBusies);
3211 rxi_KeepAliveOn(call);
3213 /* Continuing call; do nothing here. */
3215 } else { /* we're the client */
3216 /* Ignore all incoming acknowledgements for calls in DALLY state */
3217 if (call && (call->state == RX_STATE_DALLY)
3218 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3219 if (rx_stats_active)
3220 rx_atomic_inc(&rx_stats.ignorePacketDally);
3221 #ifdef RX_ENABLE_LOCKS
3223 MUTEX_EXIT(&call->lock);
3226 MUTEX_ENTER(&rx_refcnt_mutex);
3228 MUTEX_EXIT(&rx_refcnt_mutex);
3232 /* Ignore anything that's not relevant to the current call. If there
3233 * isn't a current call, then no packet is relevant. */
3234 if (!call || (np->header.callNumber != currentCallNumber)) {
3235 if (rx_stats_active)
3236 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3237 #ifdef RX_ENABLE_LOCKS
3239 MUTEX_EXIT(&call->lock);
3242 MUTEX_ENTER(&rx_refcnt_mutex);
3244 MUTEX_EXIT(&rx_refcnt_mutex);
3247 /* If the service security object index stamped in the packet does not
3248 * match the connection's security index, ignore the packet */
3249 if (np->header.securityIndex != conn->securityIndex) {
3250 #ifdef RX_ENABLE_LOCKS
3251 MUTEX_EXIT(&call->lock);
3253 MUTEX_ENTER(&rx_refcnt_mutex);
3255 MUTEX_EXIT(&rx_refcnt_mutex);
3259 /* If we're receiving the response, then all transmit packets are
3260 * implicitly acknowledged. Get rid of them. */
3261 if (np->header.type == RX_PACKET_TYPE_DATA) {
3262 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3263 /* XXX Hack. Because we must release the global rx lock when
3264 * sending packets (osi_NetSend) we drop all acks while we're
3265 * traversing the tq in rxi_Start sending packets out because
3266 * packets may move to the freePacketQueue as result of being here!
3267 * So we drop these packets until we're safely out of the
3268 * traversing. Really ugly!
3269 * For fine grain RX locking, we set the acked field in the
3270 * packets and let rxi_Start remove them from the transmit queue.
3272 if (call->flags & RX_CALL_TQ_BUSY) {
3273 #ifdef RX_ENABLE_LOCKS
3274 rxi_SetAcksInTransmitQueue(call);
3276 MUTEX_ENTER(&rx_refcnt_mutex);
3278 MUTEX_EXIT(&rx_refcnt_mutex);
3279 return np; /* xmitting; drop packet */
3282 rxi_ClearTransmitQueue(call, 0);
3284 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3285 rxi_ClearTransmitQueue(call, 0);
3286 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3288 if (np->header.type == RX_PACKET_TYPE_ACK) {
3289 /* now check to see if this is an ack packet acknowledging that the
3290 * server actually *lost* some hard-acked data. If this happens we
3291 * ignore this packet, as it may indicate that the server restarted in
3292 * the middle of a call. It is also possible that this is an old ack
3293 * packet. We don't abort the connection in this case, because this
3294 * *might* just be an old ack packet. The right way to detect a server
3295 * restart in the midst of a call is to notice that the server epoch
3297 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3298 * XXX unacknowledged. I think that this is off-by-one, but
3299 * XXX I don't dare change it just yet, since it will
3300 * XXX interact badly with the server-restart detection
3301 * XXX code in receiveackpacket. */
3302 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3303 if (rx_stats_active)
3304 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3305 MUTEX_EXIT(&call->lock);
3306 MUTEX_ENTER(&rx_refcnt_mutex);
3308 MUTEX_EXIT(&rx_refcnt_mutex);
3312 } /* else not a data packet */
3315 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3316 /* Set remote user defined status from packet */
3317 call->remoteStatus = np->header.userStatus;
3319 /* Note the gap between the expected next packet and the actual
3320 * packet that arrived, when the new packet has a smaller serial number
3321 * than expected. Rioses frequently reorder packets all by themselves,
3322 * so this will be quite important with very large window sizes.
3323 * Skew is checked against 0 here to avoid any dependence on the type of
3324 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3326 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3327 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3328 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3330 MUTEX_ENTER(&conn->conn_data_lock);
3331 skew = conn->lastSerial - np->header.serial;
3332 conn->lastSerial = np->header.serial;
3333 MUTEX_EXIT(&conn->conn_data_lock);
3335 struct rx_peer *peer;
3337 if (skew > peer->inPacketSkew) {
3338 dpf(("*** In skew changed from %d to %d\n",
3339 peer->inPacketSkew, skew));
3340 peer->inPacketSkew = skew;
3344 /* Now do packet type-specific processing */
3345 switch (np->header.type) {
3346 case RX_PACKET_TYPE_DATA:
3347 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3350 case RX_PACKET_TYPE_ACK:
3351 /* Respond immediately to ack packets requesting acknowledgement
3353 if (np->header.flags & RX_REQUEST_ACK) {
3355 (void)rxi_SendCallAbort(call, 0, 1, 0);
3357 (void)rxi_SendAck(call, 0, np->header.serial,
3358 RX_ACK_PING_RESPONSE, 1);
3360 np = rxi_ReceiveAckPacket(call, np, 1);
3362 case RX_PACKET_TYPE_ABORT: {
3363 /* An abort packet: reset the call, passing the error up to the user. */
3364 /* What if error is zero? */
3365 /* What if the error is -1? the application will treat it as a timeout. */
3366 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3367 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3368 rxi_CallError(call, errdata);
3369 MUTEX_EXIT(&call->lock);
3370 MUTEX_ENTER(&rx_refcnt_mutex);
3372 MUTEX_EXIT(&rx_refcnt_mutex);
3373 return np; /* xmitting; drop packet */
3375 case RX_PACKET_TYPE_BUSY: {
3376 struct clock busyTime;
3378 clock_GetTime(&busyTime);
3380 MUTEX_EXIT(&call->lock);
3382 MUTEX_ENTER(&conn->conn_call_lock);
3383 MUTEX_ENTER(&call->lock);
3384 conn->lastBusy[call->channel] = busyTime.sec;
3385 call->flags |= RX_CALL_PEER_BUSY;
3386 MUTEX_EXIT(&call->lock);
3387 MUTEX_EXIT(&conn->conn_call_lock);
3389 MUTEX_ENTER(&rx_refcnt_mutex);
3391 MUTEX_EXIT(&rx_refcnt_mutex);
3395 case RX_PACKET_TYPE_ACKALL:
3396 /* All packets acknowledged, so we can drop all packets previously
3397 * readied for sending */
3398 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3399 /* XXX Hack. We because we can't release the global rx lock when
3400 * sending packets (osi_NetSend) we drop all ack pkts while we're
3401 * traversing the tq in rxi_Start sending packets out because
3402 * packets may move to the freePacketQueue as result of being
3403 * here! So we drop these packets until we're safely out of the
3404 * traversing. Really ugly!
3405 * For fine grain RX locking, we set the acked field in the packets
3406 * and let rxi_Start remove the packets from the transmit queue.
3408 if (call->flags & RX_CALL_TQ_BUSY) {
3409 #ifdef RX_ENABLE_LOCKS
3410 rxi_SetAcksInTransmitQueue(call);
3412 #else /* RX_ENABLE_LOCKS */
3413 MUTEX_EXIT(&call->lock);
3414 MUTEX_ENTER(&rx_refcnt_mutex);
3416 MUTEX_EXIT(&rx_refcnt_mutex);
3417 return np; /* xmitting; drop packet */
3418 #endif /* RX_ENABLE_LOCKS */
3420 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3421 rxi_ClearTransmitQueue(call, 0);
3422 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3425 /* Should not reach here, unless the peer is broken: send an abort
3427 rxi_CallError(call, RX_PROTOCOL_ERROR);
3428 np = rxi_SendCallAbort(call, np, 1, 0);
3431 /* Note when this last legitimate packet was received, for keep-alive
3432 * processing. Note, we delay getting the time until now in the hope that
3433 * the packet will be delivered to the user before any get time is required
3434 * (if not, then the time won't actually be re-evaluated here). */
3435 call->lastReceiveTime = clock_Sec();
3436 /* we've received a legit packet, so the channel is not busy */
3437 call->flags &= ~RX_CALL_PEER_BUSY;
3438 MUTEX_EXIT(&call->lock);
3439 MUTEX_ENTER(&rx_refcnt_mutex);
3441 MUTEX_EXIT(&rx_refcnt_mutex);
3445 /* return true if this is an "interesting" connection from the point of view
3446 of someone trying to debug the system */
3448 rxi_IsConnInteresting(struct rx_connection *aconn)
3451 struct rx_call *tcall;
3453 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3456 for (i = 0; i < RX_MAXCALLS; i++) {
3457 tcall = aconn->call[i];
3459 if ((tcall->state == RX_STATE_PRECALL)
3460 || (tcall->state == RX_STATE_ACTIVE))
3462 if ((tcall->mode == RX_MODE_SENDING)
3463 || (tcall->mode == RX_MODE_RECEIVING))
3471 /* if this is one of the last few packets AND it wouldn't be used by the
3472 receiving call to immediately satisfy a read request, then drop it on
3473 the floor, since accepting it might prevent a lock-holding thread from
3474 making progress in its reading. If a call has been cleared while in
3475 the precall state then ignore all subsequent packets until the call
3476 is assigned to a thread. */
3479 TooLow(struct rx_packet *ap, struct rx_call *acall)
3483 MUTEX_ENTER(&rx_quota_mutex);
3484 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3485 && (acall->state == RX_STATE_PRECALL))
3486 || ((rx_nFreePackets < rxi_dataQuota + 2)
3487 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3488 && (acall->flags & RX_CALL_READER_WAIT)))) {
3491 MUTEX_EXIT(&rx_quota_mutex);
3497 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3499 struct rx_connection *conn = arg1;
3500 struct rx_call *acall = arg2;
3501 struct rx_call *call = acall;
3502 struct clock when, now;
3505 MUTEX_ENTER(&conn->conn_data_lock);
3506 conn->checkReachEvent = NULL;
3507 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3509 MUTEX_ENTER(&rx_refcnt_mutex);
3511 MUTEX_EXIT(&rx_refcnt_mutex);
3513 MUTEX_EXIT(&conn->conn_data_lock);
3517 MUTEX_ENTER(&conn->conn_call_lock);
3518 MUTEX_ENTER(&conn->conn_data_lock);
3519 for (i = 0; i < RX_MAXCALLS; i++) {
3520 struct rx_call *tc = conn->call[i];
3521 if (tc && tc->state == RX_STATE_PRECALL) {
3527 /* Indicate that rxi_CheckReachEvent is no longer running by
3528 * clearing the flag. Must be atomic under conn_data_lock to
3529 * avoid a new call slipping by: rxi_CheckConnReach holds
3530 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3532 conn->flags &= ~RX_CONN_ATTACHWAIT;
3533 MUTEX_EXIT(&conn->conn_data_lock);
3534 MUTEX_EXIT(&conn->conn_call_lock);
3539 MUTEX_ENTER(&call->lock);
3540 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3542 MUTEX_EXIT(&call->lock);
3544 clock_GetTime(&now);
3546 when.sec += RX_CHECKREACH_TIMEOUT;
3547 MUTEX_ENTER(&conn->conn_data_lock);
3548 if (!conn->checkReachEvent) {
3549 MUTEX_ENTER(&rx_refcnt_mutex);
3551 MUTEX_EXIT(&rx_refcnt_mutex);
3552 conn->checkReachEvent =
3553 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3556 MUTEX_EXIT(&conn->conn_data_lock);
3562 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3564 struct rx_service *service = conn->service;
3565 struct rx_peer *peer = conn->peer;
3566 afs_uint32 now, lastReach;
3568 if (service->checkReach == 0)
3572 MUTEX_ENTER(&peer->peer_lock);
3573 lastReach = peer->lastReachTime;
3574 MUTEX_EXIT(&peer->peer_lock);
3575 if (now - lastReach < RX_CHECKREACH_TTL)
3578 MUTEX_ENTER(&conn->conn_data_lock);
3579 if (conn->flags & RX_CONN_ATTACHWAIT) {
3580 MUTEX_EXIT(&conn->conn_data_lock);
3583 conn->flags |= RX_CONN_ATTACHWAIT;
3584 MUTEX_EXIT(&conn->conn_data_lock);
3585 if (!conn->checkReachEvent)
3586 rxi_CheckReachEvent(NULL, conn, call);
3591 /* try to attach call, if authentication is complete */
3593 TryAttach(struct rx_call *acall, osi_socket socket,
3594 int *tnop, struct rx_call **newcallp,
3597 struct rx_connection *conn = acall->conn;
3599 if (conn->type == RX_SERVER_CONNECTION
3600 && acall->state == RX_STATE_PRECALL) {
3601 /* Don't attach until we have any req'd. authentication. */
3602 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3603 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3604 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3605 /* Note: this does not necessarily succeed; there
3606 * may not any proc available
3609 rxi_ChallengeOn(acall->conn);
3614 /* A data packet has been received off the interface. This packet is
3615 * appropriate to the call (the call is in the right state, etc.). This
3616 * routine can return a packet to the caller, for re-use */
3619 rxi_ReceiveDataPacket(struct rx_call *call,
3620 struct rx_packet *np, int istack,
3621 osi_socket socket, afs_uint32 host, u_short port,
3622 int *tnop, struct rx_call **newcallp)
3624 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3629 afs_uint32 serial=0, flags=0;
3631 struct rx_packet *tnp;
3632 struct clock when, now;
3633 if (rx_stats_active)
3634 rx_atomic_inc(&rx_stats.dataPacketsRead);
3637 /* If there are no packet buffers, drop this new packet, unless we can find
3638 * packet buffers from inactive calls */
3640 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3641 MUTEX_ENTER(&rx_freePktQ_lock);
3642 rxi_NeedMorePackets = TRUE;
3643 MUTEX_EXIT(&rx_freePktQ_lock);
3644 if (rx_stats_active)
3645 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3646 call->rprev = np->header.serial;
3647 rxi_calltrace(RX_TRACE_DROP, call);
3648 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3650 rxi_ClearReceiveQueue(call);
3651 clock_GetTime(&now);
3653 clock_Add(&when, &rx_softAckDelay);
3654 if (!call->delayedAckEvent
3655 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3656 rxevent_Cancel(call->delayedAckEvent, call,
3657 RX_CALL_REFCOUNT_DELAY);
3658 MUTEX_ENTER(&rx_refcnt_mutex);
3659 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3660 MUTEX_EXIT(&rx_refcnt_mutex);
3662 call->delayedAckEvent =
3663 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3665 /* we've damaged this call already, might as well do it in. */
3671 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3672 * packet is one of several packets transmitted as a single
3673 * datagram. Do not send any soft or hard acks until all packets
3674 * in a jumbogram have been processed. Send negative acks right away.
3676 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3677 /* tnp is non-null when there are more packets in the
3678 * current jumbo gram */
3685 seq = np->header.seq;
3686 serial = np->header.serial;
3687 flags = np->header.flags;
3689 /* If the call is in an error state, send an abort message */
3691 return rxi_SendCallAbort(call, np, istack, 0);
3693 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3694 * AFS 3.5 jumbogram. */
3695 if (flags & RX_JUMBO_PACKET) {
3696 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3701 if (np->header.spare != 0) {
3702 MUTEX_ENTER(&call->conn->conn_data_lock);
3703 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3704 MUTEX_EXIT(&call->conn->conn_data_lock);
3707 /* The usual case is that this is the expected next packet */
3708 if (seq == call->rnext) {
3710 /* Check to make sure it is not a duplicate of one already queued */
3711 if (queue_IsNotEmpty(&call->rq)
3712 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3713 if (rx_stats_active)
3714 rx_atomic_inc(&rx_stats.dupPacketsRead);
3715 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3716 rxevent_Cancel(call->delayedAckEvent, call,
3717 RX_CALL_REFCOUNT_DELAY);
3718 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3724 /* It's the next packet. Stick it on the receive queue
3725 * for this call. Set newPackets to make sure we wake
3726 * the reader once all packets have been processed */
3727 #ifdef RX_TRACK_PACKETS
3728 np->flags |= RX_PKTFLAG_RQ;
3730 queue_Prepend(&call->rq, np);
3731 #ifdef RXDEBUG_PACKET
3733 #endif /* RXDEBUG_PACKET */
3735 np = NULL; /* We can't use this anymore */
3738 /* If an ack is requested then set a flag to make sure we
3739 * send an acknowledgement for this packet */
3740 if (flags & RX_REQUEST_ACK) {
3741 ackNeeded = RX_ACK_REQUESTED;
3744 /* Keep track of whether we have received the last packet */
3745 if (flags & RX_LAST_PACKET) {
3746 call->flags |= RX_CALL_HAVE_LAST;
3750 /* Check whether we have all of the packets for this call */
3751 if (call->flags & RX_CALL_HAVE_LAST) {
3752 afs_uint32 tseq; /* temporary sequence number */
3753 struct rx_packet *tp; /* Temporary packet pointer */
3754 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3756 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3757 if (tseq != tp->header.seq)
3759 if (tp->header.flags & RX_LAST_PACKET) {
3760 call->flags |= RX_CALL_RECEIVE_DONE;
3767 /* Provide asynchronous notification for those who want it
3768 * (e.g. multi rx) */
3769 if (call->arrivalProc) {
3770 (*call->arrivalProc) (call, call->arrivalProcHandle,
3771 call->arrivalProcArg);
3772 call->arrivalProc = (void (*)())0;
3775 /* Update last packet received */
3778 /* If there is no server process serving this call, grab
3779 * one, if available. We only need to do this once. If a
3780 * server thread is available, this thread becomes a server
3781 * thread and the server thread becomes a listener thread. */
3783 TryAttach(call, socket, tnop, newcallp, 0);
3786 /* This is not the expected next packet. */
3788 /* Determine whether this is a new or old packet, and if it's
3789 * a new one, whether it fits into the current receive window.
3790 * Also figure out whether the packet was delivered in sequence.
3791 * We use the prev variable to determine whether the new packet
3792 * is the successor of its immediate predecessor in the
3793 * receive queue, and the missing flag to determine whether
3794 * any of this packets predecessors are missing. */
3796 afs_uint32 prev; /* "Previous packet" sequence number */
3797 struct rx_packet *tp; /* Temporary packet pointer */
3798 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3799 int missing; /* Are any predecessors missing? */
3801 /* If the new packet's sequence number has been sent to the
3802 * application already, then this is a duplicate */
3803 if (seq < call->rnext) {
3804 if (rx_stats_active)
3805 rx_atomic_inc(&rx_stats.dupPacketsRead);
3806 rxevent_Cancel(call->delayedAckEvent, call,
3807 RX_CALL_REFCOUNT_DELAY);
3808 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3814 /* If the sequence number is greater than what can be
3815 * accomodated by the current window, then send a negative
3816 * acknowledge and drop the packet */
3817 if ((call->rnext + call->rwind) <= seq) {
3818 rxevent_Cancel(call->delayedAckEvent, call,
3819 RX_CALL_REFCOUNT_DELAY);
3820 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3827 /* Look for the packet in the queue of old received packets */
3828 for (prev = call->rnext - 1, missing =
3829 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3830 /*Check for duplicate packet */
3831 if (seq == tp->header.seq) {
3832 if (rx_stats_active)
3833 rx_atomic_inc(&rx_stats.dupPacketsRead);
3834 rxevent_Cancel(call->delayedAckEvent, call,
3835 RX_CALL_REFCOUNT_DELAY);
3836 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3842 /* If we find a higher sequence packet, break out and
3843 * insert the new packet here. */
3844 if (seq < tp->header.seq)
3846 /* Check for missing packet */
3847 if (tp->header.seq != prev + 1) {
3851 prev = tp->header.seq;
3854 /* Keep track of whether we have received the last packet. */
3855 if (flags & RX_LAST_PACKET) {
3856 call->flags |= RX_CALL_HAVE_LAST;
3859 /* It's within the window: add it to the the receive queue.
3860 * tp is left by the previous loop either pointing at the
3861 * packet before which to insert the new packet, or at the
3862 * queue head if the queue is empty or the packet should be
3864 #ifdef RX_TRACK_PACKETS
3865 np->flags |= RX_PKTFLAG_RQ;
3867 #ifdef RXDEBUG_PACKET
3869 #endif /* RXDEBUG_PACKET */
3870 queue_InsertBefore(tp, np);
3874 /* Check whether we have all of the packets for this call */
3875 if ((call->flags & RX_CALL_HAVE_LAST)
3876 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3877 afs_uint32 tseq; /* temporary sequence number */
3880 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3881 if (tseq != tp->header.seq)
3883 if (tp->header.flags & RX_LAST_PACKET) {
3884 call->flags |= RX_CALL_RECEIVE_DONE;
3891 /* We need to send an ack of the packet is out of sequence,
3892 * or if an ack was requested by the peer. */
3893 if (seq != prev + 1 || missing) {
3894 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3895 } else if (flags & RX_REQUEST_ACK) {
3896 ackNeeded = RX_ACK_REQUESTED;
3899 /* Acknowledge the last packet for each call */
3900 if (flags & RX_LAST_PACKET) {
3911 * If the receiver is waiting for an iovec, fill the iovec
3912 * using the data from the receive queue */
3913 if (call->flags & RX_CALL_IOVEC_WAIT) {
3914 didHardAck = rxi_FillReadVec(call, serial);
3915 /* the call may have been aborted */
3924 /* Wakeup the reader if any */
3925 if ((call->flags & RX_CALL_READER_WAIT)
3926 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3927 || (call->iovNext >= call->iovMax)
3928 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3929 call->flags &= ~RX_CALL_READER_WAIT;
3930 #ifdef RX_ENABLE_LOCKS
3931 CV_BROADCAST(&call->cv_rq);
3933 osi_rxWakeup(&call->rq);
3939 * Send an ack when requested by the peer, or once every
3940 * rxi_SoftAckRate packets until the last packet has been
3941 * received. Always send a soft ack for the last packet in
3942 * the server's reply.
3944 * If we have received all of the packets for the call
3945 * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3946 * the peer can empty its packet queue and cancel all resend
3949 if (call->flags & RX_CALL_RECEIVE_DONE) {
3950 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3951 rxi_AckAll(NULL, call, 0);
3952 } else if (ackNeeded) {
3953 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3954 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3955 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3956 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3957 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3958 } else if (call->nSoftAcks) {
3959 clock_GetTime(&now);
3961 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3962 clock_Add(&when, &rx_lastAckDelay);
3964 clock_Add(&when, &rx_softAckDelay);
3966 if (!call->delayedAckEvent
3967 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3968 rxevent_Cancel(call->delayedAckEvent, call,
3969 RX_CALL_REFCOUNT_DELAY);
3970 MUTEX_ENTER(&rx_refcnt_mutex);
3971 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3972 MUTEX_EXIT(&rx_refcnt_mutex);
3973 call->delayedAckEvent =
3974 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3982 static void rxi_ComputeRate();
3986 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3988 struct rx_peer *peer = conn->peer;
3990 MUTEX_ENTER(&peer->peer_lock);
3991 peer->lastReachTime = clock_Sec();
3992 MUTEX_EXIT(&peer->peer_lock);
3994 MUTEX_ENTER(&conn->conn_data_lock);
3995 if (conn->flags & RX_CONN_ATTACHWAIT) {
3998 conn->flags &= ~RX_CONN_ATTACHWAIT;
3999 MUTEX_EXIT(&conn->conn_data_lock);
4001 for (i = 0; i < RX_MAXCALLS; i++) {
4002 struct rx_call *call = conn->call[i];
4005 MUTEX_ENTER(&call->lock);
4006 /* tnop can be null if newcallp is null */
4007 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4009 MUTEX_EXIT(&call->lock);
4013 MUTEX_EXIT(&conn->conn_data_lock);
4016 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4018 rx_ack_reason(int reason)
4021 case RX_ACK_REQUESTED:
4023 case RX_ACK_DUPLICATE:
4025 case RX_ACK_OUT_OF_SEQUENCE:
4027 case RX_ACK_EXCEEDS_WINDOW:
4029 case RX_ACK_NOSPACE:
4033 case RX_ACK_PING_RESPONSE:
4046 /* The real smarts of the whole thing. */
4048 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4051 struct rx_ackPacket *ap;
4053 struct rx_packet *tp;
4054 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4055 struct rx_connection *conn = call->conn;
4056 struct rx_peer *peer = conn->peer;
4057 struct clock now; /* Current time, for RTT calculations */
4061 /* because there are CM's that are bogus, sending weird values for this. */
4062 afs_uint32 skew = 0;
4067 int newAckCount = 0;
4068 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4069 int pktsize = 0; /* Set if we need to update the peer mtu */
4070 int conn_data_locked = 0;
4072 if (rx_stats_active)
4073 rx_atomic_inc(&rx_stats.ackPacketsRead);
4074 ap = (struct rx_ackPacket *)rx_DataOf(np);
4075 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4077 return np; /* truncated ack packet */
4079 /* depends on ack packet struct */
4080 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4081 first = ntohl(ap->firstPacket);
4082 prev = ntohl(ap->previousPacket);
4083 serial = ntohl(ap->serial);
4084 /* temporarily disabled -- needs to degrade over time
4085 * skew = ntohs(ap->maxSkew); */
4087 /* Ignore ack packets received out of order */
4088 if (first < call->tfirst ||
4089 (first == call->tfirst && prev < call->tprev)) {
4095 if (np->header.flags & RX_SLOW_START_OK) {
4096 call->flags |= RX_CALL_SLOW_START_OK;
4099 if (ap->reason == RX_ACK_PING_RESPONSE)
4100 rxi_UpdatePeerReach(conn, call);
4102 if (conn->lastPacketSizeSeq) {
4103 MUTEX_ENTER(&conn->conn_data_lock);
4104 conn_data_locked = 1;
4105 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4106 pktsize = conn->lastPacketSize;
4107 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4110 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4111 if (!conn_data_locked) {
4112 MUTEX_ENTER(&conn->conn_data_lock);
4113 conn_data_locked = 1;
4115 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4116 /* process mtu ping ack */
4117 pktsize = conn->lastPingSize;
4118 conn->lastPingSizeSer = conn->lastPingSize = 0;
4122 if (conn_data_locked) {
4123 MUTEX_EXIT(&conn->conn_data_lock);
4124 conn_data_locked = 0;
4128 if (rxdebug_active) {
4132 len = _snprintf(msg, sizeof(msg),
4133 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4134 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4135 ntohl(ap->serial), ntohl(ap->previousPacket),
4136 (unsigned int)np->header.seq, (unsigned int)skew,
4137 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4141 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4142 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4146 OutputDebugString(msg);
4148 #else /* AFS_NT40_ENV */
4151 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4152 ap->reason, ntohl(ap->previousPacket),
4153 (unsigned int)np->header.seq, (unsigned int)serial,
4154 (unsigned int)skew, ntohl(ap->firstPacket));
4157 for (offset = 0; offset < nAcks; offset++)
4158 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4163 #endif /* AFS_NT40_ENV */
4166 MUTEX_ENTER(&peer->peer_lock);
4169 * Start somewhere. Can't assume we can send what we can receive,
4170 * but we are clearly receiving.
4172 if (!peer->maxPacketSize)
4173 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4175 if (pktsize > peer->maxPacketSize) {
4176 peer->maxPacketSize = pktsize;
4177 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4178 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4179 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4180 rxi_ScheduleGrowMTUEvent(call, 1);
4185 /* Update the outgoing packet skew value to the latest value of
4186 * the peer's incoming packet skew value. The ack packet, of
4187 * course, could arrive out of order, but that won't affect things
4189 peer->outPacketSkew = skew;
4191 /* Check for packets that no longer need to be transmitted, and
4192 * discard them. This only applies to packets positively
4193 * acknowledged as having been sent to the peer's upper level.
4194 * All other packets must be retained. So only packets with
4195 * sequence numbers < ap->firstPacket are candidates. */
4197 clock_GetTime(&now);
4199 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4200 if (tp->header.seq >= first)
4202 call->tfirst = tp->header.seq + 1;
4204 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4207 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4211 rxi_ComputeRate(call->conn->peer, call, p, np, ap->reason);
4214 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4215 /* XXX Hack. Because we have to release the global rx lock when sending
4216 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4217 * in rxi_Start sending packets out because packets may move to the
4218 * freePacketQueue as result of being here! So we drop these packets until
4219 * we're safely out of the traversing. Really ugly!
4220 * To make it even uglier, if we're using fine grain locking, we can
4221 * set the ack bits in the packets and have rxi_Start remove the packets
4222 * when it's done transmitting.
4224 if (call->flags & RX_CALL_TQ_BUSY) {
4225 #ifdef RX_ENABLE_LOCKS
4226 tp->flags |= RX_PKTFLAG_ACKED;
4227 call->flags |= RX_CALL_TQ_SOME_ACKED;
4228 #else /* RX_ENABLE_LOCKS */
4230 #endif /* RX_ENABLE_LOCKS */
4232 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4235 #ifdef RX_TRACK_PACKETS
4236 tp->flags &= ~RX_PKTFLAG_TQ;
4238 #ifdef RXDEBUG_PACKET
4240 #endif /* RXDEBUG_PACKET */
4241 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4246 /* Give rate detector a chance to respond to ping requests */
4247 if (ap->reason == RX_ACK_PING_RESPONSE) {
4248 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4252 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4254 /* Now go through explicit acks/nacks and record the results in
4255 * the waiting packets. These are packets that can't be released
4256 * yet, even with a positive acknowledge. This positive
4257 * acknowledge only means the packet has been received by the
4258 * peer, not that it will be retained long enough to be sent to
4259 * the peer's upper level. In addition, reset the transmit timers
4260 * of any missing packets (those packets that must be missing
4261 * because this packet was out of sequence) */
4263 call->nSoftAcked = 0;
4264 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4266 /* Set the acknowledge flag per packet based on the
4267 * information in the ack packet. An acknowlegded packet can
4268 * be downgraded when the server has discarded a packet it
4269 * soacked previously, or when an ack packet is received
4270 * out of sequence. */
4271 if (tp->header.seq < first) {
4272 /* Implicit ack information */
4273 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4276 tp->flags |= RX_PKTFLAG_ACKED;
4277 } else if (tp->header.seq < first + nAcks) {
4278 /* Explicit ack information: set it in the packet appropriately */
4279 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4280 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4282 tp->flags |= RX_PKTFLAG_ACKED;
4284 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4286 rxi_ComputeRate(call->conn->peer, call, tp, np,
4295 } else /* RX_ACK_TYPE_NACK */ {
4296 tp->flags &= ~RX_PKTFLAG_ACKED;
4300 if (tp->flags & RX_PKTFLAG_ACKED) {
4301 tp->flags &= ~RX_PKTFLAG_ACKED;
4307 * Following the suggestion of Phil Kern, we back off the peer's
4308 * timeout value for future packets until a successful response
4309 * is received for an initial transmission.
4311 if (missing && !peer->backedOff) {
4312 struct clock c = peer->timeout;
4313 struct clock max_to = {3, 0};
4315 clock_Add(&peer->timeout, &c);
4316 if (clock_Gt(&peer->timeout, &max_to))
4317 peer->timeout = max_to;
4318 peer->backedOff = 1;
4321 /* If packet isn't yet acked, and it has been transmitted at least
4322 * once, reset retransmit time using latest timeout
4323 * ie, this should readjust the retransmit timer for all outstanding
4324 * packets... So we don't just retransmit when we should know better*/
4326 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4327 tp->retryTime = tp->timeSent;
4328 clock_Add(&tp->retryTime, &peer->timeout);
4329 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4330 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4334 /* If the window has been extended by this acknowledge packet,
4335 * then wakeup a sender waiting in alloc for window space, or try
4336 * sending packets now, if he's been sitting on packets due to
4337 * lack of window space */
4338 if (call->tnext < (call->tfirst + call->twind)) {
4339 #ifdef RX_ENABLE_LOCKS
4340 CV_SIGNAL(&call->cv_twind);
4342 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4343 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4344 osi_rxWakeup(&call->twind);
4347 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4348 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4352 /* if the ack packet has a receivelen field hanging off it,
4353 * update our state */
4354 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4357 /* If the ack packet has a "recommended" size that is less than
4358 * what I am using now, reduce my size to match */
4359 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4360 (int)sizeof(afs_int32), &tSize);
4361 tSize = (afs_uint32) ntohl(tSize);
4362 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4364 /* Get the maximum packet size to send to this peer */
4365 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4367 tSize = (afs_uint32) ntohl(tSize);
4368 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4369 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4371 /* sanity check - peer might have restarted with different params.
4372 * If peer says "send less", dammit, send less... Peer should never
4373 * be unable to accept packets of the size that prior AFS versions would
4374 * send without asking. */
4375 if (peer->maxMTU != tSize) {
4376 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4378 peer->maxMTU = tSize;
4379 peer->MTU = MIN(tSize, peer->MTU);
4380 call->MTU = MIN(call->MTU, tSize);
4383 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4386 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4387 (int)sizeof(afs_int32), &tSize);
4388 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4389 if (tSize < call->twind) { /* smaller than our send */
4390 call->twind = tSize; /* window, we must send less... */
4391 call->ssthresh = MIN(call->twind, call->ssthresh);
4392 call->conn->twind[call->channel] = call->twind;
4395 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4396 * network MTU confused with the loopback MTU. Calculate the
4397 * maximum MTU here for use in the slow start code below.
4399 /* Did peer restart with older RX version? */
4400 if (peer->maxDgramPackets > 1) {
4401 peer->maxDgramPackets = 1;
4403 } else if (np->length >=
4404 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4407 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4408 sizeof(afs_int32), &tSize);
4409 tSize = (afs_uint32) ntohl(tSize);
4411 * As of AFS 3.5 we set the send window to match the receive window.
4413 if (tSize < call->twind) {
4414 call->twind = tSize;
4415 call->conn->twind[call->channel] = call->twind;
4416 call->ssthresh = MIN(call->twind, call->ssthresh);
4417 } else if (tSize > call->twind) {
4418 call->twind = tSize;
4419 call->conn->twind[call->channel] = call->twind;
4423 * As of AFS 3.5, a jumbogram is more than one fixed size
4424 * packet transmitted in a single UDP datagram. If the remote
4425 * MTU is smaller than our local MTU then never send a datagram
4426 * larger than the natural MTU.
4429 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4430 (int)sizeof(afs_int32), &tSize);
4431 maxDgramPackets = (afs_uint32) ntohl(tSize);
4432 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4434 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4435 if (maxDgramPackets > 1) {
4436 peer->maxDgramPackets = maxDgramPackets;
4437 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4439 peer->maxDgramPackets = 1;
4440 call->MTU = peer->natMTU;
4442 } else if (peer->maxDgramPackets > 1) {
4443 /* Restarted with lower version of RX */
4444 peer->maxDgramPackets = 1;
4446 } else if (peer->maxDgramPackets > 1
4447 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4448 /* Restarted with lower version of RX */
4449 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4450 peer->natMTU = OLD_MAX_PACKET_SIZE;
4451 peer->MTU = OLD_MAX_PACKET_SIZE;
4452 peer->maxDgramPackets = 1;
4453 peer->nDgramPackets = 1;
4455 call->MTU = OLD_MAX_PACKET_SIZE;
4460 * Calculate how many datagrams were successfully received after
4461 * the first missing packet and adjust the negative ack counter
4466 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4467 if (call->nNacks < nNacked) {
4468 call->nNacks = nNacked;
4471 call->nAcks += newAckCount;
4475 if (call->flags & RX_CALL_FAST_RECOVER) {
4477 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4479 call->flags &= ~RX_CALL_FAST_RECOVER;
4480 call->cwind = call->nextCwind;
4481 call->nextCwind = 0;
4484 call->nCwindAcks = 0;
4485 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4486 /* Three negative acks in a row trigger congestion recovery */
4487 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4488 MUTEX_EXIT(&peer->peer_lock);
4489 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4490 /* someone else is waiting to start recovery */
4493 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4494 rxi_WaitforTQBusy(call);
4495 MUTEX_ENTER(&peer->peer_lock);
4496 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4497 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4498 call->flags |= RX_CALL_FAST_RECOVER;
4499 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4501 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4502 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4503 call->nextCwind = call->ssthresh;
4506 peer->MTU = call->MTU;
4507 peer->cwind = call->nextCwind;
4508 peer->nDgramPackets = call->nDgramPackets;
4510 call->congestSeq = peer->congestSeq;
4511 /* Reset the resend times on the packets that were nacked
4512 * so we will retransmit as soon as the window permits*/
4513 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4515 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4516 clock_Zero(&tp->retryTime);
4518 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4523 /* If cwind is smaller than ssthresh, then increase
4524 * the window one packet for each ack we receive (exponential
4526 * If cwind is greater than or equal to ssthresh then increase
4527 * the congestion window by one packet for each cwind acks we
4528 * receive (linear growth). */
4529 if (call->cwind < call->ssthresh) {
4531 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4532 call->nCwindAcks = 0;
4534 call->nCwindAcks += newAckCount;
4535 if (call->nCwindAcks >= call->cwind) {
4536 call->nCwindAcks = 0;
4537 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4541 * If we have received several acknowledgements in a row then
4542 * it is time to increase the size of our datagrams
4544 if ((int)call->nAcks > rx_nDgramThreshold) {
4545 if (peer->maxDgramPackets > 1) {
4546 if (call->nDgramPackets < peer->maxDgramPackets) {
4547 call->nDgramPackets++;
4549 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4550 } else if (call->MTU < peer->maxMTU) {
4551 /* don't upgrade if we can't handle it */
4552 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4553 call->MTU = peer->ifMTU;
4555 call->MTU += peer->natMTU;
4556 call->MTU = MIN(call->MTU, peer->maxMTU);
4563 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4565 /* Servers need to hold the call until all response packets have
4566 * been acknowledged. Soft acks are good enough since clients
4567 * are not allowed to clear their receive queues. */
4568 if (call->state == RX_STATE_HOLD
4569 && call->tfirst + call->nSoftAcked >= call->tnext) {
4570 call->state = RX_STATE_DALLY;
4571 rxi_ClearTransmitQueue(call, 0);
4572 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4573 } else if (!queue_IsEmpty(&call->tq)) {
4574 rxi_Start(0, call, 0, istack);
4579 /* Received a response to a challenge packet */
4581 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4582 struct rx_packet *np, int istack)
4586 /* Ignore the packet if we're the client */
4587 if (conn->type == RX_CLIENT_CONNECTION)
4590 /* If already authenticated, ignore the packet (it's probably a retry) */
4591 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4594 /* Otherwise, have the security object evaluate the response packet */
4595 error = RXS_CheckResponse(conn->securityObject, conn, np);
4597 /* If the response is invalid, reset the connection, sending
4598 * an abort to the peer */
4602 rxi_ConnectionError(conn, error);
4603 MUTEX_ENTER(&conn->conn_data_lock);
4604 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4605 MUTEX_EXIT(&conn->conn_data_lock);
4608 /* If the response is valid, any calls waiting to attach
4609 * servers can now do so */
4612 for (i = 0; i < RX_MAXCALLS; i++) {
4613 struct rx_call *call = conn->call[i];
4615 MUTEX_ENTER(&call->lock);
4616 if (call->state == RX_STATE_PRECALL)
4617 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4618 /* tnop can be null if newcallp is null */
4619 MUTEX_EXIT(&call->lock);
4623 /* Update the peer reachability information, just in case
4624 * some calls went into attach-wait while we were waiting
4625 * for authentication..
4627 rxi_UpdatePeerReach(conn, NULL);
4632 /* A client has received an authentication challenge: the security
4633 * object is asked to cough up a respectable response packet to send
4634 * back to the server. The server is responsible for retrying the
4635 * challenge if it fails to get a response. */
4638 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4639 struct rx_packet *np, int istack)
4643 /* Ignore the challenge if we're the server */
4644 if (conn->type == RX_SERVER_CONNECTION)
4647 /* Ignore the challenge if the connection is otherwise idle; someone's
4648 * trying to use us as an oracle. */
4649 if (!rxi_HasActiveCalls(conn))
4652 /* Send the security object the challenge packet. It is expected to fill
4653 * in the response. */
4654 error = RXS_GetResponse(conn->securityObject, conn, np);
4656 /* If the security object is unable to return a valid response, reset the
4657 * connection and send an abort to the peer. Otherwise send the response
4658 * packet to the peer connection. */
4660 rxi_ConnectionError(conn, error);
4661 MUTEX_ENTER(&conn->conn_data_lock);
4662 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4663 MUTEX_EXIT(&conn->conn_data_lock);
4665 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4666 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4672 /* Find an available server process to service the current request in
4673 * the given call structure. If one isn't available, queue up this
4674 * call so it eventually gets one */
4676 rxi_AttachServerProc(struct rx_call *call,
4677 osi_socket socket, int *tnop,
4678 struct rx_call **newcallp)
4680 struct rx_serverQueueEntry *sq;
4681 struct rx_service *service = call->conn->service;
4684 /* May already be attached */
4685 if (call->state == RX_STATE_ACTIVE)
4688 MUTEX_ENTER(&rx_serverPool_lock);
4690 haveQuota = QuotaOK(service);
4691 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4692 /* If there are no processes available to service this call,
4693 * put the call on the incoming call queue (unless it's
4694 * already on the queue).
4696 #ifdef RX_ENABLE_LOCKS
4698 ReturnToServerPool(service);
4699 #endif /* RX_ENABLE_LOCKS */
4701 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4702 call->flags |= RX_CALL_WAIT_PROC;
4703 rx_atomic_inc(&rx_nWaiting);
4704 rx_atomic_inc(&rx_nWaited);
4705 rxi_calltrace(RX_CALL_ARRIVAL, call);
4706 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4707 queue_Append(&rx_incomingCallQueue, call);
4710 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4712 /* If hot threads are enabled, and both newcallp and sq->socketp
4713 * are non-null, then this thread will process the call, and the
4714 * idle server thread will start listening on this threads socket.
4717 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4720 *sq->socketp = socket;
4721 clock_GetTime(&call->startTime);
4722 MUTEX_ENTER(&rx_refcnt_mutex);
4723 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4724 MUTEX_EXIT(&rx_refcnt_mutex);
4728 if (call->flags & RX_CALL_WAIT_PROC) {
4729 /* Conservative: I don't think this should happen */
4730 call->flags &= ~RX_CALL_WAIT_PROC;
4731 if (queue_IsOnQueue(call)) {
4734 rx_atomic_dec(&rx_nWaiting);
4737 call->state = RX_STATE_ACTIVE;
4738 call->mode = RX_MODE_RECEIVING;
4739 #ifdef RX_KERNEL_TRACE
4741 int glockOwner = ISAFS_GLOCK();
4744 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4745 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4751 if (call->flags & RX_CALL_CLEARED) {
4752 /* send an ack now to start the packet flow up again */
4753 call->flags &= ~RX_CALL_CLEARED;
4754 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4756 #ifdef RX_ENABLE_LOCKS
4759 service->nRequestsRunning++;
4760 MUTEX_ENTER(&rx_quota_mutex);
4761 if (service->nRequestsRunning <= service->minProcs)
4764 MUTEX_EXIT(&rx_quota_mutex);
4768 MUTEX_EXIT(&rx_serverPool_lock);
4771 /* Delay the sending of an acknowledge event for a short while, while
4772 * a new call is being prepared (in the case of a client) or a reply
4773 * is being prepared (in the case of a server). Rather than sending
4774 * an ack packet, an ACKALL packet is sent. */
4776 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4778 #ifdef RX_ENABLE_LOCKS
4780 MUTEX_ENTER(&call->lock);
4781 call->delayedAckEvent = NULL;
4782 MUTEX_ENTER(&rx_refcnt_mutex);
4783 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4784 MUTEX_EXIT(&rx_refcnt_mutex);
4786 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4787 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4789 MUTEX_EXIT(&call->lock);
4790 #else /* RX_ENABLE_LOCKS */
4792 call->delayedAckEvent = NULL;
4793 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4794 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4795 #endif /* RX_ENABLE_LOCKS */
4799 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4801 struct rx_call *call = arg1;
4802 #ifdef RX_ENABLE_LOCKS
4804 MUTEX_ENTER(&call->lock);
4805 if (event == call->delayedAckEvent)
4806 call->delayedAckEvent = NULL;
4807 MUTEX_ENTER(&rx_refcnt_mutex);
4808 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4809 MUTEX_EXIT(&rx_refcnt_mutex);
4811 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4813 MUTEX_EXIT(&call->lock);
4814 #else /* RX_ENABLE_LOCKS */
4816 call->delayedAckEvent = NULL;
4817 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4818 #endif /* RX_ENABLE_LOCKS */
4822 #ifdef RX_ENABLE_LOCKS
4823 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4824 * clearing them out.
4827 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4829 struct rx_packet *p, *tp;
4832 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4833 p->flags |= RX_PKTFLAG_ACKED;
4837 call->flags |= RX_CALL_TQ_CLEARME;
4838 call->flags |= RX_CALL_TQ_SOME_ACKED;
4841 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4842 call->tfirst = call->tnext;
4843 call->nSoftAcked = 0;
4845 if (call->flags & RX_CALL_FAST_RECOVER) {
4846 call->flags &= ~RX_CALL_FAST_RECOVER;
4847 call->cwind = call->nextCwind;
4848 call->nextCwind = 0;
4851 CV_SIGNAL(&call->cv_twind);
4853 #endif /* RX_ENABLE_LOCKS */
4855 /* Clear out the transmit queue for the current call (all packets have
4856 * been received by peer) */
4858 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4860 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4861 struct rx_packet *p, *tp;
4863 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4865 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4866 p->flags |= RX_PKTFLAG_ACKED;
4870 call->flags |= RX_CALL_TQ_CLEARME;
4871 call->flags |= RX_CALL_TQ_SOME_ACKED;
4874 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4875 #ifdef RXDEBUG_PACKET
4877 #endif /* RXDEBUG_PACKET */
4878 rxi_FreePackets(0, &call->tq);
4879 rxi_WakeUpTransmitQueue(call);
4880 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4881 call->flags &= ~RX_CALL_TQ_CLEARME;
4883 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4885 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4886 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4887 call->nSoftAcked = 0;
4889 if (call->flags & RX_CALL_FAST_RECOVER) {
4890 call->flags &= ~RX_CALL_FAST_RECOVER;
4891 call->cwind = call->nextCwind;
4893 #ifdef RX_ENABLE_LOCKS
4894 CV_SIGNAL(&call->cv_twind);
4896 osi_rxWakeup(&call->twind);
4901 rxi_ClearReceiveQueue(struct rx_call *call)
4903 if (queue_IsNotEmpty(&call->rq)) {
4906 count = rxi_FreePackets(0, &call->rq);
4907 rx_packetReclaims += count;
4908 #ifdef RXDEBUG_PACKET
4910 if ( call->rqc != 0 )
4911 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
4913 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4915 if (call->state == RX_STATE_PRECALL) {
4916 call->flags |= RX_CALL_CLEARED;
4920 /* Send an abort packet for the specified call */
4922 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4923 int istack, int force)
4926 struct clock when, now;
4931 /* Clients should never delay abort messages */
4932 if (rx_IsClientConn(call->conn))
4935 if (call->abortCode != call->error) {
4936 call->abortCode = call->error;
4937 call->abortCount = 0;
4940 if (force || rxi_callAbortThreshhold == 0
4941 || call->abortCount < rxi_callAbortThreshhold) {
4942 if (call->delayedAbortEvent) {
4943 rxevent_Cancel(call->delayedAbortEvent, call,
4944 RX_CALL_REFCOUNT_ABORT);
4946 error = htonl(call->error);
4949 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4950 (char *)&error, sizeof(error), istack);
4951 } else if (!call->delayedAbortEvent) {
4952 clock_GetTime(&now);
4954 clock_Addmsec(&when, rxi_callAbortDelay);
4955 MUTEX_ENTER(&rx_refcnt_mutex);
4956 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4957 MUTEX_EXIT(&rx_refcnt_mutex);
4958 call->delayedAbortEvent =
4959 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4964 /* Send an abort packet for the specified connection. Packet is an
4965 * optional pointer to a packet that can be used to send the abort.
4966 * Once the number of abort messages reaches the threshhold, an
4967 * event is scheduled to send the abort. Setting the force flag
4968 * overrides sending delayed abort messages.
4970 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4971 * to send the abort packet.
4974 rxi_SendConnectionAbort(struct rx_connection *conn,
4975 struct rx_packet *packet, int istack, int force)
4978 struct clock when, now;
4983 /* Clients should never delay abort messages */
4984 if (rx_IsClientConn(conn))
4987 if (force || rxi_connAbortThreshhold == 0
4988 || conn->abortCount < rxi_connAbortThreshhold) {
4989 if (conn->delayedAbortEvent) {
4990 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4992 error = htonl(conn->error);
4994 MUTEX_EXIT(&conn->conn_data_lock);
4996 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4997 RX_PACKET_TYPE_ABORT, (char *)&error,
4998 sizeof(error), istack);
4999 MUTEX_ENTER(&conn->conn_data_lock);
5000 } else if (!conn->delayedAbortEvent) {
5001 clock_GetTime(&now);
5003 clock_Addmsec(&when, rxi_connAbortDelay);
5004 conn->delayedAbortEvent =
5005 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
5010 /* Associate an error all of the calls owned by a connection. Called
5011 * with error non-zero. This is only for really fatal things, like
5012 * bad authentication responses. The connection itself is set in
5013 * error at this point, so that future packets received will be
5016 rxi_ConnectionError(struct rx_connection *conn,
5022 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5024 MUTEX_ENTER(&conn->conn_data_lock);
5025 if (conn->challengeEvent)
5026 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
5027 if (conn->natKeepAliveEvent)
5028 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
5029 if (conn->checkReachEvent) {
5030 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
5031 conn->checkReachEvent = 0;
5032 conn->flags &= ~RX_CONN_ATTACHWAIT;
5033 MUTEX_ENTER(&rx_refcnt_mutex);
5035 MUTEX_EXIT(&rx_refcnt_mutex);
5037 MUTEX_EXIT(&conn->conn_data_lock);
5038 for (i = 0; i < RX_MAXCALLS; i++) {
5039 struct rx_call *call = conn->call[i];
5041 MUTEX_ENTER(&call->lock);
5042 rxi_CallError(call, error);
5043 MUTEX_EXIT(&call->lock);
5046 conn->error = error;
5047 if (rx_stats_active)
5048 rx_atomic_inc(&rx_stats.fatalErrors);
5053 * Interrupt an in-progress call with the specified error and wakeup waiters.
5055 * @param[in] call The call to interrupt
5056 * @param[in] error The error code to send to the peer
5059 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5061 MUTEX_ENTER(&call->lock);
5062 rxi_CallError(call, error);
5063 rxi_SendCallAbort(call, NULL, 0, 1);
5064 MUTEX_EXIT(&call->lock);
5068 rxi_CallError(struct rx_call *call, afs_int32 error)
5071 osirx_AssertMine(&call->lock, "rxi_CallError");
5073 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5075 error = call->error;
5077 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5078 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5079 rxi_ResetCall(call, 0);
5082 rxi_ResetCall(call, 0);
5084 call->error = error;
5087 /* Reset various fields in a call structure, and wakeup waiting
5088 * processes. Some fields aren't changed: state & mode are not
5089 * touched (these must be set by the caller), and bufptr, nLeft, and
5090 * nFree are not reset, since these fields are manipulated by
5091 * unprotected macros, and may only be reset by non-interrupting code.
5094 /* this code requires that call->conn be set properly as a pre-condition. */
5095 #endif /* ADAPT_WINDOW */
5098 rxi_ResetCall(struct rx_call *call, int newcall)
5101 struct rx_peer *peer;
5102 struct rx_packet *packet;
5104 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5106 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5108 /* Notify anyone who is waiting for asynchronous packet arrival */
5109 if (call->arrivalProc) {
5110 (*call->arrivalProc) (call, call->arrivalProcHandle,
5111 call->arrivalProcArg);
5112 call->arrivalProc = (void (*)())0;
5115 if (call->delayedAbortEvent) {
5116 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5117 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5119 rxi_SendCallAbort(call, packet, 0, 1);
5120 rxi_FreePacket(packet);
5125 * Update the peer with the congestion information in this call
5126 * so other calls on this connection can pick up where this call
5127 * left off. If the congestion sequence numbers don't match then
5128 * another call experienced a retransmission.
5130 peer = call->conn->peer;
5131 MUTEX_ENTER(&peer->peer_lock);
5133 if (call->congestSeq == peer->congestSeq) {
5134 peer->cwind = MAX(peer->cwind, call->cwind);
5135 peer->MTU = MAX(peer->MTU, call->MTU);
5136 peer->nDgramPackets =
5137 MAX(peer->nDgramPackets, call->nDgramPackets);
5140 call->abortCode = 0;
5141 call->abortCount = 0;
5143 if (peer->maxDgramPackets > 1) {
5144 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5146 call->MTU = peer->MTU;
5148 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5149 call->ssthresh = rx_maxSendWindow;
5150 call->nDgramPackets = peer->nDgramPackets;
5151 call->congestSeq = peer->congestSeq;
5152 MUTEX_EXIT(&peer->peer_lock);
5154 flags = call->flags;
5155 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5156 rxi_WaitforTQBusy(call);
5157 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5159 rxi_ClearTransmitQueue(call, 1);
5160 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5161 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5165 if ((flags & RX_CALL_PEER_BUSY)) {
5166 /* The call channel is still busy; resetting the call doesn't change
5168 call->flags |= RX_CALL_PEER_BUSY;
5171 rxi_ClearReceiveQueue(call);
5172 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5176 call->twind = call->conn->twind[call->channel];
5177 call->rwind = call->conn->rwind[call->channel];
5178 call->nSoftAcked = 0;
5179 call->nextCwind = 0;
5182 call->nCwindAcks = 0;
5183 call->nSoftAcks = 0;
5184 call->nHardAcks = 0;
5186 call->tfirst = call->rnext = call->tnext = 1;
5189 call->lastAcked = 0;
5190 call->localStatus = call->remoteStatus = 0;
5192 if (flags & RX_CALL_READER_WAIT) {
5193 #ifdef RX_ENABLE_LOCKS
5194 CV_BROADCAST(&call->cv_rq);
5196 osi_rxWakeup(&call->rq);
5199 if (flags & RX_CALL_WAIT_PACKETS) {
5200 MUTEX_ENTER(&rx_freePktQ_lock);
5201 rxi_PacketsUnWait(); /* XXX */
5202 MUTEX_EXIT(&rx_freePktQ_lock);
5204 #ifdef RX_ENABLE_LOCKS
5205 CV_SIGNAL(&call->cv_twind);
5207 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5208 osi_rxWakeup(&call->twind);
5211 #ifdef RX_ENABLE_LOCKS
5212 /* The following ensures that we don't mess with any queue while some
5213 * other thread might also be doing so. The call_queue_lock field is
5214 * is only modified under the call lock. If the call is in the process
5215 * of being removed from a queue, the call is not locked until the
5216 * the queue lock is dropped and only then is the call_queue_lock field
5217 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5218 * Note that any other routine which removes a call from a queue has to
5219 * obtain the queue lock before examing the queue and removing the call.
5221 if (call->call_queue_lock) {
5222 MUTEX_ENTER(call->call_queue_lock);
5223 if (queue_IsOnQueue(call)) {
5225 if (flags & RX_CALL_WAIT_PROC) {
5226 rx_atomic_dec(&rx_nWaiting);
5229 MUTEX_EXIT(call->call_queue_lock);
5230 CLEAR_CALL_QUEUE_LOCK(call);
5232 #else /* RX_ENABLE_LOCKS */
5233 if (queue_IsOnQueue(call)) {
5235 if (flags & RX_CALL_WAIT_PROC)
5236 rx_atomic_dec(&rx_nWaiting);
5238 #endif /* RX_ENABLE_LOCKS */
5240 rxi_KeepAliveOff(call);
5241 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5244 /* Send an acknowledge for the indicated packet (seq,serial) of the
5245 * indicated call, for the indicated reason (reason). This
5246 * acknowledge will specifically acknowledge receiving the packet, and
5247 * will also specify which other packets for this call have been
5248 * received. This routine returns the packet that was used to the
5249 * caller. The caller is responsible for freeing it or re-using it.
5250 * This acknowledgement also returns the highest sequence number
5251 * actually read out by the higher level to the sender; the sender
5252 * promises to keep around packets that have not been read by the
5253 * higher level yet (unless, of course, the sender decides to abort
5254 * the call altogether). Any of p, seq, serial, pflags, or reason may
5255 * be set to zero without ill effect. That is, if they are zero, they
5256 * will not convey any information.
5257 * NOW there is a trailer field, after the ack where it will safely be
5258 * ignored by mundanes, which indicates the maximum size packet this
5259 * host can swallow. */
5261 struct rx_packet *optionalPacket; use to send ack (or null)
5262 int seq; Sequence number of the packet we are acking
5263 int serial; Serial number of the packet
5264 int pflags; Flags field from packet header
5265 int reason; Reason an acknowledge was prompted
5269 rxi_SendAck(struct rx_call *call,
5270 struct rx_packet *optionalPacket, int serial, int reason,
5273 struct rx_ackPacket *ap;
5274 struct rx_packet *rqp;
5275 struct rx_packet *nxp; /* For queue_Scan */
5276 struct rx_packet *p;
5279 afs_uint32 padbytes = 0;
5280 #ifdef RX_ENABLE_TSFPQ
5281 struct rx_ts_info_t * rx_ts_info;
5285 * Open the receive window once a thread starts reading packets
5287 if (call->rnext > 1) {
5288 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5291 /* Don't attempt to grow MTU if this is a critical ping */
5292 if (reason == RX_ACK_MTU) {
5293 /* keep track of per-call attempts, if we're over max, do in small
5294 * otherwise in larger? set a size to increment by, decrease
5297 if (call->conn->peer->maxPacketSize &&
5298 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5300 padbytes = call->conn->peer->maxPacketSize+16;
5302 padbytes = call->conn->peer->maxMTU + 128;
5304 /* do always try a minimum size ping */
5305 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5307 /* subtract the ack payload */
5308 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5309 reason = RX_ACK_PING;
5312 call->nHardAcks = 0;
5313 call->nSoftAcks = 0;
5314 if (call->rnext > call->lastAcked)
5315 call->lastAcked = call->rnext;
5319 rx_computelen(p, p->length); /* reset length, you never know */
5320 } /* where that's been... */
5321 #ifdef RX_ENABLE_TSFPQ
5323 RX_TS_INFO_GET(rx_ts_info);
5324 if ((p = rx_ts_info->local_special_packet)) {
5325 rx_computelen(p, p->length);
5326 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5327 rx_ts_info->local_special_packet = p;
5328 } else { /* We won't send the ack, but don't panic. */
5329 return optionalPacket;
5333 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5334 /* We won't send the ack, but don't panic. */
5335 return optionalPacket;
5340 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5343 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5344 #ifndef RX_ENABLE_TSFPQ
5345 if (!optionalPacket)
5348 return optionalPacket;
5350 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5351 if (rx_Contiguous(p) < templ) {
5352 #ifndef RX_ENABLE_TSFPQ
5353 if (!optionalPacket)
5356 return optionalPacket;
5361 /* MTUXXX failing to send an ack is very serious. We should */
5362 /* try as hard as possible to send even a partial ack; it's */
5363 /* better than nothing. */
5364 ap = (struct rx_ackPacket *)rx_DataOf(p);
5365 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5366 ap->reason = reason;
5368 /* The skew computation used to be bogus, I think it's better now. */
5369 /* We should start paying attention to skew. XXX */
5370 ap->serial = htonl(serial);
5371 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5373 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5374 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5376 /* No fear of running out of ack packet here because there can only be at most
5377 * one window full of unacknowledged packets. The window size must be constrained
5378 * to be less than the maximum ack size, of course. Also, an ack should always
5379 * fit into a single packet -- it should not ever be fragmented. */
5380 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5381 if (!rqp || !call->rq.next
5382 || (rqp->header.seq > (call->rnext + call->rwind))) {
5383 #ifndef RX_ENABLE_TSFPQ
5384 if (!optionalPacket)
5387 rxi_CallError(call, RX_CALL_DEAD);
5388 return optionalPacket;
5391 while (rqp->header.seq > call->rnext + offset)
5392 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5393 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5395 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5396 #ifndef RX_ENABLE_TSFPQ
5397 if (!optionalPacket)
5400 rxi_CallError(call, RX_CALL_DEAD);
5401 return optionalPacket;
5406 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5408 /* these are new for AFS 3.3 */
5409 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5410 templ = htonl(templ);
5411 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5412 templ = htonl(call->conn->peer->ifMTU);
5413 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5414 sizeof(afs_int32), &templ);
5416 /* new for AFS 3.4 */
5417 templ = htonl(call->rwind);
5418 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5419 sizeof(afs_int32), &templ);
5421 /* new for AFS 3.5 */
5422 templ = htonl(call->conn->peer->ifDgramPackets);
5423 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5424 sizeof(afs_int32), &templ);
5426 p->header.serviceId = call->conn->serviceId;
5427 p->header.cid = (call->conn->cid | call->channel);
5428 p->header.callNumber = *call->callNumber;
5430 p->header.securityIndex = call->conn->securityIndex;
5431 p->header.epoch = call->conn->epoch;
5432 p->header.type = RX_PACKET_TYPE_ACK;
5433 p->header.flags = RX_SLOW_START_OK;
5434 if (reason == RX_ACK_PING) {
5435 p->header.flags |= RX_REQUEST_ACK;
5437 clock_GetTime(&call->pingRequestTime);
5440 p->length = padbytes +
5441 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5444 /* not fast but we can potentially use this if truncated
5445 * fragments are delivered to figure out the mtu.
5447 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5448 sizeof(afs_int32), sizeof(afs_int32),
5452 if (call->conn->type == RX_CLIENT_CONNECTION)
5453 p->header.flags |= RX_CLIENT_INITIATED;
5457 if (rxdebug_active) {
5461 len = _snprintf(msg, sizeof(msg),
5462 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5463 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5464 ntohl(ap->serial), ntohl(ap->previousPacket),
5465 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5466 ap->nAcks, ntohs(ap->bufferSpace) );
5470 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5471 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5475 OutputDebugString(msg);
5477 #else /* AFS_NT40_ENV */
5479 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5480 ap->reason, ntohl(ap->previousPacket),
5481 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5483 for (offset = 0; offset < ap->nAcks; offset++)
5484 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5489 #endif /* AFS_NT40_ENV */
5492 int i, nbytes = p->length;
5494 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5495 if (nbytes <= p->wirevec[i].iov_len) {
5498 savelen = p->wirevec[i].iov_len;
5500 p->wirevec[i].iov_len = nbytes;
5502 rxi_Send(call, p, istack);
5503 p->wirevec[i].iov_len = savelen;
5507 nbytes -= p->wirevec[i].iov_len;
5510 if (rx_stats_active)
5511 rx_atomic_inc(&rx_stats.ackPacketsSent);
5512 #ifndef RX_ENABLE_TSFPQ
5513 if (!optionalPacket)
5516 return optionalPacket; /* Return packet for re-use by caller */
5520 struct rx_packet **list;
5525 /* Send all of the packets in the list in single datagram */
5527 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5528 int istack, int moreFlag)
5533 struct clock now, retryTime;
5534 struct rx_connection *conn = call->conn;
5535 struct rx_peer *peer = conn->peer;
5537 MUTEX_ENTER(&peer->peer_lock);
5538 peer->nSent += xmit->len;
5539 if (xmit->resending)
5540 peer->reSends += xmit->len;
5541 retryTime = peer->timeout;
5542 MUTEX_EXIT(&peer->peer_lock);
5544 if (rx_stats_active) {
5545 if (xmit->resending)
5546 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5548 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5551 clock_GetTime(&now);
5552 clock_Add(&retryTime, &now);
5554 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5558 /* Set the packet flags and schedule the resend events */
5559 /* Only request an ack for the last packet in the list */
5560 for (i = 0; i < xmit->len; i++) {
5561 struct rx_packet *packet = xmit->list[i];
5563 packet->retryTime = retryTime;
5564 if (packet->header.serial) {
5565 /* Exponentially backoff retry times */
5566 if (packet->backoff < MAXBACKOFF) {
5567 /* so it can't stay == 0 */
5568 packet->backoff = (packet->backoff << 1) + 1;
5571 clock_Addmsec(&(packet->retryTime),
5572 ((afs_uint32) packet->backoff) << 8);
5575 /* Wait a little extra for the ack on the last packet */
5577 && !(packet->header.flags & RX_CLIENT_INITIATED)) {
5578 clock_Addmsec(&(packet->retryTime), 400);
5581 /* Record the time sent */
5582 packet->timeSent = now;
5584 /* Ask for an ack on retransmitted packets, on every other packet
5585 * if the peer doesn't support slow start. Ask for an ack on every
5586 * packet until the congestion window reaches the ack rate. */
5587 if (packet->header.serial) {
5590 /* improved RTO calculation- not Karn */
5591 packet->firstSent = now;
5592 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5593 || (!(call->flags & RX_CALL_SLOW_START_OK)
5594 && (packet->header.seq & 1)))) {
5599 /* Tag this packet as not being the last in this group,
5600 * for the receiver's benefit */
5601 if (i < xmit->len - 1 || moreFlag) {
5602 packet->header.flags |= RX_MORE_PACKETS;
5607 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5610 /* Since we're about to send a data packet to the peer, it's
5611 * safe to nuke any scheduled end-of-packets ack */
5612 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5614 MUTEX_EXIT(&call->lock);
5615 MUTEX_ENTER(&rx_refcnt_mutex);
5616 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5617 MUTEX_EXIT(&rx_refcnt_mutex);
5618 if (xmit->len > 1) {
5619 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5621 rxi_SendPacket(call, conn, xmit->list[0], istack);
5623 MUTEX_ENTER(&call->lock);
5624 MUTEX_ENTER(&rx_refcnt_mutex);
5625 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5626 MUTEX_EXIT(&rx_refcnt_mutex);
5628 /* Update last send time for this call (for keep-alive
5629 * processing), and for the connection (so that we can discover
5630 * idle connections) */
5631 conn->lastSendTime = call->lastSendTime = clock_Sec();
5632 /* Let a set of retransmits trigger an idle timeout */
5633 if (!xmit->resending)
5634 call->lastSendData = call->lastSendTime;
5637 /* When sending packets we need to follow these rules:
5638 * 1. Never send more than maxDgramPackets in a jumbogram.
5639 * 2. Never send a packet with more than two iovecs in a jumbogram.
5640 * 3. Never send a retransmitted packet in a jumbogram.
5641 * 4. Never send more than cwind/4 packets in a jumbogram
5642 * We always keep the last list we should have sent so we
5643 * can set the RX_MORE_PACKETS flags correctly.
5647 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5651 struct xmitlist working;
5652 struct xmitlist last;
5654 struct rx_peer *peer = call->conn->peer;
5655 int morePackets = 0;
5657 memset(&last, 0, sizeof(struct xmitlist));
5658 working.list = &list[0];
5660 working.resending = 0;
5662 for (i = 0; i < len; i++) {
5663 /* Does the current packet force us to flush the current list? */
5665 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5666 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5668 /* This sends the 'last' list and then rolls the current working
5669 * set into the 'last' one, and resets the working set */
5672 rxi_SendList(call, &last, istack, 1);
5673 /* If the call enters an error state stop sending, or if
5674 * we entered congestion recovery mode, stop sending */
5675 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5680 working.resending = 0;
5681 working.list = &list[i];
5683 /* Add the current packet to the list if it hasn't been acked.
5684 * Otherwise adjust the list pointer to skip the current packet. */
5685 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5688 if (list[i]->header.serial)
5689 working.resending = 1;
5691 /* Do we need to flush the list? */
5692 if (working.len >= (int)peer->maxDgramPackets
5693 || working.len >= (int)call->nDgramPackets
5694 || working.len >= (int)call->cwind
5695 || list[i]->header.serial
5696 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5698 rxi_SendList(call, &last, istack, 1);
5699 /* If the call enters an error state stop sending, or if
5700 * we entered congestion recovery mode, stop sending */
5702 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5707 working.resending = 0;
5708 working.list = &list[i + 1];
5711 if (working.len != 0) {
5712 osi_Panic("rxi_SendList error");
5714 working.list = &list[i + 1];
5718 /* Send the whole list when the call is in receive mode, when
5719 * the call is in eof mode, when we are in fast recovery mode,
5720 * and when we have the last packet */
5721 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5722 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5723 || (call->flags & RX_CALL_FAST_RECOVER)) {
5724 /* Check for the case where the current list contains
5725 * an acked packet. Since we always send retransmissions
5726 * in a separate packet, we only need to check the first
5727 * packet in the list */
5728 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5732 rxi_SendList(call, &last, istack, morePackets);
5733 /* If the call enters an error state stop sending, or if
5734 * we entered congestion recovery mode, stop sending */
5735 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5739 rxi_SendList(call, &working, istack, 0);
5741 } else if (last.len > 0) {
5742 rxi_SendList(call, &last, istack, 0);
5743 /* Packets which are in 'working' are not sent by this call */
5747 #ifdef RX_ENABLE_LOCKS
5748 /* Call rxi_Start, below, but with the call lock held. */
5750 rxi_StartUnlocked(struct rxevent *event,
5751 void *arg0, void *arg1, int istack)
5753 struct rx_call *call = arg0;
5755 MUTEX_ENTER(&call->lock);
5756 rxi_Start(event, call, arg1, istack);
5757 MUTEX_EXIT(&call->lock);
5759 #endif /* RX_ENABLE_LOCKS */
5761 /* This routine is called when new packets are readied for
5762 * transmission and when retransmission may be necessary, or when the
5763 * transmission window or burst count are favourable. This should be
5764 * better optimized for new packets, the usual case, now that we've
5765 * got rid of queues of send packets. XXXXXXXXXXX */
5767 rxi_Start(struct rxevent *event,
5768 void *arg0, void *arg1, int istack)
5770 struct rx_call *call = arg0;
5772 struct rx_packet *p;
5773 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5774 struct clock now, usenow, retryTime;
5779 /* If rxi_Start is being called as a result of a resend event,
5780 * then make sure that the event pointer is removed from the call
5781 * structure, since there is no longer a per-call retransmission
5783 if (event && event == call->resendEvent) {
5784 MUTEX_ENTER(&rx_refcnt_mutex);
5785 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5786 MUTEX_EXIT(&rx_refcnt_mutex);
5787 call->resendEvent = NULL;
5789 if ((call->flags & RX_CALL_PEER_BUSY)) {
5790 rxi_CheckBusy(call);
5793 if (queue_IsEmpty(&call->tq)) {
5800 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5801 if (rx_stats_active)
5802 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5807 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5809 clock_GetTime(&now);
5812 /* Send (or resend) any packets that need it, subject to
5813 * window restrictions and congestion burst control
5814 * restrictions. Ask for an ack on the last packet sent in
5815 * this burst. For now, we're relying upon the window being
5816 * considerably bigger than the largest number of packets that
5817 * are typically sent at once by one initial call to
5818 * rxi_Start. This is probably bogus (perhaps we should ask
5819 * for an ack when we're half way through the current
5820 * window?). Also, for non file transfer applications, this
5821 * may end up asking for an ack for every packet. Bogus. XXXX
5824 * But check whether we're here recursively, and let the other guy
5827 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5828 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5829 call->flags |= RX_CALL_TQ_BUSY;
5831 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5833 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5834 call->flags &= ~RX_CALL_NEED_START;
5835 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5837 maxXmitPackets = MIN(call->twind, call->cwind);
5838 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5839 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5840 /* We shouldn't be sending packets if a thread is waiting
5841 * to initiate congestion recovery */
5842 dpf(("call %d waiting to initiate fast recovery\n",
5843 *(call->callNumber)));
5847 && (call->flags & RX_CALL_FAST_RECOVER)) {
5848 /* Only send one packet during fast recovery */
5849 dpf(("call %d restricted to one packet per send during fast recovery\n",
5850 *(call->callNumber)));
5853 #ifdef RX_TRACK_PACKETS
5854 if ((p->flags & RX_PKTFLAG_FREE)
5855 || (!queue_IsEnd(&call->tq, nxp)
5856 && (nxp->flags & RX_PKTFLAG_FREE))
5857 || (p == (struct rx_packet *)&rx_freePacketQueue)
5858 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5859 osi_Panic("rxi_Start: xmit queue clobbered");
5862 if (p->flags & RX_PKTFLAG_ACKED) {
5863 /* Since we may block, don't trust this */
5864 usenow.sec = usenow.usec = 0;
5865 if (rx_stats_active)
5866 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5867 continue; /* Ignore this packet if it has been acknowledged */
5870 /* Turn off all flags except these ones, which are the same
5871 * on each transmission */
5872 p->header.flags &= RX_PRESET_FLAGS;
5874 if (p->header.seq >=
5875 call->tfirst + MIN((int)call->twind,
5876 (int)(call->nSoftAcked +
5878 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5879 /* Note: if we're waiting for more window space, we can
5880 * still send retransmits; hence we don't return here, but
5881 * break out to schedule a retransmit event */
5882 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5883 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5888 /* Transmit the packet if it needs to be sent. */
5889 if (!clock_Lt(&now, &p->retryTime)) {
5890 if (nXmitPackets == maxXmitPackets) {
5891 rxi_SendXmitList(call, call->xmitList,
5892 nXmitPackets, istack);
5895 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u\n",
5896 *(call->callNumber), p,
5898 p->retryTime.sec, p->retryTime.usec));
5899 call->xmitList[nXmitPackets++] = p;
5903 /* xmitList now hold pointers to all of the packets that are
5904 * ready to send. Now we loop to send the packets */
5905 if (nXmitPackets > 0) {
5906 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
5910 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5912 * TQ references no longer protected by this flag; they must remain
5913 * protected by the global lock.
5915 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5916 call->flags &= ~RX_CALL_TQ_BUSY;
5917 rxi_WakeUpTransmitQueue(call);
5921 /* We went into the error state while sending packets. Now is
5922 * the time to reset the call. This will also inform the using
5923 * process that the call is in an error state.
5925 if (rx_stats_active)
5926 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
5927 call->flags &= ~RX_CALL_TQ_BUSY;
5928 rxi_WakeUpTransmitQueue(call);
5929 rxi_CallError(call, call->error);
5932 #ifdef RX_ENABLE_LOCKS
5933 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5935 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5936 /* Some packets have received acks. If they all have, we can clear
5937 * the transmit queue.
5940 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5941 if (p->header.seq < call->tfirst
5942 && (p->flags & RX_PKTFLAG_ACKED)) {
5944 #ifdef RX_TRACK_PACKETS
5945 p->flags &= ~RX_PKTFLAG_TQ;
5947 #ifdef RXDEBUG_PACKET
5955 call->flags |= RX_CALL_TQ_CLEARME;
5957 #endif /* RX_ENABLE_LOCKS */
5958 /* Don't bother doing retransmits if the TQ is cleared. */
5959 if (call->flags & RX_CALL_TQ_CLEARME) {
5960 rxi_ClearTransmitQueue(call, 1);
5962 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5965 /* Always post a resend event, if there is anything in the
5966 * queue, and resend is possible. There should be at least
5967 * one unacknowledged packet in the queue ... otherwise none
5968 * of these packets should be on the queue in the first place.
5970 if (call->resendEvent) {
5971 /* Cancel the existing event and post a new one */
5972 rxevent_Cancel(call->resendEvent, call,
5973 RX_CALL_REFCOUNT_RESEND);
5976 /* The retry time is the retry time on the first unacknowledged
5977 * packet inside the current window */
5979 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5980 /* Don't set timers for packets outside the window */
5981 if (p->header.seq >= call->tfirst + call->twind) {
5985 if (!(p->flags & RX_PKTFLAG_ACKED)
5986 && !clock_IsZero(&p->retryTime)) {
5988 retryTime = p->retryTime;
5993 /* Post a new event to re-run rxi_Start when retries may be needed */
5994 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5995 #ifdef RX_ENABLE_LOCKS
5996 MUTEX_ENTER(&rx_refcnt_mutex);
5997 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5998 MUTEX_EXIT(&rx_refcnt_mutex);
6000 rxevent_PostNow2(&retryTime, &usenow,
6002 (void *)call, 0, istack);
6003 #else /* RX_ENABLE_LOCKS */
6005 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
6006 (void *)call, 0, istack);
6007 #endif /* RX_ENABLE_LOCKS */
6010 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6011 } while (call->flags & RX_CALL_NEED_START);
6013 * TQ references no longer protected by this flag; they must remain
6014 * protected by the global lock.
6016 call->flags &= ~RX_CALL_TQ_BUSY;
6017 rxi_WakeUpTransmitQueue(call);
6019 call->flags |= RX_CALL_NEED_START;
6021 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6023 if (call->resendEvent) {
6024 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6029 /* Also adjusts the keep alive parameters for the call, to reflect
6030 * that we have just sent a packet (so keep alives aren't sent
6033 rxi_Send(struct rx_call *call, struct rx_packet *p,
6036 struct rx_connection *conn = call->conn;
6038 /* Stamp each packet with the user supplied status */
6039 p->header.userStatus = call->localStatus;
6041 /* Allow the security object controlling this call's security to
6042 * make any last-minute changes to the packet */
6043 RXS_SendPacket(conn->securityObject, call, p);
6045 /* Since we're about to send SOME sort of packet to the peer, it's
6046 * safe to nuke any scheduled end-of-packets ack */
6047 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6049 /* Actually send the packet, filling in more connection-specific fields */
6050 MUTEX_EXIT(&call->lock);
6051 MUTEX_ENTER(&rx_refcnt_mutex);
6052 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6053 MUTEX_EXIT(&rx_refcnt_mutex);
6054 rxi_SendPacket(call, conn, p, istack);
6055 MUTEX_ENTER(&rx_refcnt_mutex);
6056 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6057 MUTEX_EXIT(&rx_refcnt_mutex);
6058 MUTEX_ENTER(&call->lock);
6060 /* Update last send time for this call (for keep-alive
6061 * processing), and for the connection (so that we can discover
6062 * idle connections) */
6063 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6064 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6065 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6067 conn->lastSendTime = call->lastSendTime = clock_Sec();
6068 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6069 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6070 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6071 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6072 RX_ACK_PING_RESPONSE)))
6073 call->lastSendData = call->lastSendTime;
6077 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6078 * that things are fine. Also called periodically to guarantee that nothing
6079 * falls through the cracks (e.g. (error + dally) connections have keepalive
6080 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6082 * haveCTLock Set if calling from rxi_ReapConnections
6084 #ifdef RX_ENABLE_LOCKS
6086 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6087 #else /* RX_ENABLE_LOCKS */
6089 rxi_CheckCall(struct rx_call *call)
6090 #endif /* RX_ENABLE_LOCKS */
6092 struct rx_connection *conn = call->conn;
6094 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6095 afs_uint32 fudgeFactor;
6099 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6100 if (call->flags & RX_CALL_TQ_BUSY) {
6101 /* Call is active and will be reset by rxi_Start if it's
6102 * in an error state.
6107 /* RTT + 8*MDEV, rounded up to the next second. */
6108 fudgeFactor = (((afs_uint32) conn->peer->rtt >> 3) +
6109 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
6111 deadTime = conn->secondsUntilDead + fudgeFactor;
6113 /* These are computed to the second (+- 1 second). But that's
6114 * good enough for these values, which should be a significant
6115 * number of seconds. */
6116 if (now > (call->lastReceiveTime + deadTime)) {
6117 if (call->state == RX_STATE_ACTIVE) {
6119 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
6121 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6122 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6123 ip_stack_t *ipst = ns->netstack_ip;
6125 ire = ire_cache_lookup(conn->peer->host
6126 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6128 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6130 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6137 if (ire && ire->ire_max_frag > 0)
6138 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6140 #if defined(GLOBAL_NETSTACKID)
6144 #endif /* ADAPT_PMTU */
6145 cerror = RX_CALL_DEAD;
6148 #ifdef RX_ENABLE_LOCKS
6149 /* Cancel pending events */
6150 rxevent_Cancel(call->delayedAckEvent, call,
6151 RX_CALL_REFCOUNT_DELAY);
6152 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6153 rxevent_Cancel(call->keepAliveEvent, call,
6154 RX_CALL_REFCOUNT_ALIVE);
6155 MUTEX_ENTER(&rx_refcnt_mutex);
6156 if (call->refCount == 0) {
6157 rxi_FreeCall(call, haveCTLock);
6158 MUTEX_EXIT(&rx_refcnt_mutex);
6161 MUTEX_EXIT(&rx_refcnt_mutex);
6163 #else /* RX_ENABLE_LOCKS */
6164 rxi_FreeCall(call, 0);
6166 #endif /* RX_ENABLE_LOCKS */
6168 /* Non-active calls are destroyed if they are not responding
6169 * to pings; active calls are simply flagged in error, so the
6170 * attached process can die reasonably gracefully. */
6173 if (conn->idleDeadTime) {
6174 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6177 /* see if we have a non-activity timeout */
6178 if (call->startWait && idleDeadTime
6179 && ((call->startWait + idleDeadTime) < now) &&
6180 (call->flags & RX_CALL_READER_WAIT)) {
6181 if (call->state == RX_STATE_ACTIVE) {
6182 cerror = RX_CALL_TIMEOUT;
6186 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6187 && ((call->lastSendData + idleDeadTime) < now)) {
6188 if (call->state == RX_STATE_ACTIVE) {
6189 cerror = conn->idleDeadErr;
6194 if (conn->hardDeadTime) {
6195 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6198 /* see if we have a hard timeout */
6200 && (now > (hardDeadTime + call->startTime.sec))) {
6201 if (call->state == RX_STATE_ACTIVE)
6202 rxi_CallError(call, RX_CALL_TIMEOUT);
6207 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6208 && call->lastReceiveTime) {
6209 int oldMTU = conn->peer->ifMTU;
6211 /* if we thought we could send more, perhaps things got worse */
6212 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6213 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6214 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6215 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6217 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6219 /* minimum capped in SetPeerMtu */
6220 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6223 conn->lastPacketSize = 0;
6225 /* needed so ResetCall doesn't clobber us. */
6226 call->MTU = conn->peer->ifMTU;
6228 /* if we never succeeded, let the error pass out as-is */
6229 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6230 cerror = conn->msgsizeRetryErr;
6233 rxi_CallError(call, cerror);
6238 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6240 struct rx_connection *conn = arg1;
6241 struct rx_header theader;
6242 char tbuffer[1 + sizeof(struct rx_header)];
6243 struct sockaddr_in taddr;
6246 struct iovec tmpiov[2];
6249 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6252 tp = &tbuffer[sizeof(struct rx_header)];
6253 taddr.sin_family = AF_INET;
6254 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6255 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6256 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6257 taddr.sin_len = sizeof(struct sockaddr_in);
6259 memset(&theader, 0, sizeof(theader));
6260 theader.epoch = htonl(999);
6262 theader.callNumber = 0;
6265 theader.type = RX_PACKET_TYPE_VERSION;
6266 theader.flags = RX_LAST_PACKET;
6267 theader.serviceId = 0;
6269 memcpy(tbuffer, &theader, sizeof(theader));
6270 memcpy(tp, &a, sizeof(a));
6271 tmpiov[0].iov_base = tbuffer;
6272 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6274 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6276 MUTEX_ENTER(&conn->conn_data_lock);
6277 MUTEX_ENTER(&rx_refcnt_mutex);
6278 /* Only reschedule ourselves if the connection would not be destroyed */
6279 if (conn->refCount <= 1) {
6280 conn->natKeepAliveEvent = NULL;
6281 MUTEX_EXIT(&rx_refcnt_mutex);
6282 MUTEX_EXIT(&conn->conn_data_lock);
6283 rx_DestroyConnection(conn); /* drop the reference for this */
6285 conn->refCount--; /* drop the reference for this */
6286 MUTEX_EXIT(&rx_refcnt_mutex);
6287 conn->natKeepAliveEvent = NULL;
6288 rxi_ScheduleNatKeepAliveEvent(conn);
6289 MUTEX_EXIT(&conn->conn_data_lock);
6294 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6296 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6297 struct clock when, now;
6298 clock_GetTime(&now);
6300 when.sec += conn->secondsUntilNatPing;
6301 MUTEX_ENTER(&rx_refcnt_mutex);
6302 conn->refCount++; /* hold a reference for this */
6303 MUTEX_EXIT(&rx_refcnt_mutex);
6304 conn->natKeepAliveEvent =
6305 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6310 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6312 MUTEX_ENTER(&conn->conn_data_lock);
6313 conn->secondsUntilNatPing = seconds;
6315 rxi_ScheduleNatKeepAliveEvent(conn);
6316 MUTEX_EXIT(&conn->conn_data_lock);
6320 rxi_NatKeepAliveOn(struct rx_connection *conn)
6322 MUTEX_ENTER(&conn->conn_data_lock);
6323 rxi_ScheduleNatKeepAliveEvent(conn);
6324 MUTEX_EXIT(&conn->conn_data_lock);
6327 /* When a call is in progress, this routine is called occasionally to
6328 * make sure that some traffic has arrived (or been sent to) the peer.
6329 * If nothing has arrived in a reasonable amount of time, the call is
6330 * declared dead; if nothing has been sent for a while, we send a
6331 * keep-alive packet (if we're actually trying to keep the call alive)
6334 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6336 struct rx_call *call = arg1;
6337 struct rx_connection *conn;
6340 MUTEX_ENTER(&rx_refcnt_mutex);
6341 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6342 MUTEX_EXIT(&rx_refcnt_mutex);
6343 MUTEX_ENTER(&call->lock);
6344 if (event == call->keepAliveEvent)
6345 call->keepAliveEvent = NULL;
6348 #ifdef RX_ENABLE_LOCKS
6349 if (rxi_CheckCall(call, 0)) {
6350 MUTEX_EXIT(&call->lock);
6353 #else /* RX_ENABLE_LOCKS */
6354 if (rxi_CheckCall(call))
6356 #endif /* RX_ENABLE_LOCKS */
6358 /* Don't try to keep alive dallying calls */
6359 if (call->state == RX_STATE_DALLY) {
6360 MUTEX_EXIT(&call->lock);
6365 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6366 /* Don't try to send keepalives if there is unacknowledged data */
6367 /* the rexmit code should be good enough, this little hack
6368 * doesn't quite work XXX */
6369 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6371 rxi_ScheduleKeepAliveEvent(call);
6372 MUTEX_EXIT(&call->lock);
6375 /* Does what's on the nameplate. */
6377 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6379 struct rx_call *call = arg1;
6380 struct rx_connection *conn;
6382 MUTEX_ENTER(&rx_refcnt_mutex);
6383 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6384 MUTEX_EXIT(&rx_refcnt_mutex);
6385 MUTEX_ENTER(&call->lock);
6387 if (event == call->growMTUEvent)
6388 call->growMTUEvent = NULL;
6390 #ifdef RX_ENABLE_LOCKS
6391 if (rxi_CheckCall(call, 0)) {
6392 MUTEX_EXIT(&call->lock);
6395 #else /* RX_ENABLE_LOCKS */
6396 if (rxi_CheckCall(call))
6398 #endif /* RX_ENABLE_LOCKS */
6400 /* Don't bother with dallying calls */
6401 if (call->state == RX_STATE_DALLY) {
6402 MUTEX_EXIT(&call->lock);
6409 * keep being scheduled, just don't do anything if we're at peak,
6410 * or we're not set up to be properly handled (idle timeout required)
6412 if ((conn->peer->maxPacketSize != 0) &&
6413 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6414 (conn->idleDeadErr))
6415 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6416 rxi_ScheduleGrowMTUEvent(call, 0);
6417 MUTEX_EXIT(&call->lock);
6421 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6423 if (!call->keepAliveEvent) {
6424 struct clock when, now;
6425 clock_GetTime(&now);
6427 when.sec += call->conn->secondsUntilPing;
6428 MUTEX_ENTER(&rx_refcnt_mutex);
6429 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6430 MUTEX_EXIT(&rx_refcnt_mutex);
6431 call->keepAliveEvent =
6432 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6437 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6439 if (!call->growMTUEvent) {
6440 struct clock when, now;
6442 clock_GetTime(&now);
6445 if (call->conn->secondsUntilPing)
6446 secs = (6*call->conn->secondsUntilPing)-1;
6448 if (call->conn->secondsUntilDead)
6449 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6453 MUTEX_ENTER(&rx_refcnt_mutex);
6454 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6455 MUTEX_EXIT(&rx_refcnt_mutex);
6456 call->growMTUEvent =
6457 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6461 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6463 rxi_KeepAliveOn(struct rx_call *call)
6465 /* Pretend last packet received was received now--i.e. if another
6466 * packet isn't received within the keep alive time, then the call
6467 * will die; Initialize last send time to the current time--even
6468 * if a packet hasn't been sent yet. This will guarantee that a
6469 * keep-alive is sent within the ping time */
6470 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6471 rxi_ScheduleKeepAliveEvent(call);
6475 rxi_GrowMTUOn(struct rx_call *call)
6477 struct rx_connection *conn = call->conn;
6478 MUTEX_ENTER(&conn->conn_data_lock);
6479 conn->lastPingSizeSer = conn->lastPingSize = 0;
6480 MUTEX_EXIT(&conn->conn_data_lock);
6481 rxi_ScheduleGrowMTUEvent(call, 1);
6484 /* This routine is called to send connection abort messages
6485 * that have been delayed to throttle looping clients. */
6487 rxi_SendDelayedConnAbort(struct rxevent *event,
6488 void *arg1, void *unused)
6490 struct rx_connection *conn = arg1;
6493 struct rx_packet *packet;
6495 MUTEX_ENTER(&conn->conn_data_lock);
6496 conn->delayedAbortEvent = NULL;
6497 error = htonl(conn->error);
6499 MUTEX_EXIT(&conn->conn_data_lock);
6500 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6503 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6504 RX_PACKET_TYPE_ABORT, (char *)&error,
6506 rxi_FreePacket(packet);
6510 /* This routine is called to send call abort messages
6511 * that have been delayed to throttle looping clients. */
6513 rxi_SendDelayedCallAbort(struct rxevent *event,
6514 void *arg1, void *dummy)
6516 struct rx_call *call = arg1;
6519 struct rx_packet *packet;
6521 MUTEX_ENTER(&call->lock);
6522 call->delayedAbortEvent = NULL;
6523 error = htonl(call->error);
6525 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6528 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6529 (char *)&error, sizeof(error), 0);
6530 rxi_FreePacket(packet);
6532 MUTEX_EXIT(&call->lock);
6533 MUTEX_ENTER(&rx_refcnt_mutex);
6534 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6535 MUTEX_EXIT(&rx_refcnt_mutex);
6538 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6539 * seconds) to ask the client to authenticate itself. The routine
6540 * issues a challenge to the client, which is obtained from the
6541 * security object associated with the connection */
6543 rxi_ChallengeEvent(struct rxevent *event,
6544 void *arg0, void *arg1, int tries)
6546 struct rx_connection *conn = arg0;
6548 conn->challengeEvent = NULL;
6549 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6550 struct rx_packet *packet;
6551 struct clock when, now;
6554 /* We've failed to authenticate for too long.
6555 * Reset any calls waiting for authentication;
6556 * they are all in RX_STATE_PRECALL.
6560 MUTEX_ENTER(&conn->conn_call_lock);
6561 for (i = 0; i < RX_MAXCALLS; i++) {
6562 struct rx_call *call = conn->call[i];
6564 MUTEX_ENTER(&call->lock);
6565 if (call->state == RX_STATE_PRECALL) {
6566 rxi_CallError(call, RX_CALL_DEAD);
6567 rxi_SendCallAbort(call, NULL, 0, 0);
6569 MUTEX_EXIT(&call->lock);
6572 MUTEX_EXIT(&conn->conn_call_lock);
6576 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6578 /* If there's no packet available, do this later. */
6579 RXS_GetChallenge(conn->securityObject, conn, packet);
6580 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6581 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6582 rxi_FreePacket(packet);
6584 clock_GetTime(&now);
6586 when.sec += RX_CHALLENGE_TIMEOUT;
6587 conn->challengeEvent =
6588 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6593 /* Call this routine to start requesting the client to authenticate
6594 * itself. This will continue until authentication is established,
6595 * the call times out, or an invalid response is returned. The
6596 * security object associated with the connection is asked to create
6597 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6598 * defined earlier. */
6600 rxi_ChallengeOn(struct rx_connection *conn)
6602 if (!conn->challengeEvent) {
6603 RXS_CreateChallenge(conn->securityObject, conn);
6604 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6609 /* rxi_ComputeRoundTripTime is called with peer locked. */
6610 /* peer may be null */
6612 rxi_ComputeRoundTripTime(struct rx_packet *p,
6613 struct rx_ackPacket *ack,
6614 struct rx_peer *peer,
6617 struct clock thisRtt, *sentp;
6621 /* If the ACK is delayed, then do nothing */
6622 if (ack->reason == RX_ACK_DELAY)
6625 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6626 * their RTT multiple times, so only include the RTT of the last packet
6628 if (p->flags & RX_JUMBO_PACKET)
6631 /* Use the serial number to determine which transmission the ACK is for,
6632 * and set the sent time to match this. If we have no serial number, then
6633 * only use the ACK for RTT calculations if the packet has not been
6637 serial = ntohl(ack->serial);
6639 if (serial == p->header.serial) {
6640 sentp = &p->timeSent;
6641 } else if (serial == p->firstSerial) {
6642 sentp = &p->firstSent;
6643 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6644 sentp = &p->firstSent;
6648 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6649 sentp = &p->firstSent;
6656 if (clock_Lt(&thisRtt, sentp))
6657 return; /* somebody set the clock back, don't count this time. */
6659 clock_Sub(&thisRtt, sentp);
6660 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6661 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6663 if (clock_IsZero(&thisRtt)) {
6665 * The actual round trip time is shorter than the
6666 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6667 * Since we can't tell which at the moment we will assume 1ms.
6669 thisRtt.usec = 1000;
6672 if (rx_stats_active) {
6673 MUTEX_ENTER(&rx_stats_mutex);
6674 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6675 rx_stats.minRtt = thisRtt;
6676 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6677 if (thisRtt.sec > 60) {
6678 MUTEX_EXIT(&rx_stats_mutex);
6679 return; /* somebody set the clock ahead */
6681 rx_stats.maxRtt = thisRtt;
6683 clock_Add(&rx_stats.totalRtt, &thisRtt);
6684 rx_atomic_inc(&rx_stats.nRttSamples);
6685 MUTEX_EXIT(&rx_stats_mutex);
6688 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6690 /* Apply VanJacobson round-trip estimations */
6695 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6696 * srtt is stored as fixed point with 3 bits after the binary
6697 * point (i.e., scaled by 8). The following magic is
6698 * equivalent to the smoothing algorithm in rfc793 with an
6699 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6700 * srtt'*8 = rtt + srtt*7
6701 * srtt'*8 = srtt*8 + rtt - srtt
6702 * srtt' = srtt + rtt/8 - srtt/8
6703 * srtt' = srtt + (rtt - srtt)/8
6706 delta = _8THMSEC(&thisRtt) - peer->rtt;
6707 peer->rtt += (delta >> 3);
6710 * We accumulate a smoothed rtt variance (actually, a smoothed
6711 * mean difference), then set the retransmit timer to smoothed
6712 * rtt + 4 times the smoothed variance (was 2x in van's original
6713 * paper, but 4x works better for me, and apparently for him as
6715 * rttvar is stored as
6716 * fixed point with 2 bits after the binary point (scaled by
6717 * 4). The following is equivalent to rfc793 smoothing with
6718 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6719 * rttvar'*4 = rttvar*3 + |delta|
6720 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6721 * rttvar' = rttvar + |delta|/4 - rttvar/4
6722 * rttvar' = rttvar + (|delta| - rttvar)/4
6723 * This replaces rfc793's wired-in beta.
6724 * dev*4 = dev*4 + (|actual - expected| - dev)
6730 delta -= (peer->rtt_dev << 1);
6731 peer->rtt_dev += (delta >> 3);
6733 /* I don't have a stored RTT so I start with this value. Since I'm
6734 * probably just starting a call, and will be pushing more data down
6735 * this, I expect congestion to increase rapidly. So I fudge a
6736 * little, and I set deviance to half the rtt. In practice,
6737 * deviance tends to approach something a little less than
6738 * half the smoothed rtt. */
6739 peer->rtt = _8THMSEC(&thisRtt) + 8;
6740 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6742 /* the timeout is RTT + 4*MDEV + rx_minPeerTimeout msec.
6743 * This is because one end or the other of these connections is usually
6744 * in a user process, and can be switched and/or swapped out. So on fast,
6745 * reliable networks, the timeout would otherwise be too short. */
6746 rtt_timeout = ((peer->rtt >> 3) + peer->rtt_dev) + rx_minPeerTimeout;
6747 clock_Zero(&(peer->timeout));
6748 clock_Addmsec(&(peer->timeout), rtt_timeout);
6750 /* Reset the backedOff flag since we just computed a new timeout value */
6751 peer->backedOff = 0;
6753 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6754 p->header.callNumber, p, MSEC(&thisRtt), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6758 /* Find all server connections that have not been active for a long time, and
6761 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6763 struct clock now, when;
6764 clock_GetTime(&now);
6766 /* Find server connection structures that haven't been used for
6767 * greater than rx_idleConnectionTime */
6769 struct rx_connection **conn_ptr, **conn_end;
6770 int i, havecalls = 0;
6771 MUTEX_ENTER(&rx_connHashTable_lock);
6772 for (conn_ptr = &rx_connHashTable[0], conn_end =
6773 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6775 struct rx_connection *conn, *next;
6776 struct rx_call *call;
6780 for (conn = *conn_ptr; conn; conn = next) {
6781 /* XXX -- Shouldn't the connection be locked? */
6784 for (i = 0; i < RX_MAXCALLS; i++) {
6785 call = conn->call[i];
6789 code = MUTEX_TRYENTER(&call->lock);
6792 #ifdef RX_ENABLE_LOCKS
6793 result = rxi_CheckCall(call, 1);
6794 #else /* RX_ENABLE_LOCKS */
6795 result = rxi_CheckCall(call);
6796 #endif /* RX_ENABLE_LOCKS */
6797 MUTEX_EXIT(&call->lock);
6799 /* If CheckCall freed the call, it might
6800 * have destroyed the connection as well,
6801 * which screws up the linked lists.
6807 if (conn->type == RX_SERVER_CONNECTION) {
6808 /* This only actually destroys the connection if
6809 * there are no outstanding calls */
6810 MUTEX_ENTER(&conn->conn_data_lock);
6811 MUTEX_ENTER(&rx_refcnt_mutex);
6812 if (!havecalls && !conn->refCount
6813 && ((conn->lastSendTime + rx_idleConnectionTime) <
6815 conn->refCount++; /* it will be decr in rx_DestroyConn */
6816 MUTEX_EXIT(&rx_refcnt_mutex);
6817 MUTEX_EXIT(&conn->conn_data_lock);
6818 #ifdef RX_ENABLE_LOCKS
6819 rxi_DestroyConnectionNoLock(conn);
6820 #else /* RX_ENABLE_LOCKS */
6821 rxi_DestroyConnection(conn);
6822 #endif /* RX_ENABLE_LOCKS */
6824 #ifdef RX_ENABLE_LOCKS
6826 MUTEX_EXIT(&rx_refcnt_mutex);
6827 MUTEX_EXIT(&conn->conn_data_lock);
6829 #endif /* RX_ENABLE_LOCKS */
6833 #ifdef RX_ENABLE_LOCKS
6834 while (rx_connCleanup_list) {
6835 struct rx_connection *conn;
6836 conn = rx_connCleanup_list;
6837 rx_connCleanup_list = rx_connCleanup_list->next;
6838 MUTEX_EXIT(&rx_connHashTable_lock);
6839 rxi_CleanupConnection(conn);
6840 MUTEX_ENTER(&rx_connHashTable_lock);
6842 MUTEX_EXIT(&rx_connHashTable_lock);
6843 #endif /* RX_ENABLE_LOCKS */
6846 /* Find any peer structures that haven't been used (haven't had an
6847 * associated connection) for greater than rx_idlePeerTime */
6849 struct rx_peer **peer_ptr, **peer_end;
6853 * Why do we need to hold the rx_peerHashTable_lock across
6854 * the incrementing of peer_ptr since the rx_peerHashTable
6855 * array is not changing? We don't.
6857 * By dropping the lock periodically we can permit other
6858 * activities to be performed while a rxi_ReapConnections
6859 * call is in progress. The goal of reap connections
6860 * is to clean up quickly without causing large amounts
6861 * of contention. Therefore, it is important that global
6862 * mutexes not be held for extended periods of time.
6864 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6865 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6867 struct rx_peer *peer, *next, *prev;
6869 MUTEX_ENTER(&rx_peerHashTable_lock);
6870 for (prev = peer = *peer_ptr; peer; peer = next) {
6872 code = MUTEX_TRYENTER(&peer->peer_lock);
6873 if ((code) && (peer->refCount == 0)
6874 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6875 rx_interface_stat_p rpc_stat, nrpc_stat;
6879 * now know that this peer object is one to be
6880 * removed from the hash table. Once it is removed
6881 * it can't be referenced by other threads.
6882 * Lets remove it first and decrement the struct
6883 * nPeerStructs count.
6885 if (peer == *peer_ptr) {
6891 if (rx_stats_active)
6892 rx_atomic_dec(&rx_stats.nPeerStructs);
6895 * Now if we hold references on 'prev' and 'next'
6896 * we can safely drop the rx_peerHashTable_lock
6897 * while we destroy this 'peer' object.
6903 MUTEX_EXIT(&rx_peerHashTable_lock);
6905 MUTEX_EXIT(&peer->peer_lock);
6906 MUTEX_DESTROY(&peer->peer_lock);
6908 (&peer->rpcStats, rpc_stat, nrpc_stat,
6909 rx_interface_stat)) {
6910 unsigned int num_funcs;
6913 queue_Remove(&rpc_stat->queue_header);
6914 queue_Remove(&rpc_stat->all_peers);
6915 num_funcs = rpc_stat->stats[0].func_total;
6917 sizeof(rx_interface_stat_t) +
6918 rpc_stat->stats[0].func_total *
6919 sizeof(rx_function_entry_v1_t);
6921 rxi_Free(rpc_stat, space);
6923 MUTEX_ENTER(&rx_rpc_stats);
6924 rxi_rpc_peer_stat_cnt -= num_funcs;
6925 MUTEX_EXIT(&rx_rpc_stats);
6930 * Regain the rx_peerHashTable_lock and
6931 * decrement the reference count on 'prev'
6934 MUTEX_ENTER(&rx_peerHashTable_lock);
6941 MUTEX_EXIT(&peer->peer_lock);
6946 MUTEX_EXIT(&rx_peerHashTable_lock);
6950 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6951 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6952 * GC, just below. Really, we shouldn't have to keep moving packets from
6953 * one place to another, but instead ought to always know if we can
6954 * afford to hold onto a packet in its particular use. */
6955 MUTEX_ENTER(&rx_freePktQ_lock);
6956 if (rx_waitingForPackets) {
6957 rx_waitingForPackets = 0;
6958 #ifdef RX_ENABLE_LOCKS
6959 CV_BROADCAST(&rx_waitingForPackets_cv);
6961 osi_rxWakeup(&rx_waitingForPackets);
6964 MUTEX_EXIT(&rx_freePktQ_lock);
6967 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6968 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6972 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6973 * rx.h is sort of strange this is better. This is called with a security
6974 * object before it is discarded. Each connection using a security object has
6975 * its own refcount to the object so it won't actually be freed until the last
6976 * connection is destroyed.
6978 * This is the only rxs module call. A hold could also be written but no one
6982 rxs_Release(struct rx_securityClass *aobj)
6984 return RXS_Close(aobj);
6988 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6989 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6990 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6991 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6993 /* Adjust our estimate of the transmission rate to this peer, given
6994 * that the packet p was just acked. We can adjust peer->timeout and
6995 * call->twind. Pragmatically, this is called
6996 * only with packets of maximal length.
6997 * Called with peer and call locked.
7001 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
7002 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
7004 afs_int32 xferSize, xferMs;
7008 /* Count down packets */
7009 if (peer->rateFlag > 0)
7011 /* Do nothing until we're enabled */
7012 if (peer->rateFlag != 0)
7017 /* Count only when the ack seems legitimate */
7018 switch (ackReason) {
7019 case RX_ACK_REQUESTED:
7021 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
7025 case RX_ACK_PING_RESPONSE:
7026 if (p) /* want the response to ping-request, not data send */
7028 clock_GetTime(&newTO);
7029 if (clock_Gt(&newTO, &call->pingRequestTime)) {
7030 clock_Sub(&newTO, &call->pingRequestTime);
7031 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
7035 xferSize = rx_AckDataSize(rx_maxSendWindow) + RX_HEADER_SIZE;
7042 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)\n",
7043 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
7044 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
7046 /* Track only packets that are big enough. */
7047 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
7051 /* absorb RTT data (in milliseconds) for these big packets */
7052 if (peer->smRtt == 0) {
7053 peer->smRtt = xferMs;
7055 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
7060 if (peer->countDown) {
7064 peer->countDown = 10; /* recalculate only every so often */
7066 /* In practice, we can measure only the RTT for full packets,
7067 * because of the way Rx acks the data that it receives. (If it's
7068 * smaller than a full packet, it often gets implicitly acked
7069 * either by the call response (from a server) or by the next call
7070 * (from a client), and either case confuses transmission times
7071 * with processing times.) Therefore, replace the above
7072 * more-sophisticated processing with a simpler version, where the
7073 * smoothed RTT is kept for full-size packets, and the time to
7074 * transmit a windowful of full-size packets is simply RTT *
7075 * windowSize. Again, we take two steps:
7076 - ensure the timeout is large enough for a single packet's RTT;
7077 - ensure that the window is small enough to fit in the desired timeout.*/
7079 /* First, the timeout check. */
7080 minTime = peer->smRtt;
7081 /* Get a reasonable estimate for a timeout period */
7083 newTO.sec = minTime / 1000;
7084 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
7086 /* Increase the timeout period so that we can always do at least
7087 * one packet exchange */
7088 if (clock_Gt(&newTO, &peer->timeout)) {
7090 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u)\n",
7091 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
7092 newTO.sec, newTO.usec, peer->smRtt));
7094 peer->timeout = newTO;
7097 /* Now, get an estimate for the transmit window size. */
7098 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
7099 /* Now, convert to the number of full packets that could fit in a
7100 * reasonable fraction of that interval */
7101 minTime /= (peer->smRtt << 1);
7102 minTime = MAX(minTime, rx_minPeerTimeout);
7103 xferSize = minTime; /* (make a copy) */
7105 /* Now clamp the size to reasonable bounds. */
7108 else if (minTime > rx_maxSendWindow)
7109 minTime = rx_maxSendWindow;
7110 /* if (minTime != peer->maxWindow) {
7111 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u)\n",
7112 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
7113 peer->timeout.sec, peer->timeout.usec, peer->smRtt));
7114 peer->maxWindow = minTime;
7115 elide... call->twind = minTime;
7119 /* Cut back on the peer timeout if it had earlier grown unreasonably.
7120 * Discern this by calculating the timeout necessary for rx_Window
7122 if ((xferSize > rx_maxSendWindow) && (peer->timeout.sec >= 3)) {
7123 /* calculate estimate for transmission interval in milliseconds */
7124 minTime = rx_maxSendWindow * peer->smRtt;
7125 if (minTime < 1000) {
7126 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u)\n",
7127 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
7128 peer->timeout.usec, peer->smRtt));
7130 newTO.sec = 0; /* cut back on timeout by half a second */
7131 newTO.usec = 500000;
7132 clock_Sub(&peer->timeout, &newTO);
7137 } /* end of rxi_ComputeRate */
7138 #endif /* ADAPT_WINDOW */
7146 #define TRACE_OPTION_RX_DEBUG 16
7154 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7155 0, KEY_QUERY_VALUE, &parmKey);
7156 if (code != ERROR_SUCCESS)
7159 dummyLen = sizeof(TraceOption);
7160 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7161 (BYTE *) &TraceOption, &dummyLen);
7162 if (code == ERROR_SUCCESS) {
7163 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7165 RegCloseKey (parmKey);
7166 #endif /* AFS_NT40_ENV */
7171 rx_DebugOnOff(int on)
7175 rxdebug_active = on;
7181 rx_StatsOnOff(int on)
7183 rx_stats_active = on;
7187 /* Don't call this debugging routine directly; use dpf */
7189 rxi_DebugPrint(char *format, ...)
7198 va_start(ap, format);
7200 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7203 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7205 OutputDebugString(msg);
7211 va_start(ap, format);
7213 clock_GetTime(&now);
7214 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7215 (unsigned int)now.usec);
7216 vfprintf(rx_Log, format, ap);
7224 * This function is used to process the rx_stats structure that is local
7225 * to a process as well as an rx_stats structure received from a remote
7226 * process (via rxdebug). Therefore, it needs to do minimal version
7230 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7231 afs_int32 freePackets, char version)
7235 if (size != sizeof(struct rx_statistics)) {
7237 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7238 size, sizeof(struct rx_statistics));
7241 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7244 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7245 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7246 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7247 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7248 s->specialPktAllocFailures);
7250 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7251 s->receivePktAllocFailures, s->sendPktAllocFailures,
7252 s->specialPktAllocFailures);
7256 " greedy %u, " "bogusReads %u (last from host %x), "
7257 "noPackets %u, " "noBuffers %u, " "selects %u, "
7258 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7259 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7260 s->selects, s->sendSelects);
7262 fprintf(file, " packets read: ");
7263 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7264 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7266 fprintf(file, "\n");
7269 " other read counters: data %u, " "ack %u, " "dup %u "
7270 "spurious %u " "dally %u\n", s->dataPacketsRead,
7271 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7272 s->ignorePacketDally);
7274 fprintf(file, " packets sent: ");
7275 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7276 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7278 fprintf(file, "\n");
7281 " other send counters: ack %u, " "data %u (not resends), "
7282 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7283 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7284 s->dataPacketsPushed, s->ignoreAckedPacket);
7287 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7288 s->netSendFailures, (int)s->fatalErrors);
7290 if (s->nRttSamples) {
7291 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7292 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7294 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7295 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7299 " %d server connections, " "%d client connections, "
7300 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7301 s->nServerConns, s->nClientConns, s->nPeerStructs,
7302 s->nCallStructs, s->nFreeCallStructs);
7304 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7305 fprintf(file, " %d clock updates\n", clock_nUpdates);
7309 /* for backward compatibility */
7311 rx_PrintStats(FILE * file)
7313 MUTEX_ENTER(&rx_stats_mutex);
7314 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7315 sizeof(rx_stats), rx_nFreePackets,
7317 MUTEX_EXIT(&rx_stats_mutex);
7321 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7323 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7324 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7325 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7328 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7329 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7330 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7333 " Packet size %d, " "max in packet skew %d, "
7334 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7335 (int)peer->outPacketSkew);
7339 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7341 * This mutex protects the following static variables:
7345 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7346 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7348 #define LOCK_RX_DEBUG
7349 #define UNLOCK_RX_DEBUG
7350 #endif /* AFS_PTHREAD_ENV */
7352 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7354 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7355 u_char type, void *inputData, size_t inputLength,
7356 void *outputData, size_t outputLength)
7358 static afs_int32 counter = 100;
7359 time_t waitTime, waitCount;
7360 struct rx_header theader;
7363 struct timeval tv_now, tv_wake, tv_delta;
7364 struct sockaddr_in taddr, faddr;
7378 tp = &tbuffer[sizeof(struct rx_header)];
7379 taddr.sin_family = AF_INET;
7380 taddr.sin_port = remotePort;
7381 taddr.sin_addr.s_addr = remoteAddr;
7382 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7383 taddr.sin_len = sizeof(struct sockaddr_in);
7386 memset(&theader, 0, sizeof(theader));
7387 theader.epoch = htonl(999);
7389 theader.callNumber = htonl(counter);
7392 theader.type = type;
7393 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7394 theader.serviceId = 0;
7396 memcpy(tbuffer, &theader, sizeof(theader));
7397 memcpy(tp, inputData, inputLength);
7399 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7400 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7402 /* see if there's a packet available */
7403 gettimeofday(&tv_wake,0);
7404 tv_wake.tv_sec += waitTime;
7407 FD_SET(socket, &imask);
7408 tv_delta.tv_sec = tv_wake.tv_sec;
7409 tv_delta.tv_usec = tv_wake.tv_usec;
7410 gettimeofday(&tv_now, 0);
7412 if (tv_delta.tv_usec < tv_now.tv_usec) {
7414 tv_delta.tv_usec += 1000000;
7417 tv_delta.tv_usec -= tv_now.tv_usec;
7419 if (tv_delta.tv_sec < tv_now.tv_sec) {
7423 tv_delta.tv_sec -= tv_now.tv_sec;
7426 code = select(0, &imask, 0, 0, &tv_delta);
7427 #else /* AFS_NT40_ENV */
7428 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7429 #endif /* AFS_NT40_ENV */
7430 if (code == 1 && FD_ISSET(socket, &imask)) {
7431 /* now receive a packet */
7432 faddrLen = sizeof(struct sockaddr_in);
7434 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7435 (struct sockaddr *)&faddr, &faddrLen);
7438 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7439 if (counter == ntohl(theader.callNumber))
7447 /* see if we've timed out */
7455 code -= sizeof(struct rx_header);
7456 if (code > outputLength)
7457 code = outputLength;
7458 memcpy(outputData, tp, code);
7461 #endif /* RXDEBUG */
7464 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7465 afs_uint16 remotePort, struct rx_debugStats * stat,
7466 afs_uint32 * supportedValues)
7468 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7470 struct rx_debugIn in;
7472 *supportedValues = 0;
7473 in.type = htonl(RX_DEBUGI_GETSTATS);
7476 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7477 &in, sizeof(in), stat, sizeof(*stat));
7480 * If the call was successful, fixup the version and indicate
7481 * what contents of the stat structure are valid.
7482 * Also do net to host conversion of fields here.
7486 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7487 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7489 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7490 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7492 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7493 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7495 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7496 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7498 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7499 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7501 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7502 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7504 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7505 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7507 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7508 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7510 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7511 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7513 stat->nFreePackets = ntohl(stat->nFreePackets);
7514 stat->packetReclaims = ntohl(stat->packetReclaims);
7515 stat->callsExecuted = ntohl(stat->callsExecuted);
7516 stat->nWaiting = ntohl(stat->nWaiting);
7517 stat->idleThreads = ntohl(stat->idleThreads);
7518 stat->nWaited = ntohl(stat->nWaited);
7519 stat->nPackets = ntohl(stat->nPackets);
7528 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7529 afs_uint16 remotePort, struct rx_statistics * stat,
7530 afs_uint32 * supportedValues)
7532 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7534 struct rx_debugIn in;
7535 afs_int32 *lp = (afs_int32 *) stat;
7539 * supportedValues is currently unused, but added to allow future
7540 * versioning of this function.
7543 *supportedValues = 0;
7544 in.type = htonl(RX_DEBUGI_RXSTATS);
7546 memset(stat, 0, sizeof(*stat));
7548 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7549 &in, sizeof(in), stat, sizeof(*stat));
7554 * Do net to host conversion here
7557 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7568 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7569 afs_uint16 remotePort, size_t version_length,
7572 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7574 return MakeDebugCall(socket, remoteAddr, remotePort,
7575 RX_PACKET_TYPE_VERSION, a, 1, version,
7583 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7584 afs_uint16 remotePort, afs_int32 * nextConnection,
7585 int allConnections, afs_uint32 debugSupportedValues,
7586 struct rx_debugConn * conn,
7587 afs_uint32 * supportedValues)
7589 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7591 struct rx_debugIn in;
7595 * supportedValues is currently unused, but added to allow future
7596 * versioning of this function.
7599 *supportedValues = 0;
7600 if (allConnections) {
7601 in.type = htonl(RX_DEBUGI_GETALLCONN);
7603 in.type = htonl(RX_DEBUGI_GETCONN);
7605 in.index = htonl(*nextConnection);
7606 memset(conn, 0, sizeof(*conn));
7608 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7609 &in, sizeof(in), conn, sizeof(*conn));
7612 *nextConnection += 1;
7615 * Convert old connection format to new structure.
7618 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7619 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7620 #define MOVEvL(a) (conn->a = vL->a)
7622 /* any old or unrecognized version... */
7623 for (i = 0; i < RX_MAXCALLS; i++) {
7624 MOVEvL(callState[i]);
7625 MOVEvL(callMode[i]);
7626 MOVEvL(callFlags[i]);
7627 MOVEvL(callOther[i]);
7629 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7630 MOVEvL(secStats.type);
7631 MOVEvL(secStats.level);
7632 MOVEvL(secStats.flags);
7633 MOVEvL(secStats.expires);
7634 MOVEvL(secStats.packetsReceived);
7635 MOVEvL(secStats.packetsSent);
7636 MOVEvL(secStats.bytesReceived);
7637 MOVEvL(secStats.bytesSent);
7642 * Do net to host conversion here
7644 * I don't convert host or port since we are most likely
7645 * going to want these in NBO.
7647 conn->cid = ntohl(conn->cid);
7648 conn->serial = ntohl(conn->serial);
7649 for (i = 0; i < RX_MAXCALLS; i++) {
7650 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7652 conn->error = ntohl(conn->error);
7653 conn->secStats.flags = ntohl(conn->secStats.flags);
7654 conn->secStats.expires = ntohl(conn->secStats.expires);
7655 conn->secStats.packetsReceived =
7656 ntohl(conn->secStats.packetsReceived);
7657 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7658 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7659 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7660 conn->epoch = ntohl(conn->epoch);
7661 conn->natMTU = ntohl(conn->natMTU);
7670 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7671 afs_uint16 remotePort, afs_int32 * nextPeer,
7672 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7673 afs_uint32 * supportedValues)
7675 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7677 struct rx_debugIn in;
7680 * supportedValues is currently unused, but added to allow future
7681 * versioning of this function.
7684 *supportedValues = 0;
7685 in.type = htonl(RX_DEBUGI_GETPEER);
7686 in.index = htonl(*nextPeer);
7687 memset(peer, 0, sizeof(*peer));
7689 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7690 &in, sizeof(in), peer, sizeof(*peer));
7696 * Do net to host conversion here
7698 * I don't convert host or port since we are most likely
7699 * going to want these in NBO.
7701 peer->ifMTU = ntohs(peer->ifMTU);
7702 peer->idleWhen = ntohl(peer->idleWhen);
7703 peer->refCount = ntohs(peer->refCount);
7704 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7705 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7706 peer->rtt = ntohl(peer->rtt);
7707 peer->rtt_dev = ntohl(peer->rtt_dev);
7708 peer->timeout.sec = ntohl(peer->timeout.sec);
7709 peer->timeout.usec = ntohl(peer->timeout.usec);
7710 peer->nSent = ntohl(peer->nSent);
7711 peer->reSends = ntohl(peer->reSends);
7712 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7713 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7714 peer->rateFlag = ntohl(peer->rateFlag);
7715 peer->natMTU = ntohs(peer->natMTU);
7716 peer->maxMTU = ntohs(peer->maxMTU);
7717 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7718 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7719 peer->MTU = ntohs(peer->MTU);
7720 peer->cwind = ntohs(peer->cwind);
7721 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7722 peer->congestSeq = ntohs(peer->congestSeq);
7723 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7724 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7725 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7726 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7735 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7736 struct rx_debugPeer * peerStats)
7739 afs_int32 error = 1; /* default to "did not succeed" */
7740 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7742 MUTEX_ENTER(&rx_peerHashTable_lock);
7743 for(tp = rx_peerHashTable[hashValue];
7744 tp != NULL; tp = tp->next) {
7745 if (tp->host == peerHost)
7751 MUTEX_EXIT(&rx_peerHashTable_lock);
7755 MUTEX_ENTER(&tp->peer_lock);
7756 peerStats->host = tp->host;
7757 peerStats->port = tp->port;
7758 peerStats->ifMTU = tp->ifMTU;
7759 peerStats->idleWhen = tp->idleWhen;
7760 peerStats->refCount = tp->refCount;
7761 peerStats->burstSize = tp->burstSize;
7762 peerStats->burst = tp->burst;
7763 peerStats->burstWait.sec = tp->burstWait.sec;
7764 peerStats->burstWait.usec = tp->burstWait.usec;
7765 peerStats->rtt = tp->rtt;
7766 peerStats->rtt_dev = tp->rtt_dev;
7767 peerStats->timeout.sec = tp->timeout.sec;
7768 peerStats->timeout.usec = tp->timeout.usec;
7769 peerStats->nSent = tp->nSent;
7770 peerStats->reSends = tp->reSends;
7771 peerStats->inPacketSkew = tp->inPacketSkew;
7772 peerStats->outPacketSkew = tp->outPacketSkew;
7773 peerStats->rateFlag = tp->rateFlag;
7774 peerStats->natMTU = tp->natMTU;
7775 peerStats->maxMTU = tp->maxMTU;
7776 peerStats->maxDgramPackets = tp->maxDgramPackets;
7777 peerStats->ifDgramPackets = tp->ifDgramPackets;
7778 peerStats->MTU = tp->MTU;
7779 peerStats->cwind = tp->cwind;
7780 peerStats->nDgramPackets = tp->nDgramPackets;
7781 peerStats->congestSeq = tp->congestSeq;
7782 peerStats->bytesSent.high = tp->bytesSent.high;
7783 peerStats->bytesSent.low = tp->bytesSent.low;
7784 peerStats->bytesReceived.high = tp->bytesReceived.high;
7785 peerStats->bytesReceived.low = tp->bytesReceived.low;
7786 MUTEX_EXIT(&tp->peer_lock);
7788 MUTEX_ENTER(&rx_peerHashTable_lock);
7791 MUTEX_EXIT(&rx_peerHashTable_lock);
7799 struct rx_serverQueueEntry *np;
7802 struct rx_call *call;
7803 struct rx_serverQueueEntry *sq;
7807 if (rxinit_status == 1) {
7809 return; /* Already shutdown. */
7813 #ifndef AFS_PTHREAD_ENV
7814 FD_ZERO(&rx_selectMask);
7815 #endif /* AFS_PTHREAD_ENV */
7816 rxi_dataQuota = RX_MAX_QUOTA;
7817 #ifndef AFS_PTHREAD_ENV
7819 #endif /* AFS_PTHREAD_ENV */
7822 #ifndef AFS_PTHREAD_ENV
7823 #ifndef AFS_USE_GETTIMEOFDAY
7825 #endif /* AFS_USE_GETTIMEOFDAY */
7826 #endif /* AFS_PTHREAD_ENV */
7828 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7829 call = queue_First(&rx_freeCallQueue, rx_call);
7831 rxi_Free(call, sizeof(struct rx_call));
7834 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7835 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7841 struct rx_peer **peer_ptr, **peer_end;
7842 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7843 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7845 struct rx_peer *peer, *next;
7847 MUTEX_ENTER(&rx_peerHashTable_lock);
7848 for (peer = *peer_ptr; peer; peer = next) {
7849 rx_interface_stat_p rpc_stat, nrpc_stat;
7852 MUTEX_ENTER(&rx_rpc_stats);
7853 MUTEX_ENTER(&peer->peer_lock);
7855 (&peer->rpcStats, rpc_stat, nrpc_stat,
7856 rx_interface_stat)) {
7857 unsigned int num_funcs;
7860 queue_Remove(&rpc_stat->queue_header);
7861 queue_Remove(&rpc_stat->all_peers);
7862 num_funcs = rpc_stat->stats[0].func_total;
7864 sizeof(rx_interface_stat_t) +
7865 rpc_stat->stats[0].func_total *
7866 sizeof(rx_function_entry_v1_t);
7868 rxi_Free(rpc_stat, space);
7870 /* rx_rpc_stats must be held */
7871 rxi_rpc_peer_stat_cnt -= num_funcs;
7873 MUTEX_EXIT(&peer->peer_lock);
7874 MUTEX_EXIT(&rx_rpc_stats);
7878 if (rx_stats_active)
7879 rx_atomic_dec(&rx_stats.nPeerStructs);
7881 MUTEX_EXIT(&rx_peerHashTable_lock);
7884 for (i = 0; i < RX_MAX_SERVICES; i++) {
7886 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7888 for (i = 0; i < rx_hashTableSize; i++) {
7889 struct rx_connection *tc, *ntc;
7890 MUTEX_ENTER(&rx_connHashTable_lock);
7891 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7893 for (j = 0; j < RX_MAXCALLS; j++) {
7895 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7898 rxi_Free(tc, sizeof(*tc));
7900 MUTEX_EXIT(&rx_connHashTable_lock);
7903 MUTEX_ENTER(&freeSQEList_lock);
7905 while ((np = rx_FreeSQEList)) {
7906 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7907 MUTEX_DESTROY(&np->lock);
7908 rxi_Free(np, sizeof(*np));
7911 MUTEX_EXIT(&freeSQEList_lock);
7912 MUTEX_DESTROY(&freeSQEList_lock);
7913 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7914 MUTEX_DESTROY(&rx_connHashTable_lock);
7915 MUTEX_DESTROY(&rx_peerHashTable_lock);
7916 MUTEX_DESTROY(&rx_serverPool_lock);
7918 osi_Free(rx_connHashTable,
7919 rx_hashTableSize * sizeof(struct rx_connection *));
7920 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7922 UNPIN(rx_connHashTable,
7923 rx_hashTableSize * sizeof(struct rx_connection *));
7924 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7926 rxi_FreeAllPackets();
7928 MUTEX_ENTER(&rx_quota_mutex);
7929 rxi_dataQuota = RX_MAX_QUOTA;
7930 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7931 MUTEX_EXIT(&rx_quota_mutex);
7936 #ifdef RX_ENABLE_LOCKS
7938 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7940 if (!MUTEX_ISMINE(lockaddr))
7941 osi_Panic("Lock not held: %s", msg);
7943 #endif /* RX_ENABLE_LOCKS */
7948 * Routines to implement connection specific data.
7952 rx_KeyCreate(rx_destructor_t rtn)
7955 MUTEX_ENTER(&rxi_keyCreate_lock);
7956 key = rxi_keyCreate_counter++;
7957 rxi_keyCreate_destructor = (rx_destructor_t *)
7958 realloc((void *)rxi_keyCreate_destructor,
7959 (key + 1) * sizeof(rx_destructor_t));
7960 rxi_keyCreate_destructor[key] = rtn;
7961 MUTEX_EXIT(&rxi_keyCreate_lock);
7966 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7969 MUTEX_ENTER(&conn->conn_data_lock);
7970 if (!conn->specific) {
7971 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7972 for (i = 0; i < key; i++)
7973 conn->specific[i] = NULL;
7974 conn->nSpecific = key + 1;
7975 conn->specific[key] = ptr;
7976 } else if (key >= conn->nSpecific) {
7977 conn->specific = (void **)
7978 realloc(conn->specific, (key + 1) * sizeof(void *));
7979 for (i = conn->nSpecific; i < key; i++)
7980 conn->specific[i] = NULL;
7981 conn->nSpecific = key + 1;
7982 conn->specific[key] = ptr;
7984 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7985 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7986 conn->specific[key] = ptr;
7988 MUTEX_EXIT(&conn->conn_data_lock);
7992 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7995 MUTEX_ENTER(&svc->svc_data_lock);
7996 if (!svc->specific) {
7997 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7998 for (i = 0; i < key; i++)
7999 svc->specific[i] = NULL;
8000 svc->nSpecific = key + 1;
8001 svc->specific[key] = ptr;
8002 } else if (key >= svc->nSpecific) {
8003 svc->specific = (void **)
8004 realloc(svc->specific, (key + 1) * sizeof(void *));
8005 for (i = svc->nSpecific; i < key; i++)
8006 svc->specific[i] = NULL;
8007 svc->nSpecific = key + 1;
8008 svc->specific[key] = ptr;
8010 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8011 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8012 svc->specific[key] = ptr;
8014 MUTEX_EXIT(&svc->svc_data_lock);
8018 rx_GetSpecific(struct rx_connection *conn, int key)
8021 MUTEX_ENTER(&conn->conn_data_lock);
8022 if (key >= conn->nSpecific)
8025 ptr = conn->specific[key];
8026 MUTEX_EXIT(&conn->conn_data_lock);
8031 rx_GetServiceSpecific(struct rx_service *svc, int key)
8034 MUTEX_ENTER(&svc->svc_data_lock);
8035 if (key >= svc->nSpecific)
8038 ptr = svc->specific[key];
8039 MUTEX_EXIT(&svc->svc_data_lock);
8044 #endif /* !KERNEL */
8047 * processStats is a queue used to store the statistics for the local
8048 * process. Its contents are similar to the contents of the rpcStats
8049 * queue on a rx_peer structure, but the actual data stored within
8050 * this queue contains totals across the lifetime of the process (assuming
8051 * the stats have not been reset) - unlike the per peer structures
8052 * which can come and go based upon the peer lifetime.
8055 static struct rx_queue processStats = { &processStats, &processStats };
8058 * peerStats is a queue used to store the statistics for all peer structs.
8059 * Its contents are the union of all the peer rpcStats queues.
8062 static struct rx_queue peerStats = { &peerStats, &peerStats };
8065 * rxi_monitor_processStats is used to turn process wide stat collection
8069 static int rxi_monitor_processStats = 0;
8072 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8075 static int rxi_monitor_peerStats = 0;
8078 * rxi_AddRpcStat - given all of the information for a particular rpc
8079 * call, create (if needed) and update the stat totals for the rpc.
8083 * IN stats - the queue of stats that will be updated with the new value
8085 * IN rxInterface - a unique number that identifies the rpc interface
8087 * IN currentFunc - the index of the function being invoked
8089 * IN totalFunc - the total number of functions in this interface
8091 * IN queueTime - the amount of time this function waited for a thread
8093 * IN execTime - the amount of time this function invocation took to execute
8095 * IN bytesSent - the number bytes sent by this invocation
8097 * IN bytesRcvd - the number bytes received by this invocation
8099 * IN isServer - if true, this invocation was made to a server
8101 * IN remoteHost - the ip address of the remote host
8103 * IN remotePort - the port of the remote host
8105 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8107 * INOUT counter - if a new stats structure is allocated, the counter will
8108 * be updated with the new number of allocated stat structures
8116 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8117 afs_uint32 currentFunc, afs_uint32 totalFunc,
8118 struct clock *queueTime, struct clock *execTime,
8119 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8120 afs_uint32 remoteHost, afs_uint32 remotePort,
8121 int addToPeerList, unsigned int *counter)
8124 rx_interface_stat_p rpc_stat, nrpc_stat;
8127 * See if there's already a structure for this interface
8130 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8131 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8132 && (rpc_stat->stats[0].remote_is_server == isServer))
8137 * Didn't find a match so allocate a new structure and add it to the
8141 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8142 || (rpc_stat->stats[0].interfaceId != rxInterface)
8143 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8148 sizeof(rx_interface_stat_t) +
8149 totalFunc * sizeof(rx_function_entry_v1_t);
8151 rpc_stat = rxi_Alloc(space);
8152 if (rpc_stat == NULL) {
8156 *counter += totalFunc;
8157 for (i = 0; i < totalFunc; i++) {
8158 rpc_stat->stats[i].remote_peer = remoteHost;
8159 rpc_stat->stats[i].remote_port = remotePort;
8160 rpc_stat->stats[i].remote_is_server = isServer;
8161 rpc_stat->stats[i].interfaceId = rxInterface;
8162 rpc_stat->stats[i].func_total = totalFunc;
8163 rpc_stat->stats[i].func_index = i;
8164 hzero(rpc_stat->stats[i].invocations);
8165 hzero(rpc_stat->stats[i].bytes_sent);
8166 hzero(rpc_stat->stats[i].bytes_rcvd);
8167 rpc_stat->stats[i].queue_time_sum.sec = 0;
8168 rpc_stat->stats[i].queue_time_sum.usec = 0;
8169 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8170 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8171 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8172 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8173 rpc_stat->stats[i].queue_time_max.sec = 0;
8174 rpc_stat->stats[i].queue_time_max.usec = 0;
8175 rpc_stat->stats[i].execution_time_sum.sec = 0;
8176 rpc_stat->stats[i].execution_time_sum.usec = 0;
8177 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8178 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8179 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8180 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8181 rpc_stat->stats[i].execution_time_max.sec = 0;
8182 rpc_stat->stats[i].execution_time_max.usec = 0;
8184 queue_Prepend(stats, rpc_stat);
8185 if (addToPeerList) {
8186 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8191 * Increment the stats for this function
8194 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8195 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8196 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8197 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8198 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8199 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8200 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8202 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8203 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8205 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8206 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8208 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8209 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8211 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8212 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8220 * rx_IncrementTimeAndCount - increment the times and count for a particular
8225 * IN peer - the peer who invoked the rpc
8227 * IN rxInterface - a unique number that identifies the rpc interface
8229 * IN currentFunc - the index of the function being invoked
8231 * IN totalFunc - the total number of functions in this interface
8233 * IN queueTime - the amount of time this function waited for a thread
8235 * IN execTime - the amount of time this function invocation took to execute
8237 * IN bytesSent - the number bytes sent by this invocation
8239 * IN bytesRcvd - the number bytes received by this invocation
8241 * IN isServer - if true, this invocation was made to a server
8249 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8250 afs_uint32 currentFunc, afs_uint32 totalFunc,
8251 struct clock *queueTime, struct clock *execTime,
8252 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8256 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8259 MUTEX_ENTER(&rx_rpc_stats);
8261 if (rxi_monitor_peerStats) {
8262 MUTEX_ENTER(&peer->peer_lock);
8263 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8264 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8265 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8266 MUTEX_EXIT(&peer->peer_lock);
8269 if (rxi_monitor_processStats) {
8270 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8271 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8272 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8275 MUTEX_EXIT(&rx_rpc_stats);
8280 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8284 * IN callerVersion - the rpc stat version of the caller.
8286 * IN count - the number of entries to marshall.
8288 * IN stats - pointer to stats to be marshalled.
8290 * OUT ptr - Where to store the marshalled data.
8297 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8298 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8304 * We only support the first version
8306 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8307 *(ptr++) = stats->remote_peer;
8308 *(ptr++) = stats->remote_port;
8309 *(ptr++) = stats->remote_is_server;
8310 *(ptr++) = stats->interfaceId;
8311 *(ptr++) = stats->func_total;
8312 *(ptr++) = stats->func_index;
8313 *(ptr++) = hgethi(stats->invocations);
8314 *(ptr++) = hgetlo(stats->invocations);
8315 *(ptr++) = hgethi(stats->bytes_sent);
8316 *(ptr++) = hgetlo(stats->bytes_sent);
8317 *(ptr++) = hgethi(stats->bytes_rcvd);
8318 *(ptr++) = hgetlo(stats->bytes_rcvd);
8319 *(ptr++) = stats->queue_time_sum.sec;
8320 *(ptr++) = stats->queue_time_sum.usec;
8321 *(ptr++) = stats->queue_time_sum_sqr.sec;
8322 *(ptr++) = stats->queue_time_sum_sqr.usec;
8323 *(ptr++) = stats->queue_time_min.sec;
8324 *(ptr++) = stats->queue_time_min.usec;
8325 *(ptr++) = stats->queue_time_max.sec;
8326 *(ptr++) = stats->queue_time_max.usec;
8327 *(ptr++) = stats->execution_time_sum.sec;
8328 *(ptr++) = stats->execution_time_sum.usec;
8329 *(ptr++) = stats->execution_time_sum_sqr.sec;
8330 *(ptr++) = stats->execution_time_sum_sqr.usec;
8331 *(ptr++) = stats->execution_time_min.sec;
8332 *(ptr++) = stats->execution_time_min.usec;
8333 *(ptr++) = stats->execution_time_max.sec;
8334 *(ptr++) = stats->execution_time_max.usec;
8340 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8345 * IN callerVersion - the rpc stat version of the caller
8347 * OUT myVersion - the rpc stat version of this function
8349 * OUT clock_sec - local time seconds
8351 * OUT clock_usec - local time microseconds
8353 * OUT allocSize - the number of bytes allocated to contain stats
8355 * OUT statCount - the number stats retrieved from this process.
8357 * OUT stats - the actual stats retrieved from this process.
8361 * Returns void. If successful, stats will != NULL.
8365 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8366 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8367 size_t * allocSize, afs_uint32 * statCount,
8368 afs_uint32 ** stats)
8378 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8381 * Check to see if stats are enabled
8384 MUTEX_ENTER(&rx_rpc_stats);
8385 if (!rxi_monitor_processStats) {
8386 MUTEX_EXIT(&rx_rpc_stats);
8390 clock_GetTime(&now);
8391 *clock_sec = now.sec;
8392 *clock_usec = now.usec;
8395 * Allocate the space based upon the caller version
8397 * If the client is at an older version than we are,
8398 * we return the statistic data in the older data format, but
8399 * we still return our version number so the client knows we
8400 * are maintaining more data than it can retrieve.
8403 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8404 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8405 *statCount = rxi_rpc_process_stat_cnt;
8408 * This can't happen yet, but in the future version changes
8409 * can be handled by adding additional code here
8413 if (space > (size_t) 0) {
8415 ptr = *stats = rxi_Alloc(space);
8418 rx_interface_stat_p rpc_stat, nrpc_stat;
8422 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8424 * Copy the data based upon the caller version
8426 rx_MarshallProcessRPCStats(callerVersion,
8427 rpc_stat->stats[0].func_total,
8428 rpc_stat->stats, &ptr);
8434 MUTEX_EXIT(&rx_rpc_stats);
8439 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8443 * IN callerVersion - the rpc stat version of the caller
8445 * OUT myVersion - the rpc stat version of this function
8447 * OUT clock_sec - local time seconds
8449 * OUT clock_usec - local time microseconds
8451 * OUT allocSize - the number of bytes allocated to contain stats
8453 * OUT statCount - the number of stats retrieved from the individual
8456 * OUT stats - the actual stats retrieved from the individual peer structures.
8460 * Returns void. If successful, stats will != NULL.
8464 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8465 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8466 size_t * allocSize, afs_uint32 * statCount,
8467 afs_uint32 ** stats)
8477 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8480 * Check to see if stats are enabled
8483 MUTEX_ENTER(&rx_rpc_stats);
8484 if (!rxi_monitor_peerStats) {
8485 MUTEX_EXIT(&rx_rpc_stats);
8489 clock_GetTime(&now);
8490 *clock_sec = now.sec;
8491 *clock_usec = now.usec;
8494 * Allocate the space based upon the caller version
8496 * If the client is at an older version than we are,
8497 * we return the statistic data in the older data format, but
8498 * we still return our version number so the client knows we
8499 * are maintaining more data than it can retrieve.
8502 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8503 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8504 *statCount = rxi_rpc_peer_stat_cnt;
8507 * This can't happen yet, but in the future version changes
8508 * can be handled by adding additional code here
8512 if (space > (size_t) 0) {
8514 ptr = *stats = rxi_Alloc(space);
8517 rx_interface_stat_p rpc_stat, nrpc_stat;
8521 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8523 * We have to fix the offset of rpc_stat since we are
8524 * keeping this structure on two rx_queues. The rx_queue
8525 * package assumes that the rx_queue member is the first
8526 * member of the structure. That is, rx_queue assumes that
8527 * any one item is only on one queue at a time. We are
8528 * breaking that assumption and so we have to do a little
8529 * math to fix our pointers.
8532 fix_offset = (char *)rpc_stat;
8533 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8534 rpc_stat = (rx_interface_stat_p) fix_offset;
8537 * Copy the data based upon the caller version
8539 rx_MarshallProcessRPCStats(callerVersion,
8540 rpc_stat->stats[0].func_total,
8541 rpc_stat->stats, &ptr);
8547 MUTEX_EXIT(&rx_rpc_stats);
8552 * rx_FreeRPCStats - free memory allocated by
8553 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8557 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8558 * rx_RetrievePeerRPCStats
8560 * IN allocSize - the number of bytes in stats.
8568 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8570 rxi_Free(stats, allocSize);
8574 * rx_queryProcessRPCStats - see if process rpc stat collection is
8575 * currently enabled.
8581 * Returns 0 if stats are not enabled != 0 otherwise
8585 rx_queryProcessRPCStats(void)
8588 MUTEX_ENTER(&rx_rpc_stats);
8589 rc = rxi_monitor_processStats;
8590 MUTEX_EXIT(&rx_rpc_stats);
8595 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8601 * Returns 0 if stats are not enabled != 0 otherwise
8605 rx_queryPeerRPCStats(void)
8608 MUTEX_ENTER(&rx_rpc_stats);
8609 rc = rxi_monitor_peerStats;
8610 MUTEX_EXIT(&rx_rpc_stats);
8615 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8625 rx_enableProcessRPCStats(void)
8627 MUTEX_ENTER(&rx_rpc_stats);
8628 rx_enable_stats = 1;
8629 rxi_monitor_processStats = 1;
8630 MUTEX_EXIT(&rx_rpc_stats);
8634 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8644 rx_enablePeerRPCStats(void)
8646 MUTEX_ENTER(&rx_rpc_stats);
8647 rx_enable_stats = 1;
8648 rxi_monitor_peerStats = 1;
8649 MUTEX_EXIT(&rx_rpc_stats);
8653 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8663 rx_disableProcessRPCStats(void)
8665 rx_interface_stat_p rpc_stat, nrpc_stat;
8668 MUTEX_ENTER(&rx_rpc_stats);
8671 * Turn off process statistics and if peer stats is also off, turn
8675 rxi_monitor_processStats = 0;
8676 if (rxi_monitor_peerStats == 0) {
8677 rx_enable_stats = 0;
8680 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8681 unsigned int num_funcs = 0;
8684 queue_Remove(rpc_stat);
8685 num_funcs = rpc_stat->stats[0].func_total;
8687 sizeof(rx_interface_stat_t) +
8688 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8690 rxi_Free(rpc_stat, space);
8691 rxi_rpc_process_stat_cnt -= num_funcs;
8693 MUTEX_EXIT(&rx_rpc_stats);
8697 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8707 rx_disablePeerRPCStats(void)
8709 struct rx_peer **peer_ptr, **peer_end;
8713 * Turn off peer statistics and if process stats is also off, turn
8717 rxi_monitor_peerStats = 0;
8718 if (rxi_monitor_processStats == 0) {
8719 rx_enable_stats = 0;
8722 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8723 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8725 struct rx_peer *peer, *next, *prev;
8727 MUTEX_ENTER(&rx_peerHashTable_lock);
8728 MUTEX_ENTER(&rx_rpc_stats);
8729 for (prev = peer = *peer_ptr; peer; peer = next) {
8731 code = MUTEX_TRYENTER(&peer->peer_lock);
8733 rx_interface_stat_p rpc_stat, nrpc_stat;
8736 if (prev == *peer_ptr) {
8747 MUTEX_EXIT(&rx_peerHashTable_lock);
8750 (&peer->rpcStats, rpc_stat, nrpc_stat,
8751 rx_interface_stat)) {
8752 unsigned int num_funcs = 0;
8755 queue_Remove(&rpc_stat->queue_header);
8756 queue_Remove(&rpc_stat->all_peers);
8757 num_funcs = rpc_stat->stats[0].func_total;
8759 sizeof(rx_interface_stat_t) +
8760 rpc_stat->stats[0].func_total *
8761 sizeof(rx_function_entry_v1_t);
8763 rxi_Free(rpc_stat, space);
8764 rxi_rpc_peer_stat_cnt -= num_funcs;
8766 MUTEX_EXIT(&peer->peer_lock);
8768 MUTEX_ENTER(&rx_peerHashTable_lock);
8778 MUTEX_EXIT(&rx_rpc_stats);
8779 MUTEX_EXIT(&rx_peerHashTable_lock);
8784 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8789 * IN clearFlag - flag indicating which stats to clear
8797 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8799 rx_interface_stat_p rpc_stat, nrpc_stat;
8801 MUTEX_ENTER(&rx_rpc_stats);
8803 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8804 unsigned int num_funcs = 0, i;
8805 num_funcs = rpc_stat->stats[0].func_total;
8806 for (i = 0; i < num_funcs; i++) {
8807 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8808 hzero(rpc_stat->stats[i].invocations);
8810 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8811 hzero(rpc_stat->stats[i].bytes_sent);
8813 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8814 hzero(rpc_stat->stats[i].bytes_rcvd);
8816 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8817 rpc_stat->stats[i].queue_time_sum.sec = 0;
8818 rpc_stat->stats[i].queue_time_sum.usec = 0;
8820 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8821 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8822 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8824 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8825 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8826 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8828 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8829 rpc_stat->stats[i].queue_time_max.sec = 0;
8830 rpc_stat->stats[i].queue_time_max.usec = 0;
8832 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8833 rpc_stat->stats[i].execution_time_sum.sec = 0;
8834 rpc_stat->stats[i].execution_time_sum.usec = 0;
8836 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8837 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8838 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8840 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8841 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8842 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8844 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8845 rpc_stat->stats[i].execution_time_max.sec = 0;
8846 rpc_stat->stats[i].execution_time_max.usec = 0;
8851 MUTEX_EXIT(&rx_rpc_stats);
8855 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8860 * IN clearFlag - flag indicating which stats to clear
8868 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8870 rx_interface_stat_p rpc_stat, nrpc_stat;
8872 MUTEX_ENTER(&rx_rpc_stats);
8874 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8875 unsigned int num_funcs = 0, i;
8878 * We have to fix the offset of rpc_stat since we are
8879 * keeping this structure on two rx_queues. The rx_queue
8880 * package assumes that the rx_queue member is the first
8881 * member of the structure. That is, rx_queue assumes that
8882 * any one item is only on one queue at a time. We are
8883 * breaking that assumption and so we have to do a little
8884 * math to fix our pointers.
8887 fix_offset = (char *)rpc_stat;
8888 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8889 rpc_stat = (rx_interface_stat_p) fix_offset;
8891 num_funcs = rpc_stat->stats[0].func_total;
8892 for (i = 0; i < num_funcs; i++) {
8893 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8894 hzero(rpc_stat->stats[i].invocations);
8896 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8897 hzero(rpc_stat->stats[i].bytes_sent);
8899 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8900 hzero(rpc_stat->stats[i].bytes_rcvd);
8902 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8903 rpc_stat->stats[i].queue_time_sum.sec = 0;
8904 rpc_stat->stats[i].queue_time_sum.usec = 0;
8906 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8907 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8908 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8910 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8911 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8912 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8914 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8915 rpc_stat->stats[i].queue_time_max.sec = 0;
8916 rpc_stat->stats[i].queue_time_max.usec = 0;
8918 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8919 rpc_stat->stats[i].execution_time_sum.sec = 0;
8920 rpc_stat->stats[i].execution_time_sum.usec = 0;
8922 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8923 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8924 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8926 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8927 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8928 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8930 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8931 rpc_stat->stats[i].execution_time_max.sec = 0;
8932 rpc_stat->stats[i].execution_time_max.usec = 0;
8937 MUTEX_EXIT(&rx_rpc_stats);
8941 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8942 * is authorized to enable/disable/clear RX statistics.
8944 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8947 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8949 rxi_rxstat_userok = proc;
8953 rx_RxStatUserOk(struct rx_call *call)
8955 if (!rxi_rxstat_userok)
8957 return rxi_rxstat_userok(call);
8962 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8963 * function in the MSVC runtime DLL (msvcrt.dll).
8965 * Note: the system serializes calls to this function.
8968 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8969 DWORD reason, /* reason function is being called */
8970 LPVOID reserved) /* reserved for future use */
8973 case DLL_PROCESS_ATTACH:
8974 /* library is being attached to a process */
8978 case DLL_PROCESS_DETACH:
8985 #endif /* AFS_NT40_ENV */
8988 int rx_DumpCalls(FILE *outputFile, char *cookie)
8990 #ifdef RXDEBUG_PACKET
8991 #ifdef KDUMP_RX_LOCK
8992 struct rx_call_rx_lock *c;
8999 #define RXDPRINTF sprintf
9000 #define RXDPRINTOUT output
9002 #define RXDPRINTF fprintf
9003 #define RXDPRINTOUT outputFile
9006 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9008 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9011 for (c = rx_allCallsp; c; c = c->allNextp) {
9012 u_short rqc, tqc, iovqc;
9013 struct rx_packet *p, *np;
9015 MUTEX_ENTER(&c->lock);
9016 queue_Count(&c->rq, p, np, rx_packet, rqc);
9017 queue_Count(&c->tq, p, np, rx_packet, tqc);
9018 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9020 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, "
9021 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9022 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9023 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9024 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9025 #ifdef RX_ENABLE_LOCKS
9028 #ifdef RX_REFCOUNT_CHECK
9029 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9030 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9033 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,
9034 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9035 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9036 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9037 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9038 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9039 #ifdef RX_ENABLE_LOCKS
9040 , (afs_uint32)c->refCount
9042 #ifdef RX_REFCOUNT_CHECK
9043 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9046 MUTEX_EXIT(&c->lock);
9049 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9052 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9054 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9056 #endif /* RXDEBUG_PACKET */