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 "inet/common.h"
29 # include "inet/ip_ire.h"
31 # include "afs/afs_args.h"
32 # include "afs/afs_osi.h"
33 # ifdef RX_KERNEL_TRACE
34 # include "rx_kcommon.h"
36 # if defined(AFS_AIX_ENV)
40 # undef RXDEBUG /* turn off debugging */
42 # if defined(AFS_SGI_ENV)
43 # include "sys/debug.h"
46 # include "afs/sysincludes.h"
47 # include "afsincludes.h"
48 # endif /* !UKERNEL */
49 # include "afs/lock.h"
50 # include "rx_kmutex.h"
51 # include "rx_kernel.h"
52 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
53 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
54 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
55 extern afs_int32 afs_termState;
57 # include "sys/lockl.h"
58 # include "sys/lock_def.h"
59 # endif /* AFS_AIX41_ENV */
60 # include "afs/rxgen_consts.h"
62 # include <sys/types.h>
72 # include <afs/afsutil.h>
73 # include <WINNT\afsreg.h>
75 # include <sys/socket.h>
76 # include <sys/file.h>
78 # include <sys/stat.h>
79 # include <netinet/in.h>
80 # include <sys/time.h>
88 #include "rx_atomic.h"
89 #include "rx_globals.h"
91 #include "rx_internal.h"
94 #include <afs/rxgen_consts.h>
97 #ifdef AFS_PTHREAD_ENV
99 int (*registerProgram) (pid_t, char *) = 0;
100 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
103 int (*registerProgram) (PROCESS, char *) = 0;
104 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
108 /* Local static routines */
109 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
110 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
111 struct rx_peer *, struct clock *);
113 #ifdef RX_ENABLE_LOCKS
114 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
117 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
119 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
120 rx_atomic_t rxi_start_in_error;
122 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
125 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
126 * currently allocated within rx. This number is used to allocate the
127 * memory required to return the statistics when queried.
128 * Protected by the rx_rpc_stats mutex.
131 static unsigned int rxi_rpc_peer_stat_cnt;
134 * rxi_rpc_process_stat_cnt counts the total number of local process stat
135 * structures currently allocated within rx. The number is used to allocate
136 * the memory required to return the statistics when queried.
137 * Protected by the rx_rpc_stats mutex.
140 static unsigned int rxi_rpc_process_stat_cnt;
142 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
143 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
145 #if !defined(offsetof)
146 #include <stddef.h> /* for definition of offsetof() */
149 #ifdef RX_ENABLE_LOCKS
150 afs_kmutex_t rx_atomic_mutex;
153 #ifdef AFS_PTHREAD_ENV
156 * Use procedural initialization of mutexes/condition variables
160 extern afs_kmutex_t rx_quota_mutex;
161 extern afs_kmutex_t rx_pthread_mutex;
162 extern afs_kmutex_t rx_packets_mutex;
163 extern afs_kmutex_t rx_refcnt_mutex;
164 extern afs_kmutex_t des_init_mutex;
165 extern afs_kmutex_t des_random_mutex;
166 extern afs_kmutex_t rx_clock_mutex;
167 extern afs_kmutex_t rxi_connCacheMutex;
168 extern afs_kmutex_t rx_event_mutex;
169 extern afs_kmutex_t osi_malloc_mutex;
170 extern afs_kmutex_t event_handler_mutex;
171 extern afs_kmutex_t listener_mutex;
172 extern afs_kmutex_t rx_if_init_mutex;
173 extern afs_kmutex_t rx_if_mutex;
174 extern afs_kmutex_t rxkad_client_uid_mutex;
175 extern afs_kmutex_t rxkad_random_mutex;
177 extern afs_kcondvar_t rx_event_handler_cond;
178 extern afs_kcondvar_t rx_listener_cond;
180 static afs_kmutex_t epoch_mutex;
181 static afs_kmutex_t rx_init_mutex;
182 static afs_kmutex_t rx_debug_mutex;
183 static afs_kmutex_t rx_rpc_stats;
186 rxi_InitPthread(void)
188 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
189 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
190 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
191 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
192 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
193 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
194 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
210 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
211 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
213 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
214 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
216 rxkad_global_stats_init();
218 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
220 #ifdef RX_ENABLE_LOCKS
223 #endif /* RX_LOCKS_DB */
224 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
227 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
229 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
231 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
233 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
234 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
235 #endif /* RX_ENABLE_LOCKS */
238 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
239 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
241 * The rx_stats_mutex mutex protects the following global variables:
242 * rxi_lowConnRefCount
243 * rxi_lowPeerRefCount
252 * The rx_quota_mutex mutex protects the following global variables:
260 * The rx_freePktQ_lock protects the following global variables:
265 * The rx_packets_mutex mutex protects the following global variables:
273 * The rx_pthread_mutex mutex protects the following global variables:
274 * rxi_fcfs_thread_num
277 #define INIT_PTHREAD_LOCKS
281 /* Variables for handling the minProcs implementation. availProcs gives the
282 * number of threads available in the pool at this moment (not counting dudes
283 * executing right now). totalMin gives the total number of procs required
284 * for handling all minProcs requests. minDeficit is a dynamic variable
285 * tracking the # of procs required to satisfy all of the remaining minProcs
287 * For fine grain locking to work, the quota check and the reservation of
288 * a server thread has to come while rxi_availProcs and rxi_minDeficit
289 * are locked. To this end, the code has been modified under #ifdef
290 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
291 * same time. A new function, ReturnToServerPool() returns the allocation.
293 * A call can be on several queue's (but only one at a time). When
294 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
295 * that no one else is touching the queue. To this end, we store the address
296 * of the queue lock in the call structure (under the call lock) when we
297 * put the call on a queue, and we clear the call_queue_lock when the
298 * call is removed from a queue (once the call lock has been obtained).
299 * This allows rxi_ResetCall to safely synchronize with others wishing
300 * to manipulate the queue.
303 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
304 static afs_kmutex_t rx_rpc_stats;
305 void rxi_StartUnlocked(struct rxevent *event, void *call,
306 void *arg1, int istack);
309 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
310 ** pretty good that the next packet coming in is from the same connection
311 ** as the last packet, since we're send multiple packets in a transmit window.
313 struct rx_connection *rxLastConn = 0;
315 #ifdef RX_ENABLE_LOCKS
316 /* The locking hierarchy for rx fine grain locking is composed of these
319 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
320 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
321 * call->lock - locks call data fields.
322 * These are independent of each other:
323 * rx_freeCallQueue_lock
328 * serverQueueEntry->lock
329 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
331 * peer->lock - locks peer data fields.
332 * conn_data_lock - that more than one thread is not updating a conn data
333 * field at the same time.
344 * Do we need a lock to protect the peer field in the conn structure?
345 * conn->peer was previously a constant for all intents and so has no
346 * lock protecting this field. The multihomed client delta introduced
347 * a RX code change : change the peer field in the connection structure
348 * to that remote interface from which the last packet for this
349 * connection was sent out. This may become an issue if further changes
352 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
353 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
355 /* rxdb_fileID is used to identify the lock location, along with line#. */
356 static int rxdb_fileID = RXDB_FILE_RX;
357 #endif /* RX_LOCKS_DB */
358 #else /* RX_ENABLE_LOCKS */
359 #define SET_CALL_QUEUE_LOCK(C, L)
360 #define CLEAR_CALL_QUEUE_LOCK(C)
361 #endif /* RX_ENABLE_LOCKS */
362 struct rx_serverQueueEntry *rx_waitForPacket = 0;
363 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
365 /* ------------Exported Interfaces------------- */
367 /* This function allows rxkad to set the epoch to a suitably random number
368 * which rx_NewConnection will use in the future. The principle purpose is to
369 * get rxnull connections to use the same epoch as the rxkad connections do, at
370 * least once the first rxkad connection is established. This is important now
371 * that the host/port addresses aren't used in FindConnection: the uniqueness
372 * of epoch/cid matters and the start time won't do. */
374 #ifdef AFS_PTHREAD_ENV
376 * This mutex protects the following global variables:
380 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
381 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
385 #endif /* AFS_PTHREAD_ENV */
388 rx_SetEpoch(afs_uint32 epoch)
395 /* Initialize rx. A port number may be mentioned, in which case this
396 * becomes the default port number for any service installed later.
397 * If 0 is provided for the port number, a random port will be chosen
398 * by the kernel. Whether this will ever overlap anything in
399 * /etc/services is anybody's guess... Returns 0 on success, -1 on
404 int rxinit_status = 1;
405 #ifdef AFS_PTHREAD_ENV
407 * This mutex protects the following global variables:
411 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
412 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
415 #define UNLOCK_RX_INIT
419 rx_InitHost(u_int host, u_int port)
426 char *htable, *ptable;
433 if (rxinit_status == 0) {
434 tmp_status = rxinit_status;
436 return tmp_status; /* Already started; return previous error code. */
442 if (afs_winsockInit() < 0)
448 * Initialize anything necessary to provide a non-premptive threading
451 rxi_InitializeThreadSupport();
454 /* Allocate and initialize a socket for client and perhaps server
457 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
458 if (rx_socket == OSI_NULLSOCKET) {
462 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
465 #endif /* RX_LOCKS_DB */
466 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
467 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
468 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
469 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
470 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
471 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
472 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
476 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
478 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
480 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
482 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
483 #if defined(AFS_HPUX110_ENV)
485 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
486 #endif /* AFS_HPUX110_ENV */
487 #endif /* RX_ENABLE_LOCKS && KERNEL */
490 rx_connDeadTime = 12;
491 rx_tranquil = 0; /* reset flag */
492 rxi_ResetStatistics();
494 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
495 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
496 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
497 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
498 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
499 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
501 /* Malloc up a bunch of packets & buffers */
503 queue_Init(&rx_freePacketQueue);
504 rxi_NeedMorePackets = FALSE;
505 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
507 /* enforce a minimum number of allocated packets */
508 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
509 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
511 /* allocate the initial free packet pool */
512 #ifdef RX_ENABLE_TSFPQ
513 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
514 #else /* RX_ENABLE_TSFPQ */
515 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
516 #endif /* RX_ENABLE_TSFPQ */
523 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
524 tv.tv_sec = clock_now.sec;
525 tv.tv_usec = clock_now.usec;
526 srand((unsigned int)tv.tv_usec);
533 #if defined(KERNEL) && !defined(UKERNEL)
534 /* Really, this should never happen in a real kernel */
537 struct sockaddr_in addr;
539 int addrlen = sizeof(addr);
541 socklen_t addrlen = sizeof(addr);
543 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
547 rx_port = addr.sin_port;
550 rx_stats.minRtt.sec = 9999999;
552 rx_SetEpoch(tv.tv_sec | 0x80000000);
554 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
555 * will provide a randomer value. */
557 MUTEX_ENTER(&rx_quota_mutex);
558 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
559 MUTEX_EXIT(&rx_quota_mutex);
560 /* *Slightly* random start time for the cid. This is just to help
561 * out with the hashing function at the peer */
562 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
563 rx_connHashTable = (struct rx_connection **)htable;
564 rx_peerHashTable = (struct rx_peer **)ptable;
566 rx_lastAckDelay.sec = 0;
567 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
568 rx_hardAckDelay.sec = 0;
569 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
570 rx_softAckDelay.sec = 0;
571 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
573 rxevent_Init(20, rxi_ReScheduleEvents);
575 /* Initialize various global queues */
576 queue_Init(&rx_idleServerQueue);
577 queue_Init(&rx_incomingCallQueue);
578 queue_Init(&rx_freeCallQueue);
580 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
581 /* Initialize our list of usable IP addresses. */
585 /* Start listener process (exact function is dependent on the
586 * implementation environment--kernel or user space) */
590 tmp_status = rxinit_status = 0;
598 return rx_InitHost(htonl(INADDR_ANY), port);
601 /* called with unincremented nRequestsRunning to see if it is OK to start
602 * a new thread in this service. Could be "no" for two reasons: over the
603 * max quota, or would prevent others from reaching their min quota.
605 #ifdef RX_ENABLE_LOCKS
606 /* This verion of QuotaOK reserves quota if it's ok while the
607 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
610 QuotaOK(struct rx_service *aservice)
612 /* check if over max quota */
613 if (aservice->nRequestsRunning >= aservice->maxProcs) {
617 /* under min quota, we're OK */
618 /* otherwise, can use only if there are enough to allow everyone
619 * to go to their min quota after this guy starts.
622 MUTEX_ENTER(&rx_quota_mutex);
623 if ((aservice->nRequestsRunning < aservice->minProcs)
624 || (rxi_availProcs > rxi_minDeficit)) {
625 aservice->nRequestsRunning++;
626 /* just started call in minProcs pool, need fewer to maintain
628 if (aservice->nRequestsRunning <= aservice->minProcs)
631 MUTEX_EXIT(&rx_quota_mutex);
634 MUTEX_EXIT(&rx_quota_mutex);
640 ReturnToServerPool(struct rx_service *aservice)
642 aservice->nRequestsRunning--;
643 MUTEX_ENTER(&rx_quota_mutex);
644 if (aservice->nRequestsRunning < aservice->minProcs)
647 MUTEX_EXIT(&rx_quota_mutex);
650 #else /* RX_ENABLE_LOCKS */
652 QuotaOK(struct rx_service *aservice)
655 /* under min quota, we're OK */
656 if (aservice->nRequestsRunning < aservice->minProcs)
659 /* check if over max quota */
660 if (aservice->nRequestsRunning >= aservice->maxProcs)
663 /* otherwise, can use only if there are enough to allow everyone
664 * to go to their min quota after this guy starts.
666 MUTEX_ENTER(&rx_quota_mutex);
667 if (rxi_availProcs > rxi_minDeficit)
669 MUTEX_EXIT(&rx_quota_mutex);
672 #endif /* RX_ENABLE_LOCKS */
675 /* Called by rx_StartServer to start up lwp's to service calls.
676 NExistingProcs gives the number of procs already existing, and which
677 therefore needn't be created. */
679 rxi_StartServerProcs(int nExistingProcs)
681 struct rx_service *service;
686 /* For each service, reserve N processes, where N is the "minimum"
687 * number of processes that MUST be able to execute a request in parallel,
688 * at any time, for that process. Also compute the maximum difference
689 * between any service's maximum number of processes that can run
690 * (i.e. the maximum number that ever will be run, and a guarantee
691 * that this number will run if other services aren't running), and its
692 * minimum number. The result is the extra number of processes that
693 * we need in order to provide the latter guarantee */
694 for (i = 0; i < RX_MAX_SERVICES; i++) {
696 service = rx_services[i];
697 if (service == (struct rx_service *)0)
699 nProcs += service->minProcs;
700 diff = service->maxProcs - service->minProcs;
704 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
705 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
706 for (i = 0; i < nProcs; i++) {
707 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
713 /* This routine is only required on Windows */
715 rx_StartClientThread(void)
717 #ifdef AFS_PTHREAD_ENV
719 pid = pthread_self();
720 #endif /* AFS_PTHREAD_ENV */
722 #endif /* AFS_NT40_ENV */
724 /* This routine must be called if any services are exported. If the
725 * donateMe flag is set, the calling process is donated to the server
728 rx_StartServer(int donateMe)
730 struct rx_service *service;
736 /* Start server processes, if necessary (exact function is dependent
737 * on the implementation environment--kernel or user space). DonateMe
738 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
739 * case, one less new proc will be created rx_StartServerProcs.
741 rxi_StartServerProcs(donateMe);
743 /* count up the # of threads in minProcs, and add set the min deficit to
744 * be that value, too.
746 for (i = 0; i < RX_MAX_SERVICES; i++) {
747 service = rx_services[i];
748 if (service == (struct rx_service *)0)
750 MUTEX_ENTER(&rx_quota_mutex);
751 rxi_totalMin += service->minProcs;
752 /* below works even if a thread is running, since minDeficit would
753 * still have been decremented and later re-incremented.
755 rxi_minDeficit += service->minProcs;
756 MUTEX_EXIT(&rx_quota_mutex);
759 /* Turn on reaping of idle server connections */
760 rxi_ReapConnections(NULL, NULL, NULL);
769 #ifdef AFS_PTHREAD_ENV
771 pid = afs_pointer_to_int(pthread_self());
772 #else /* AFS_PTHREAD_ENV */
774 LWP_CurrentProcess(&pid);
775 #endif /* AFS_PTHREAD_ENV */
777 sprintf(name, "srv_%d", ++nProcs);
779 (*registerProgram) (pid, name);
781 #endif /* AFS_NT40_ENV */
782 rx_ServerProc(NULL); /* Never returns */
784 #ifdef RX_ENABLE_TSFPQ
785 /* no use leaving packets around in this thread's local queue if
786 * it isn't getting donated to the server thread pool.
788 rxi_FlushLocalPacketsTSFPQ();
789 #endif /* RX_ENABLE_TSFPQ */
793 /* Create a new client connection to the specified service, using the
794 * specified security object to implement the security model for this
796 struct rx_connection *
797 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
798 struct rx_securityClass *securityObject,
799 int serviceSecurityIndex)
803 struct rx_connection *conn;
808 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
809 "serviceSecurityIndex %d)\n",
810 ntohl(shost), ntohs(sport), sservice, securityObject,
811 serviceSecurityIndex));
813 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
814 * the case of kmem_alloc? */
815 conn = rxi_AllocConnection();
816 #ifdef RX_ENABLE_LOCKS
817 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
818 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
819 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
822 MUTEX_ENTER(&rx_connHashTable_lock);
823 cid = (rx_nextCid += RX_MAXCALLS);
824 conn->type = RX_CLIENT_CONNECTION;
826 conn->epoch = rx_epoch;
827 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
828 conn->serviceId = sservice;
829 conn->securityObject = securityObject;
830 conn->securityData = (void *) 0;
831 conn->securityIndex = serviceSecurityIndex;
832 rx_SetConnDeadTime(conn, rx_connDeadTime);
833 rx_SetConnSecondsUntilNatPing(conn, 0);
834 conn->ackRate = RX_FAST_ACK_RATE;
836 conn->specific = NULL;
837 conn->challengeEvent = NULL;
838 conn->delayedAbortEvent = NULL;
839 conn->abortCount = 0;
841 for (i = 0; i < RX_MAXCALLS; i++) {
842 conn->twind[i] = rx_initSendWindow;
843 conn->rwind[i] = rx_initReceiveWindow;
846 RXS_NewConnection(securityObject, conn);
848 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
850 conn->refCount++; /* no lock required since only this thread knows... */
851 conn->next = rx_connHashTable[hashindex];
852 rx_connHashTable[hashindex] = conn;
854 rx_atomic_inc(&rx_stats.nClientConns);
855 MUTEX_EXIT(&rx_connHashTable_lock);
861 * Ensure a connection's timeout values are valid.
863 * @param[in] conn The connection to check
865 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
866 * unless idleDeadTime and/or hardDeadTime are not set
870 rxi_CheckConnTimeouts(struct rx_connection *conn)
872 /* a connection's timeouts must have the relationship
873 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
874 * total loss of network to a peer may cause an idle timeout instead of a
875 * dead timeout, simply because the idle timeout gets hit first. Also set
876 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
877 /* this logic is slightly complicated by the fact that
878 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
880 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
881 if (conn->idleDeadTime) {
882 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
884 if (conn->hardDeadTime) {
885 if (conn->idleDeadTime) {
886 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
888 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
894 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
896 /* The idea is to set the dead time to a value that allows several
897 * keepalives to be dropped without timing out the connection. */
898 conn->secondsUntilDead = seconds;
899 rxi_CheckConnTimeouts(conn);
900 conn->secondsUntilPing = conn->secondsUntilDead / 6;
904 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
906 conn->hardDeadTime = seconds;
907 rxi_CheckConnTimeouts(conn);
911 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
913 conn->idleDeadTime = seconds;
914 rxi_CheckConnTimeouts(conn);
917 int rxi_lowPeerRefCount = 0;
918 int rxi_lowConnRefCount = 0;
921 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
922 * NOTE: must not be called with rx_connHashTable_lock held.
925 rxi_CleanupConnection(struct rx_connection *conn)
927 /* Notify the service exporter, if requested, that this connection
928 * is being destroyed */
929 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
930 (*conn->service->destroyConnProc) (conn);
932 /* Notify the security module that this connection is being destroyed */
933 RXS_DestroyConnection(conn->securityObject, conn);
935 /* If this is the last connection using the rx_peer struct, set its
936 * idle time to now. rxi_ReapConnections will reap it if it's still
937 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
939 MUTEX_ENTER(&rx_peerHashTable_lock);
940 if (conn->peer->refCount < 2) {
941 conn->peer->idleWhen = clock_Sec();
942 if (conn->peer->refCount < 1) {
943 conn->peer->refCount = 1;
944 if (rx_stats_active) {
945 MUTEX_ENTER(&rx_stats_mutex);
946 rxi_lowPeerRefCount++;
947 MUTEX_EXIT(&rx_stats_mutex);
951 conn->peer->refCount--;
952 MUTEX_EXIT(&rx_peerHashTable_lock);
956 if (conn->type == RX_SERVER_CONNECTION)
957 rx_atomic_dec(&rx_stats.nServerConns);
959 rx_atomic_dec(&rx_stats.nClientConns);
962 if (conn->specific) {
964 for (i = 0; i < conn->nSpecific; i++) {
965 if (conn->specific[i] && rxi_keyCreate_destructor[i])
966 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
967 conn->specific[i] = NULL;
969 free(conn->specific);
971 conn->specific = NULL;
975 MUTEX_DESTROY(&conn->conn_call_lock);
976 MUTEX_DESTROY(&conn->conn_data_lock);
977 CV_DESTROY(&conn->conn_call_cv);
979 rxi_FreeConnection(conn);
982 /* Destroy the specified connection */
984 rxi_DestroyConnection(struct rx_connection *conn)
986 MUTEX_ENTER(&rx_connHashTable_lock);
987 rxi_DestroyConnectionNoLock(conn);
988 /* conn should be at the head of the cleanup list */
989 if (conn == rx_connCleanup_list) {
990 rx_connCleanup_list = rx_connCleanup_list->next;
991 MUTEX_EXIT(&rx_connHashTable_lock);
992 rxi_CleanupConnection(conn);
994 #ifdef RX_ENABLE_LOCKS
996 MUTEX_EXIT(&rx_connHashTable_lock);
998 #endif /* RX_ENABLE_LOCKS */
1002 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1004 struct rx_connection **conn_ptr;
1006 struct rx_packet *packet;
1013 MUTEX_ENTER(&conn->conn_data_lock);
1014 MUTEX_ENTER(&rx_refcnt_mutex);
1015 if (conn->refCount > 0)
1018 if (rx_stats_active) {
1019 MUTEX_ENTER(&rx_stats_mutex);
1020 rxi_lowConnRefCount++;
1021 MUTEX_EXIT(&rx_stats_mutex);
1025 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1026 /* Busy; wait till the last guy before proceeding */
1027 MUTEX_EXIT(&rx_refcnt_mutex);
1028 MUTEX_EXIT(&conn->conn_data_lock);
1033 /* If the client previously called rx_NewCall, but it is still
1034 * waiting, treat this as a running call, and wait to destroy the
1035 * connection later when the call completes. */
1036 if ((conn->type == RX_CLIENT_CONNECTION)
1037 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1038 conn->flags |= RX_CONN_DESTROY_ME;
1039 MUTEX_EXIT(&conn->conn_data_lock);
1043 MUTEX_EXIT(&rx_refcnt_mutex);
1044 MUTEX_EXIT(&conn->conn_data_lock);
1046 /* Check for extant references to this connection */
1047 for (i = 0; i < RX_MAXCALLS; i++) {
1048 struct rx_call *call = conn->call[i];
1051 if (conn->type == RX_CLIENT_CONNECTION) {
1052 MUTEX_ENTER(&call->lock);
1053 if (call->delayedAckEvent) {
1054 /* Push the final acknowledgment out now--there
1055 * won't be a subsequent call to acknowledge the
1056 * last reply packets */
1057 rxevent_Cancel(call->delayedAckEvent, call,
1058 RX_CALL_REFCOUNT_DELAY);
1059 if (call->state == RX_STATE_PRECALL
1060 || call->state == RX_STATE_ACTIVE) {
1061 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1063 rxi_AckAll(NULL, call, 0);
1066 MUTEX_EXIT(&call->lock);
1070 #ifdef RX_ENABLE_LOCKS
1072 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1073 MUTEX_EXIT(&conn->conn_data_lock);
1075 /* Someone is accessing a packet right now. */
1079 #endif /* RX_ENABLE_LOCKS */
1082 /* Don't destroy the connection if there are any call
1083 * structures still in use */
1084 MUTEX_ENTER(&conn->conn_data_lock);
1085 conn->flags |= RX_CONN_DESTROY_ME;
1086 MUTEX_EXIT(&conn->conn_data_lock);
1091 if (conn->natKeepAliveEvent) {
1092 rxi_NatKeepAliveOff(conn);
1095 if (conn->delayedAbortEvent) {
1096 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1097 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1099 MUTEX_ENTER(&conn->conn_data_lock);
1100 rxi_SendConnectionAbort(conn, packet, 0, 1);
1101 MUTEX_EXIT(&conn->conn_data_lock);
1102 rxi_FreePacket(packet);
1106 /* Remove from connection hash table before proceeding */
1108 &rx_connHashTable[CONN_HASH
1109 (peer->host, peer->port, conn->cid, conn->epoch,
1111 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1112 if (*conn_ptr == conn) {
1113 *conn_ptr = conn->next;
1117 /* if the conn that we are destroying was the last connection, then we
1118 * clear rxLastConn as well */
1119 if (rxLastConn == conn)
1122 /* Make sure the connection is completely reset before deleting it. */
1123 /* get rid of pending events that could zap us later */
1124 if (conn->challengeEvent)
1125 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1126 if (conn->checkReachEvent)
1127 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1128 if (conn->natKeepAliveEvent)
1129 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1131 /* Add the connection to the list of destroyed connections that
1132 * need to be cleaned up. This is necessary to avoid deadlocks
1133 * in the routines we call to inform others that this connection is
1134 * being destroyed. */
1135 conn->next = rx_connCleanup_list;
1136 rx_connCleanup_list = conn;
1139 /* Externally available version */
1141 rx_DestroyConnection(struct rx_connection *conn)
1146 rxi_DestroyConnection(conn);
1151 rx_GetConnection(struct rx_connection *conn)
1156 MUTEX_ENTER(&rx_refcnt_mutex);
1158 MUTEX_EXIT(&rx_refcnt_mutex);
1162 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1163 /* Wait for the transmit queue to no longer be busy.
1164 * requires the call->lock to be held */
1166 rxi_WaitforTQBusy(struct rx_call *call) {
1167 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1168 call->flags |= RX_CALL_TQ_WAIT;
1170 #ifdef RX_ENABLE_LOCKS
1171 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1172 CV_WAIT(&call->cv_tq, &call->lock);
1173 #else /* RX_ENABLE_LOCKS */
1174 osi_rxSleep(&call->tq);
1175 #endif /* RX_ENABLE_LOCKS */
1177 if (call->tqWaiters == 0) {
1178 call->flags &= ~RX_CALL_TQ_WAIT;
1185 rxi_WakeUpTransmitQueue(struct rx_call *call)
1187 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1188 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1189 call, call->tqWaiters, call->flags));
1190 #ifdef RX_ENABLE_LOCKS
1191 osirx_AssertMine(&call->lock, "rxi_Start start");
1192 CV_BROADCAST(&call->cv_tq);
1193 #else /* RX_ENABLE_LOCKS */
1194 osi_rxWakeup(&call->tq);
1195 #endif /* RX_ENABLE_LOCKS */
1199 /* Start a new rx remote procedure call, on the specified connection.
1200 * If wait is set to 1, wait for a free call channel; otherwise return
1201 * 0. Maxtime gives the maximum number of seconds this call may take,
1202 * after rx_NewCall returns. After this time interval, a call to any
1203 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1204 * For fine grain locking, we hold the conn_call_lock in order to
1205 * to ensure that we don't get signalle after we found a call in an active
1206 * state and before we go to sleep.
1209 rx_NewCall(struct rx_connection *conn)
1212 struct rx_call *call;
1213 struct clock queueTime;
1217 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1220 clock_GetTime(&queueTime);
1222 * Check if there are others waiting for a new call.
1223 * If so, let them go first to avoid starving them.
1224 * This is a fairly simple scheme, and might not be
1225 * a complete solution for large numbers of waiters.
1227 * makeCallWaiters keeps track of the number of
1228 * threads waiting to make calls and the
1229 * RX_CONN_MAKECALL_WAITING flag bit is used to
1230 * indicate that there are indeed calls waiting.
1231 * The flag is set when the waiter is incremented.
1232 * It is only cleared when makeCallWaiters is 0.
1233 * This prevents us from accidently destroying the
1234 * connection while it is potentially about to be used.
1236 MUTEX_ENTER(&conn->conn_call_lock);
1237 MUTEX_ENTER(&conn->conn_data_lock);
1238 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1239 conn->flags |= RX_CONN_MAKECALL_WAITING;
1240 conn->makeCallWaiters++;
1241 MUTEX_EXIT(&conn->conn_data_lock);
1243 #ifdef RX_ENABLE_LOCKS
1244 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1248 MUTEX_ENTER(&conn->conn_data_lock);
1249 conn->makeCallWaiters--;
1250 if (conn->makeCallWaiters == 0)
1251 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1254 /* We are now the active thread in rx_NewCall */
1255 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1256 MUTEX_EXIT(&conn->conn_data_lock);
1261 for (i = 0; i < RX_MAXCALLS; i++) {
1262 call = conn->call[i];
1264 if (call->state == RX_STATE_DALLY) {
1265 MUTEX_ENTER(&call->lock);
1266 if (call->state == RX_STATE_DALLY) {
1268 * We are setting the state to RX_STATE_RESET to
1269 * ensure that no one else will attempt to use this
1270 * call once we drop the conn->conn_call_lock and
1271 * call->lock. We must drop the conn->conn_call_lock
1272 * before calling rxi_ResetCall because the process
1273 * of clearing the transmit queue can block for an
1274 * extended period of time. If we block while holding
1275 * the conn->conn_call_lock, then all rx_EndCall
1276 * processing will block as well. This has a detrimental
1277 * effect on overall system performance.
1279 call->state = RX_STATE_RESET;
1280 MUTEX_EXIT(&conn->conn_call_lock);
1281 MUTEX_ENTER(&rx_refcnt_mutex);
1282 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1283 MUTEX_EXIT(&rx_refcnt_mutex);
1284 rxi_ResetCall(call, 0);
1285 (*call->callNumber)++;
1286 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1290 * If we failed to be able to safely obtain the
1291 * conn->conn_call_lock we will have to drop the
1292 * call->lock to avoid a deadlock. When the call->lock
1293 * is released the state of the call can change. If it
1294 * is no longer RX_STATE_RESET then some other thread is
1297 MUTEX_EXIT(&call->lock);
1298 MUTEX_ENTER(&conn->conn_call_lock);
1299 MUTEX_ENTER(&call->lock);
1301 if (call->state == RX_STATE_RESET)
1305 * If we get here it means that after dropping
1306 * the conn->conn_call_lock and call->lock that
1307 * the call is no longer ours. If we can't find
1308 * a free call in the remaining slots we should
1309 * not go immediately to RX_CONN_MAKECALL_WAITING
1310 * because by dropping the conn->conn_call_lock
1311 * we have given up synchronization with rx_EndCall.
1312 * Instead, cycle through one more time to see if
1313 * we can find a call that can call our own.
1315 MUTEX_ENTER(&rx_refcnt_mutex);
1316 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1317 MUTEX_EXIT(&rx_refcnt_mutex);
1320 MUTEX_EXIT(&call->lock);
1323 /* rxi_NewCall returns with mutex locked */
1324 call = rxi_NewCall(conn, i);
1325 MUTEX_ENTER(&rx_refcnt_mutex);
1326 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1327 MUTEX_EXIT(&rx_refcnt_mutex);
1331 if (i < RX_MAXCALLS) {
1337 MUTEX_ENTER(&conn->conn_data_lock);
1338 conn->flags |= RX_CONN_MAKECALL_WAITING;
1339 conn->makeCallWaiters++;
1340 MUTEX_EXIT(&conn->conn_data_lock);
1342 #ifdef RX_ENABLE_LOCKS
1343 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1347 MUTEX_ENTER(&conn->conn_data_lock);
1348 conn->makeCallWaiters--;
1349 if (conn->makeCallWaiters == 0)
1350 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1351 MUTEX_EXIT(&conn->conn_data_lock);
1353 /* Client is initially in send mode */
1354 call->state = RX_STATE_ACTIVE;
1355 call->error = conn->error;
1357 call->mode = RX_MODE_ERROR;
1359 call->mode = RX_MODE_SENDING;
1361 /* remember start time for call in case we have hard dead time limit */
1362 call->queueTime = queueTime;
1363 clock_GetTime(&call->startTime);
1364 hzero(call->bytesSent);
1365 hzero(call->bytesRcvd);
1367 /* Turn on busy protocol. */
1368 rxi_KeepAliveOn(call);
1370 /* Attempt MTU discovery */
1371 rxi_GrowMTUOn(call);
1374 * We are no longer the active thread in rx_NewCall
1376 MUTEX_ENTER(&conn->conn_data_lock);
1377 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1378 MUTEX_EXIT(&conn->conn_data_lock);
1381 * Wake up anyone else who might be giving us a chance to
1382 * run (see code above that avoids resource starvation).
1384 #ifdef RX_ENABLE_LOCKS
1385 CV_BROADCAST(&conn->conn_call_cv);
1389 MUTEX_EXIT(&conn->conn_call_lock);
1391 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1392 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1393 osi_Panic("rx_NewCall call about to be used without an empty tq");
1395 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1397 MUTEX_EXIT(&call->lock);
1400 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1405 rxi_HasActiveCalls(struct rx_connection *aconn)
1408 struct rx_call *tcall;
1412 for (i = 0; i < RX_MAXCALLS; i++) {
1413 if ((tcall = aconn->call[i])) {
1414 if ((tcall->state == RX_STATE_ACTIVE)
1415 || (tcall->state == RX_STATE_PRECALL)) {
1426 rxi_GetCallNumberVector(struct rx_connection *aconn,
1427 afs_int32 * aint32s)
1430 struct rx_call *tcall;
1434 for (i = 0; i < RX_MAXCALLS; i++) {
1435 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1436 aint32s[i] = aconn->callNumber[i] + 1;
1438 aint32s[i] = aconn->callNumber[i];
1445 rxi_SetCallNumberVector(struct rx_connection *aconn,
1446 afs_int32 * aint32s)
1449 struct rx_call *tcall;
1453 for (i = 0; i < RX_MAXCALLS; i++) {
1454 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1455 aconn->callNumber[i] = aint32s[i] - 1;
1457 aconn->callNumber[i] = aint32s[i];
1463 /* Advertise a new service. A service is named locally by a UDP port
1464 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1467 char *serviceName; Name for identification purposes (e.g. the
1468 service name might be used for probing for
1471 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1472 char *serviceName, struct rx_securityClass **securityObjects,
1473 int nSecurityObjects,
1474 afs_int32(*serviceProc) (struct rx_call * acall))
1476 osi_socket socket = OSI_NULLSOCKET;
1477 struct rx_service *tservice;
1483 if (serviceId == 0) {
1485 "rx_NewService: service id for service %s is not non-zero.\n",
1492 "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",
1500 tservice = rxi_AllocService();
1503 #ifdef RX_ENABLE_LOCKS
1504 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1507 for (i = 0; i < RX_MAX_SERVICES; i++) {
1508 struct rx_service *service = rx_services[i];
1510 if (port == service->servicePort && host == service->serviceHost) {
1511 if (service->serviceId == serviceId) {
1512 /* The identical service has already been
1513 * installed; if the caller was intending to
1514 * change the security classes used by this
1515 * service, he/she loses. */
1517 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1518 serviceName, serviceId, service->serviceName);
1520 rxi_FreeService(tservice);
1523 /* Different service, same port: re-use the socket
1524 * which is bound to the same port */
1525 socket = service->socket;
1528 if (socket == OSI_NULLSOCKET) {
1529 /* If we don't already have a socket (from another
1530 * service on same port) get a new one */
1531 socket = rxi_GetHostUDPSocket(host, port);
1532 if (socket == OSI_NULLSOCKET) {
1534 rxi_FreeService(tservice);
1539 service->socket = socket;
1540 service->serviceHost = host;
1541 service->servicePort = port;
1542 service->serviceId = serviceId;
1543 service->serviceName = serviceName;
1544 service->nSecurityObjects = nSecurityObjects;
1545 service->securityObjects = securityObjects;
1546 service->minProcs = 0;
1547 service->maxProcs = 1;
1548 service->idleDeadTime = 60;
1549 service->idleDeadErr = 0;
1550 service->connDeadTime = rx_connDeadTime;
1551 service->executeRequestProc = serviceProc;
1552 service->checkReach = 0;
1553 service->nSpecific = 0;
1554 service->specific = NULL;
1555 rx_services[i] = service; /* not visible until now */
1561 rxi_FreeService(tservice);
1562 (osi_Msg "rx_NewService: cannot support > %d services\n",
1567 /* Set configuration options for all of a service's security objects */
1570 rx_SetSecurityConfiguration(struct rx_service *service,
1571 rx_securityConfigVariables type,
1575 for (i = 0; i<service->nSecurityObjects; i++) {
1576 if (service->securityObjects[i]) {
1577 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1585 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1586 struct rx_securityClass **securityObjects, int nSecurityObjects,
1587 afs_int32(*serviceProc) (struct rx_call * acall))
1589 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1592 /* Generic request processing loop. This routine should be called
1593 * by the implementation dependent rx_ServerProc. If socketp is
1594 * non-null, it will be set to the file descriptor that this thread
1595 * is now listening on. If socketp is null, this routine will never
1598 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1600 struct rx_call *call;
1602 struct rx_service *tservice = NULL;
1609 call = rx_GetCall(threadID, tservice, socketp);
1610 if (socketp && *socketp != OSI_NULLSOCKET) {
1611 /* We are now a listener thread */
1616 /* if server is restarting( typically smooth shutdown) then do not
1617 * allow any new calls.
1620 if (rx_tranquil && (call != NULL)) {
1624 MUTEX_ENTER(&call->lock);
1626 rxi_CallError(call, RX_RESTARTING);
1627 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1629 MUTEX_EXIT(&call->lock);
1633 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1634 #ifdef RX_ENABLE_LOCKS
1636 #endif /* RX_ENABLE_LOCKS */
1637 afs_termState = AFSOP_STOP_AFS;
1638 afs_osi_Wakeup(&afs_termState);
1639 #ifdef RX_ENABLE_LOCKS
1641 #endif /* RX_ENABLE_LOCKS */
1646 tservice = call->conn->service;
1648 if (tservice->beforeProc)
1649 (*tservice->beforeProc) (call);
1651 code = tservice->executeRequestProc(call);
1653 if (tservice->afterProc)
1654 (*tservice->afterProc) (call, code);
1656 rx_EndCall(call, code);
1657 if (rx_stats_active) {
1658 MUTEX_ENTER(&rx_stats_mutex);
1660 MUTEX_EXIT(&rx_stats_mutex);
1667 rx_WakeupServerProcs(void)
1669 struct rx_serverQueueEntry *np, *tqp;
1673 MUTEX_ENTER(&rx_serverPool_lock);
1675 #ifdef RX_ENABLE_LOCKS
1676 if (rx_waitForPacket)
1677 CV_BROADCAST(&rx_waitForPacket->cv);
1678 #else /* RX_ENABLE_LOCKS */
1679 if (rx_waitForPacket)
1680 osi_rxWakeup(rx_waitForPacket);
1681 #endif /* RX_ENABLE_LOCKS */
1682 MUTEX_ENTER(&freeSQEList_lock);
1683 for (np = rx_FreeSQEList; np; np = tqp) {
1684 tqp = *(struct rx_serverQueueEntry **)np;
1685 #ifdef RX_ENABLE_LOCKS
1686 CV_BROADCAST(&np->cv);
1687 #else /* RX_ENABLE_LOCKS */
1689 #endif /* RX_ENABLE_LOCKS */
1691 MUTEX_EXIT(&freeSQEList_lock);
1692 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1693 #ifdef RX_ENABLE_LOCKS
1694 CV_BROADCAST(&np->cv);
1695 #else /* RX_ENABLE_LOCKS */
1697 #endif /* RX_ENABLE_LOCKS */
1699 MUTEX_EXIT(&rx_serverPool_lock);
1704 * One thing that seems to happen is that all the server threads get
1705 * tied up on some empty or slow call, and then a whole bunch of calls
1706 * arrive at once, using up the packet pool, so now there are more
1707 * empty calls. The most critical resources here are server threads
1708 * and the free packet pool. The "doreclaim" code seems to help in
1709 * general. I think that eventually we arrive in this state: there
1710 * are lots of pending calls which do have all their packets present,
1711 * so they won't be reclaimed, are multi-packet calls, so they won't
1712 * be scheduled until later, and thus are tying up most of the free
1713 * packet pool for a very long time.
1715 * 1. schedule multi-packet calls if all the packets are present.
1716 * Probably CPU-bound operation, useful to return packets to pool.
1717 * Do what if there is a full window, but the last packet isn't here?
1718 * 3. preserve one thread which *only* runs "best" calls, otherwise
1719 * it sleeps and waits for that type of call.
1720 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1721 * the current dataquota business is badly broken. The quota isn't adjusted
1722 * to reflect how many packets are presently queued for a running call.
1723 * So, when we schedule a queued call with a full window of packets queued
1724 * up for it, that *should* free up a window full of packets for other 2d-class
1725 * calls to be able to use from the packet pool. But it doesn't.
1727 * NB. Most of the time, this code doesn't run -- since idle server threads
1728 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1729 * as a new call arrives.
1731 /* Sleep until a call arrives. Returns a pointer to the call, ready
1732 * for an rx_Read. */
1733 #ifdef RX_ENABLE_LOCKS
1735 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1737 struct rx_serverQueueEntry *sq;
1738 struct rx_call *call = (struct rx_call *)0;
1739 struct rx_service *service = NULL;
1742 MUTEX_ENTER(&freeSQEList_lock);
1744 if ((sq = rx_FreeSQEList)) {
1745 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1746 MUTEX_EXIT(&freeSQEList_lock);
1747 } else { /* otherwise allocate a new one and return that */
1748 MUTEX_EXIT(&freeSQEList_lock);
1749 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1750 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1751 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1754 MUTEX_ENTER(&rx_serverPool_lock);
1755 if (cur_service != NULL) {
1756 ReturnToServerPool(cur_service);
1759 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1760 struct rx_call *tcall, *ncall, *choice2 = NULL;
1762 /* Scan for eligible incoming calls. A call is not eligible
1763 * if the maximum number of calls for its service type are
1764 * already executing */
1765 /* One thread will process calls FCFS (to prevent starvation),
1766 * while the other threads may run ahead looking for calls which
1767 * have all their input data available immediately. This helps
1768 * keep threads from blocking, waiting for data from the client. */
1769 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1770 service = tcall->conn->service;
1771 if (!QuotaOK(service)) {
1774 MUTEX_ENTER(&rx_pthread_mutex);
1775 if (tno == rxi_fcfs_thread_num
1776 || !tcall->queue_item_header.next) {
1777 MUTEX_EXIT(&rx_pthread_mutex);
1778 /* If we're the fcfs thread , then we'll just use
1779 * this call. If we haven't been able to find an optimal
1780 * choice, and we're at the end of the list, then use a
1781 * 2d choice if one has been identified. Otherwise... */
1782 call = (choice2 ? choice2 : tcall);
1783 service = call->conn->service;
1785 MUTEX_EXIT(&rx_pthread_mutex);
1786 if (!queue_IsEmpty(&tcall->rq)) {
1787 struct rx_packet *rp;
1788 rp = queue_First(&tcall->rq, rx_packet);
1789 if (rp->header.seq == 1) {
1791 || (rp->header.flags & RX_LAST_PACKET)) {
1793 } else if (rxi_2dchoice && !choice2
1794 && !(tcall->flags & RX_CALL_CLEARED)
1795 && (tcall->rprev > rxi_HardAckRate)) {
1805 ReturnToServerPool(service);
1812 MUTEX_EXIT(&rx_serverPool_lock);
1813 MUTEX_ENTER(&call->lock);
1815 if (call->flags & RX_CALL_WAIT_PROC) {
1816 call->flags &= ~RX_CALL_WAIT_PROC;
1817 rx_atomic_dec(&rx_nWaiting);
1820 if (call->state != RX_STATE_PRECALL || call->error) {
1821 MUTEX_EXIT(&call->lock);
1822 MUTEX_ENTER(&rx_serverPool_lock);
1823 ReturnToServerPool(service);
1828 if (queue_IsEmpty(&call->rq)
1829 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1830 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1832 CLEAR_CALL_QUEUE_LOCK(call);
1835 /* If there are no eligible incoming calls, add this process
1836 * to the idle server queue, to wait for one */
1840 *socketp = OSI_NULLSOCKET;
1842 sq->socketp = socketp;
1843 queue_Append(&rx_idleServerQueue, sq);
1844 #ifndef AFS_AIX41_ENV
1845 rx_waitForPacket = sq;
1847 rx_waitingForPacket = sq;
1848 #endif /* AFS_AIX41_ENV */
1850 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1852 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1853 MUTEX_EXIT(&rx_serverPool_lock);
1854 return (struct rx_call *)0;
1857 } while (!(call = sq->newcall)
1858 && !(socketp && *socketp != OSI_NULLSOCKET));
1859 MUTEX_EXIT(&rx_serverPool_lock);
1861 MUTEX_ENTER(&call->lock);
1867 MUTEX_ENTER(&freeSQEList_lock);
1868 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1869 rx_FreeSQEList = sq;
1870 MUTEX_EXIT(&freeSQEList_lock);
1873 clock_GetTime(&call->startTime);
1874 call->state = RX_STATE_ACTIVE;
1875 call->mode = RX_MODE_RECEIVING;
1876 #ifdef RX_KERNEL_TRACE
1877 if (ICL_SETACTIVE(afs_iclSetp)) {
1878 int glockOwner = ISAFS_GLOCK();
1881 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1882 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1889 rxi_calltrace(RX_CALL_START, call);
1890 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1891 call->conn->service->servicePort, call->conn->service->serviceId,
1894 MUTEX_EXIT(&call->lock);
1895 MUTEX_ENTER(&rx_refcnt_mutex);
1896 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1897 MUTEX_EXIT(&rx_refcnt_mutex);
1899 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1904 #else /* RX_ENABLE_LOCKS */
1906 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1908 struct rx_serverQueueEntry *sq;
1909 struct rx_call *call = (struct rx_call *)0, *choice2;
1910 struct rx_service *service = NULL;
1914 MUTEX_ENTER(&freeSQEList_lock);
1916 if ((sq = rx_FreeSQEList)) {
1917 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1918 MUTEX_EXIT(&freeSQEList_lock);
1919 } else { /* otherwise allocate a new one and return that */
1920 MUTEX_EXIT(&freeSQEList_lock);
1921 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1922 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1923 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1925 MUTEX_ENTER(&sq->lock);
1927 if (cur_service != NULL) {
1928 cur_service->nRequestsRunning--;
1929 MUTEX_ENTER(&rx_quota_mutex);
1930 if (cur_service->nRequestsRunning < cur_service->minProcs)
1933 MUTEX_EXIT(&rx_quota_mutex);
1935 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1936 struct rx_call *tcall, *ncall;
1937 /* Scan for eligible incoming calls. A call is not eligible
1938 * if the maximum number of calls for its service type are
1939 * already executing */
1940 /* One thread will process calls FCFS (to prevent starvation),
1941 * while the other threads may run ahead looking for calls which
1942 * have all their input data available immediately. This helps
1943 * keep threads from blocking, waiting for data from the client. */
1944 choice2 = (struct rx_call *)0;
1945 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1946 service = tcall->conn->service;
1947 if (QuotaOK(service)) {
1948 MUTEX_ENTER(&rx_pthread_mutex);
1949 if (tno == rxi_fcfs_thread_num
1950 || !tcall->queue_item_header.next) {
1951 MUTEX_EXIT(&rx_pthread_mutex);
1952 /* If we're the fcfs thread, then we'll just use
1953 * this call. If we haven't been able to find an optimal
1954 * choice, and we're at the end of the list, then use a
1955 * 2d choice if one has been identified. Otherwise... */
1956 call = (choice2 ? choice2 : tcall);
1957 service = call->conn->service;
1959 MUTEX_EXIT(&rx_pthread_mutex);
1960 if (!queue_IsEmpty(&tcall->rq)) {
1961 struct rx_packet *rp;
1962 rp = queue_First(&tcall->rq, rx_packet);
1963 if (rp->header.seq == 1
1965 || (rp->header.flags & RX_LAST_PACKET))) {
1967 } else if (rxi_2dchoice && !choice2
1968 && !(tcall->flags & RX_CALL_CLEARED)
1969 && (tcall->rprev > rxi_HardAckRate)) {
1983 /* we can't schedule a call if there's no data!!! */
1984 /* send an ack if there's no data, if we're missing the
1985 * first packet, or we're missing something between first
1986 * and last -- there's a "hole" in the incoming data. */
1987 if (queue_IsEmpty(&call->rq)
1988 || queue_First(&call->rq, rx_packet)->header.seq != 1
1989 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1990 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1992 call->flags &= (~RX_CALL_WAIT_PROC);
1993 service->nRequestsRunning++;
1994 /* just started call in minProcs pool, need fewer to maintain
1996 MUTEX_ENTER(&rx_quota_mutex);
1997 if (service->nRequestsRunning <= service->minProcs)
2000 MUTEX_EXIT(&rx_quota_mutex);
2001 rx_atomic_dec(&rx_nWaiting);
2002 /* MUTEX_EXIT(&call->lock); */
2004 /* If there are no eligible incoming calls, add this process
2005 * to the idle server queue, to wait for one */
2008 *socketp = OSI_NULLSOCKET;
2010 sq->socketp = socketp;
2011 queue_Append(&rx_idleServerQueue, sq);
2015 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2017 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2018 return (struct rx_call *)0;
2021 } while (!(call = sq->newcall)
2022 && !(socketp && *socketp != OSI_NULLSOCKET));
2024 MUTEX_EXIT(&sq->lock);
2026 MUTEX_ENTER(&freeSQEList_lock);
2027 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2028 rx_FreeSQEList = sq;
2029 MUTEX_EXIT(&freeSQEList_lock);
2032 clock_GetTime(&call->startTime);
2033 call->state = RX_STATE_ACTIVE;
2034 call->mode = RX_MODE_RECEIVING;
2035 #ifdef RX_KERNEL_TRACE
2036 if (ICL_SETACTIVE(afs_iclSetp)) {
2037 int glockOwner = ISAFS_GLOCK();
2040 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2041 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2048 rxi_calltrace(RX_CALL_START, call);
2049 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2050 call->conn->service->servicePort, call->conn->service->serviceId,
2053 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2060 #endif /* RX_ENABLE_LOCKS */
2064 /* Establish a procedure to be called when a packet arrives for a
2065 * call. This routine will be called at most once after each call,
2066 * and will also be called if there is an error condition on the or
2067 * the call is complete. Used by multi rx to build a selection
2068 * function which determines which of several calls is likely to be a
2069 * good one to read from.
2070 * NOTE: the way this is currently implemented it is probably only a
2071 * good idea to (1) use it immediately after a newcall (clients only)
2072 * and (2) only use it once. Other uses currently void your warranty
2075 rx_SetArrivalProc(struct rx_call *call,
2076 void (*proc) (struct rx_call * call,
2079 void * handle, int arg)
2081 call->arrivalProc = proc;
2082 call->arrivalProcHandle = handle;
2083 call->arrivalProcArg = arg;
2086 /* Call is finished (possibly prematurely). Return rc to the peer, if
2087 * appropriate, and return the final error code from the conversation
2091 rx_EndCall(struct rx_call *call, afs_int32 rc)
2093 struct rx_connection *conn = call->conn;
2097 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2098 call, rc, call->error, call->abortCode));
2101 MUTEX_ENTER(&call->lock);
2103 if (rc == 0 && call->error == 0) {
2104 call->abortCode = 0;
2105 call->abortCount = 0;
2108 call->arrivalProc = (void (*)())0;
2109 if (rc && call->error == 0) {
2110 rxi_CallError(call, rc);
2111 call->mode = RX_MODE_ERROR;
2112 /* Send an abort message to the peer if this error code has
2113 * only just been set. If it was set previously, assume the
2114 * peer has already been sent the error code or will request it
2116 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2118 if (conn->type == RX_SERVER_CONNECTION) {
2119 /* Make sure reply or at least dummy reply is sent */
2120 if (call->mode == RX_MODE_RECEIVING) {
2121 MUTEX_EXIT(&call->lock);
2122 rxi_WriteProc(call, 0, 0);
2123 MUTEX_ENTER(&call->lock);
2125 if (call->mode == RX_MODE_SENDING) {
2126 MUTEX_EXIT(&call->lock);
2127 rxi_FlushWrite(call);
2128 MUTEX_ENTER(&call->lock);
2130 rxi_calltrace(RX_CALL_END, call);
2131 /* Call goes to hold state until reply packets are acknowledged */
2132 if (call->tfirst + call->nSoftAcked < call->tnext) {
2133 call->state = RX_STATE_HOLD;
2135 call->state = RX_STATE_DALLY;
2136 rxi_ClearTransmitQueue(call, 0);
2137 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2138 rxevent_Cancel(call->keepAliveEvent, call,
2139 RX_CALL_REFCOUNT_ALIVE);
2141 } else { /* Client connection */
2143 /* Make sure server receives input packets, in the case where
2144 * no reply arguments are expected */
2145 if ((call->mode == RX_MODE_SENDING)
2146 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2147 MUTEX_EXIT(&call->lock);
2148 (void)rxi_ReadProc(call, &dummy, 1);
2149 MUTEX_ENTER(&call->lock);
2152 /* If we had an outstanding delayed ack, be nice to the server
2153 * and force-send it now.
2155 if (call->delayedAckEvent) {
2156 rxevent_Cancel(call->delayedAckEvent, call,
2157 RX_CALL_REFCOUNT_DELAY);
2158 call->delayedAckEvent = NULL;
2159 rxi_SendDelayedAck(NULL, call, NULL);
2162 /* We need to release the call lock since it's lower than the
2163 * conn_call_lock and we don't want to hold the conn_call_lock
2164 * over the rx_ReadProc call. The conn_call_lock needs to be held
2165 * here for the case where rx_NewCall is perusing the calls on
2166 * the connection structure. We don't want to signal until
2167 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2168 * have checked this call, found it active and by the time it
2169 * goes to sleep, will have missed the signal.
2171 MUTEX_EXIT(&call->lock);
2172 MUTEX_ENTER(&conn->conn_call_lock);
2173 MUTEX_ENTER(&call->lock);
2174 MUTEX_ENTER(&conn->conn_data_lock);
2175 conn->flags |= RX_CONN_BUSY;
2176 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2177 MUTEX_EXIT(&conn->conn_data_lock);
2178 #ifdef RX_ENABLE_LOCKS
2179 CV_BROADCAST(&conn->conn_call_cv);
2184 #ifdef RX_ENABLE_LOCKS
2186 MUTEX_EXIT(&conn->conn_data_lock);
2188 #endif /* RX_ENABLE_LOCKS */
2189 call->state = RX_STATE_DALLY;
2191 error = call->error;
2193 /* currentPacket, nLeft, and NFree must be zeroed here, because
2194 * ResetCall cannot: ResetCall may be called at splnet(), in the
2195 * kernel version, and may interrupt the macros rx_Read or
2196 * rx_Write, which run at normal priority for efficiency. */
2197 if (call->currentPacket) {
2198 #ifdef RX_TRACK_PACKETS
2199 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2201 rxi_FreePacket(call->currentPacket);
2202 call->currentPacket = (struct rx_packet *)0;
2205 call->nLeft = call->nFree = call->curlen = 0;
2207 /* Free any packets from the last call to ReadvProc/WritevProc */
2208 #ifdef RXDEBUG_PACKET
2210 #endif /* RXDEBUG_PACKET */
2211 rxi_FreePackets(0, &call->iovq);
2212 MUTEX_EXIT(&call->lock);
2214 MUTEX_ENTER(&rx_refcnt_mutex);
2215 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2216 MUTEX_EXIT(&rx_refcnt_mutex);
2217 if (conn->type == RX_CLIENT_CONNECTION) {
2218 MUTEX_ENTER(&conn->conn_data_lock);
2219 conn->flags &= ~RX_CONN_BUSY;
2220 MUTEX_EXIT(&conn->conn_data_lock);
2221 MUTEX_EXIT(&conn->conn_call_lock);
2225 * Map errors to the local host's errno.h format.
2227 error = ntoh_syserr_conv(error);
2231 #if !defined(KERNEL)
2233 /* Call this routine when shutting down a server or client (especially
2234 * clients). This will allow Rx to gracefully garbage collect server
2235 * connections, and reduce the number of retries that a server might
2236 * make to a dead client.
2237 * This is not quite right, since some calls may still be ongoing and
2238 * we can't lock them to destroy them. */
2242 struct rx_connection **conn_ptr, **conn_end;
2246 if (rxinit_status == 1) {
2248 return; /* Already shutdown. */
2250 rxi_DeleteCachedConnections();
2251 if (rx_connHashTable) {
2252 MUTEX_ENTER(&rx_connHashTable_lock);
2253 for (conn_ptr = &rx_connHashTable[0], conn_end =
2254 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2256 struct rx_connection *conn, *next;
2257 for (conn = *conn_ptr; conn; conn = next) {
2259 if (conn->type == RX_CLIENT_CONNECTION) {
2260 MUTEX_ENTER(&rx_refcnt_mutex);
2262 MUTEX_EXIT(&rx_refcnt_mutex);
2263 #ifdef RX_ENABLE_LOCKS
2264 rxi_DestroyConnectionNoLock(conn);
2265 #else /* RX_ENABLE_LOCKS */
2266 rxi_DestroyConnection(conn);
2267 #endif /* RX_ENABLE_LOCKS */
2271 #ifdef RX_ENABLE_LOCKS
2272 while (rx_connCleanup_list) {
2273 struct rx_connection *conn;
2274 conn = rx_connCleanup_list;
2275 rx_connCleanup_list = rx_connCleanup_list->next;
2276 MUTEX_EXIT(&rx_connHashTable_lock);
2277 rxi_CleanupConnection(conn);
2278 MUTEX_ENTER(&rx_connHashTable_lock);
2280 MUTEX_EXIT(&rx_connHashTable_lock);
2281 #endif /* RX_ENABLE_LOCKS */
2286 afs_winsockCleanup();
2294 /* if we wakeup packet waiter too often, can get in loop with two
2295 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2297 rxi_PacketsUnWait(void)
2299 if (!rx_waitingForPackets) {
2303 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2304 return; /* still over quota */
2307 rx_waitingForPackets = 0;
2308 #ifdef RX_ENABLE_LOCKS
2309 CV_BROADCAST(&rx_waitingForPackets_cv);
2311 osi_rxWakeup(&rx_waitingForPackets);
2317 /* ------------------Internal interfaces------------------------- */
2319 /* Return this process's service structure for the
2320 * specified socket and service */
2322 rxi_FindService(osi_socket socket, u_short serviceId)
2324 struct rx_service **sp;
2325 for (sp = &rx_services[0]; *sp; sp++) {
2326 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2332 #ifdef RXDEBUG_PACKET
2333 #ifdef KDUMP_RX_LOCK
2334 static struct rx_call_rx_lock *rx_allCallsp = 0;
2336 static struct rx_call *rx_allCallsp = 0;
2338 #endif /* RXDEBUG_PACKET */
2340 /* Allocate a call structure, for the indicated channel of the
2341 * supplied connection. The mode and state of the call must be set by
2342 * the caller. Returns the call with mutex locked. */
2344 rxi_NewCall(struct rx_connection *conn, int channel)
2346 struct rx_call *call;
2347 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2348 struct rx_call *cp; /* Call pointer temp */
2349 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2350 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2352 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2354 /* Grab an existing call structure, or allocate a new one.
2355 * Existing call structures are assumed to have been left reset by
2357 MUTEX_ENTER(&rx_freeCallQueue_lock);
2359 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2361 * EXCEPT that the TQ might not yet be cleared out.
2362 * Skip over those with in-use TQs.
2365 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2366 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2372 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2373 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2374 call = queue_First(&rx_freeCallQueue, rx_call);
2375 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2377 if (rx_stats_active)
2378 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2379 MUTEX_EXIT(&rx_freeCallQueue_lock);
2380 MUTEX_ENTER(&call->lock);
2381 CLEAR_CALL_QUEUE_LOCK(call);
2382 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2383 /* Now, if TQ wasn't cleared earlier, do it now. */
2384 rxi_WaitforTQBusy(call);
2385 if (call->flags & RX_CALL_TQ_CLEARME) {
2386 rxi_ClearTransmitQueue(call, 1);
2387 /*queue_Init(&call->tq);*/
2389 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2390 /* Bind the call to its connection structure */
2392 rxi_ResetCall(call, 1);
2395 call = rxi_Alloc(sizeof(struct rx_call));
2396 #ifdef RXDEBUG_PACKET
2397 call->allNextp = rx_allCallsp;
2398 rx_allCallsp = call;
2400 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2401 #else /* RXDEBUG_PACKET */
2402 rx_atomic_inc(&rx_stats.nCallStructs);
2403 #endif /* RXDEBUG_PACKET */
2405 MUTEX_EXIT(&rx_freeCallQueue_lock);
2406 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2407 MUTEX_ENTER(&call->lock);
2408 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2409 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2410 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2412 /* Initialize once-only items */
2413 queue_Init(&call->tq);
2414 queue_Init(&call->rq);
2415 queue_Init(&call->iovq);
2416 #ifdef RXDEBUG_PACKET
2417 call->rqc = call->tqc = call->iovqc = 0;
2418 #endif /* RXDEBUG_PACKET */
2419 /* Bind the call to its connection structure (prereq for reset) */
2421 rxi_ResetCall(call, 1);
2423 call->channel = channel;
2424 call->callNumber = &conn->callNumber[channel];
2425 call->rwind = conn->rwind[channel];
2426 call->twind = conn->twind[channel];
2427 /* Note that the next expected call number is retained (in
2428 * conn->callNumber[i]), even if we reallocate the call structure
2430 conn->call[channel] = call;
2431 /* if the channel's never been used (== 0), we should start at 1, otherwise
2432 * the call number is valid from the last time this channel was used */
2433 if (*call->callNumber == 0)
2434 *call->callNumber = 1;
2439 /* A call has been inactive long enough that so we can throw away
2440 * state, including the call structure, which is placed on the call
2443 * call->lock amd rx_refcnt_mutex are held upon entry.
2444 * haveCTLock is set when called from rxi_ReapConnections.
2447 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2449 int channel = call->channel;
2450 struct rx_connection *conn = call->conn;
2453 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2454 (*call->callNumber)++;
2456 * We are setting the state to RX_STATE_RESET to
2457 * ensure that no one else will attempt to use this
2458 * call once we drop the refcnt lock. We must drop
2459 * the refcnt lock before calling rxi_ResetCall
2460 * because it cannot be held across acquiring the
2461 * freepktQ lock. NewCall does the same.
2463 call->state = RX_STATE_RESET;
2464 MUTEX_EXIT(&rx_refcnt_mutex);
2465 rxi_ResetCall(call, 0);
2466 call->conn->call[channel] = (struct rx_call *)0;
2468 MUTEX_ENTER(&rx_freeCallQueue_lock);
2469 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2470 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2471 /* A call may be free even though its transmit queue is still in use.
2472 * Since we search the call list from head to tail, put busy calls at
2473 * the head of the list, and idle calls at the tail.
2475 if (call->flags & RX_CALL_TQ_BUSY)
2476 queue_Prepend(&rx_freeCallQueue, call);
2478 queue_Append(&rx_freeCallQueue, call);
2479 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2480 queue_Append(&rx_freeCallQueue, call);
2481 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2482 if (rx_stats_active)
2483 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2484 MUTEX_EXIT(&rx_freeCallQueue_lock);
2486 /* Destroy the connection if it was previously slated for
2487 * destruction, i.e. the Rx client code previously called
2488 * rx_DestroyConnection (client connections), or
2489 * rxi_ReapConnections called the same routine (server
2490 * connections). Only do this, however, if there are no
2491 * outstanding calls. Note that for fine grain locking, there appears
2492 * to be a deadlock in that rxi_FreeCall has a call locked and
2493 * DestroyConnectionNoLock locks each call in the conn. But note a
2494 * few lines up where we have removed this call from the conn.
2495 * If someone else destroys a connection, they either have no
2496 * call lock held or are going through this section of code.
2498 MUTEX_ENTER(&conn->conn_data_lock);
2499 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2500 MUTEX_ENTER(&rx_refcnt_mutex);
2502 MUTEX_EXIT(&rx_refcnt_mutex);
2503 MUTEX_EXIT(&conn->conn_data_lock);
2504 #ifdef RX_ENABLE_LOCKS
2506 rxi_DestroyConnectionNoLock(conn);
2508 rxi_DestroyConnection(conn);
2509 #else /* RX_ENABLE_LOCKS */
2510 rxi_DestroyConnection(conn);
2511 #endif /* RX_ENABLE_LOCKS */
2513 MUTEX_EXIT(&conn->conn_data_lock);
2515 MUTEX_ENTER(&rx_refcnt_mutex);
2518 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2519 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2522 rxi_Alloc(size_t size)
2526 if (rx_stats_active) {
2527 rx_atomic_add(&rxi_Allocsize, (int) size);
2528 rx_atomic_inc(&rxi_Alloccnt);
2532 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2533 afs_osi_Alloc_NoSleep(size);
2538 osi_Panic("rxi_Alloc error");
2544 rxi_Free(void *addr, size_t size)
2546 if (rx_stats_active) {
2547 rx_atomic_sub(&rxi_Allocsize, (int) size);
2548 rx_atomic_dec(&rxi_Alloccnt);
2550 osi_Free(addr, size);
2554 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2556 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2557 struct rx_peer *next = NULL;
2561 MUTEX_ENTER(&rx_peerHashTable_lock);
2563 peer_ptr = &rx_peerHashTable[0];
2564 peer_end = &rx_peerHashTable[rx_hashTableSize];
2567 for ( ; peer_ptr < peer_end; peer_ptr++) {
2570 for ( ; peer; peer = next) {
2572 if (host == peer->host)
2577 hashIndex = PEER_HASH(host, port);
2578 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2579 if ((peer->host == host) && (peer->port == port))
2584 MUTEX_ENTER(&rx_peerHashTable_lock);
2589 MUTEX_EXIT(&rx_peerHashTable_lock);
2591 MUTEX_ENTER(&peer->peer_lock);
2592 /* We don't handle dropping below min, so don't */
2593 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2594 peer->ifMTU=MIN(mtu, peer->ifMTU);
2595 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2596 /* if we tweaked this down, need to tune our peer MTU too */
2597 peer->MTU = MIN(peer->MTU, peer->natMTU);
2598 /* if we discovered a sub-1500 mtu, degrade */
2599 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2600 peer->maxDgramPackets = 1;
2601 /* We no longer have valid peer packet information */
2602 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2603 peer->maxPacketSize = 0;
2604 MUTEX_EXIT(&peer->peer_lock);
2606 MUTEX_ENTER(&rx_peerHashTable_lock);
2608 if (host && !port) {
2610 /* pick up where we left off */
2614 MUTEX_EXIT(&rx_peerHashTable_lock);
2617 /* Find the peer process represented by the supplied (host,port)
2618 * combination. If there is no appropriate active peer structure, a
2619 * new one will be allocated and initialized
2620 * The origPeer, if set, is a pointer to a peer structure on which the
2621 * refcount will be be decremented. This is used to replace the peer
2622 * structure hanging off a connection structure */
2624 rxi_FindPeer(afs_uint32 host, u_short port,
2625 struct rx_peer *origPeer, int create)
2629 hashIndex = PEER_HASH(host, port);
2630 MUTEX_ENTER(&rx_peerHashTable_lock);
2631 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2632 if ((pp->host == host) && (pp->port == port))
2637 pp = rxi_AllocPeer(); /* This bzero's *pp */
2638 pp->host = host; /* set here or in InitPeerParams is zero */
2640 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2641 queue_Init(&pp->congestionQueue);
2642 queue_Init(&pp->rpcStats);
2643 pp->next = rx_peerHashTable[hashIndex];
2644 rx_peerHashTable[hashIndex] = pp;
2645 rxi_InitPeerParams(pp);
2646 if (rx_stats_active)
2647 rx_atomic_inc(&rx_stats.nPeerStructs);
2654 origPeer->refCount--;
2655 MUTEX_EXIT(&rx_peerHashTable_lock);
2660 /* Find the connection at (host, port) started at epoch, and with the
2661 * given connection id. Creates the server connection if necessary.
2662 * The type specifies whether a client connection or a server
2663 * connection is desired. In both cases, (host, port) specify the
2664 * peer's (host, pair) pair. Client connections are not made
2665 * automatically by this routine. The parameter socket gives the
2666 * socket descriptor on which the packet was received. This is used,
2667 * in the case of server connections, to check that *new* connections
2668 * come via a valid (port, serviceId). Finally, the securityIndex
2669 * parameter must match the existing index for the connection. If a
2670 * server connection is created, it will be created using the supplied
2671 * index, if the index is valid for this service */
2672 struct rx_connection *
2673 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2674 u_short port, u_short serviceId, afs_uint32 cid,
2675 afs_uint32 epoch, int type, u_int securityIndex)
2677 int hashindex, flag, i;
2678 struct rx_connection *conn;
2679 hashindex = CONN_HASH(host, port, cid, epoch, type);
2680 MUTEX_ENTER(&rx_connHashTable_lock);
2681 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2682 rx_connHashTable[hashindex],
2685 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2686 && (epoch == conn->epoch)) {
2687 struct rx_peer *pp = conn->peer;
2688 if (securityIndex != conn->securityIndex) {
2689 /* this isn't supposed to happen, but someone could forge a packet
2690 * like this, and there seems to be some CM bug that makes this
2691 * happen from time to time -- in which case, the fileserver
2693 MUTEX_EXIT(&rx_connHashTable_lock);
2694 return (struct rx_connection *)0;
2696 if (pp->host == host && pp->port == port)
2698 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2700 /* So what happens when it's a callback connection? */
2701 if ( /*type == RX_CLIENT_CONNECTION && */
2702 (conn->epoch & 0x80000000))
2706 /* the connection rxLastConn that was used the last time is not the
2707 ** one we are looking for now. Hence, start searching in the hash */
2709 conn = rx_connHashTable[hashindex];
2714 struct rx_service *service;
2715 if (type == RX_CLIENT_CONNECTION) {
2716 MUTEX_EXIT(&rx_connHashTable_lock);
2717 return (struct rx_connection *)0;
2719 service = rxi_FindService(socket, serviceId);
2720 if (!service || (securityIndex >= service->nSecurityObjects)
2721 || (service->securityObjects[securityIndex] == 0)) {
2722 MUTEX_EXIT(&rx_connHashTable_lock);
2723 return (struct rx_connection *)0;
2725 conn = rxi_AllocConnection(); /* This bzero's the connection */
2726 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2727 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2728 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2729 conn->next = rx_connHashTable[hashindex];
2730 rx_connHashTable[hashindex] = conn;
2731 conn->peer = rxi_FindPeer(host, port, 0, 1);
2732 conn->type = RX_SERVER_CONNECTION;
2733 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2734 conn->epoch = epoch;
2735 conn->cid = cid & RX_CIDMASK;
2736 /* conn->serial = conn->lastSerial = 0; */
2737 /* conn->timeout = 0; */
2738 conn->ackRate = RX_FAST_ACK_RATE;
2739 conn->service = service;
2740 conn->serviceId = serviceId;
2741 conn->securityIndex = securityIndex;
2742 conn->securityObject = service->securityObjects[securityIndex];
2743 conn->nSpecific = 0;
2744 conn->specific = NULL;
2745 rx_SetConnDeadTime(conn, service->connDeadTime);
2746 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2747 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2748 for (i = 0; i < RX_MAXCALLS; i++) {
2749 conn->twind[i] = rx_initSendWindow;
2750 conn->rwind[i] = rx_initReceiveWindow;
2752 /* Notify security object of the new connection */
2753 RXS_NewConnection(conn->securityObject, conn);
2754 /* XXXX Connection timeout? */
2755 if (service->newConnProc)
2756 (*service->newConnProc) (conn);
2757 if (rx_stats_active)
2758 rx_atomic_inc(&rx_stats.nServerConns);
2761 MUTEX_ENTER(&rx_refcnt_mutex);
2763 MUTEX_EXIT(&rx_refcnt_mutex);
2765 rxLastConn = conn; /* store this connection as the last conn used */
2766 MUTEX_EXIT(&rx_connHashTable_lock);
2770 /* There are two packet tracing routines available for testing and monitoring
2771 * Rx. One is called just after every packet is received and the other is
2772 * called just before every packet is sent. Received packets, have had their
2773 * headers decoded, and packets to be sent have not yet had their headers
2774 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2775 * containing the network address. Both can be modified. The return value, if
2776 * non-zero, indicates that the packet should be dropped. */
2778 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2779 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2781 /* A packet has been received off the interface. Np is the packet, socket is
2782 * the socket number it was received from (useful in determining which service
2783 * this packet corresponds to), and (host, port) reflect the host,port of the
2784 * sender. This call returns the packet to the caller if it is finished with
2785 * it, rather than de-allocating it, just as a small performance hack */
2788 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2789 afs_uint32 host, u_short port, int *tnop,
2790 struct rx_call **newcallp)
2792 struct rx_call *call;
2793 struct rx_connection *conn;
2795 afs_uint32 currentCallNumber;
2801 struct rx_packet *tnp;
2804 /* We don't print out the packet until now because (1) the time may not be
2805 * accurate enough until now in the lwp implementation (rx_Listener only gets
2806 * the time after the packet is read) and (2) from a protocol point of view,
2807 * this is the first time the packet has been seen */
2808 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2809 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2810 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2811 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2812 np->header.epoch, np->header.cid, np->header.callNumber,
2813 np->header.seq, np->header.flags, np));
2816 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2817 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2820 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2821 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2824 /* If an input tracer function is defined, call it with the packet and
2825 * network address. Note this function may modify its arguments. */
2826 if (rx_justReceived) {
2827 struct sockaddr_in addr;
2829 addr.sin_family = AF_INET;
2830 addr.sin_port = port;
2831 addr.sin_addr.s_addr = host;
2832 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2833 addr.sin_len = sizeof(addr);
2834 #endif /* AFS_OSF_ENV */
2835 drop = (*rx_justReceived) (np, &addr);
2836 /* drop packet if return value is non-zero */
2839 port = addr.sin_port; /* in case fcn changed addr */
2840 host = addr.sin_addr.s_addr;
2844 /* If packet was not sent by the client, then *we* must be the client */
2845 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2846 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2848 /* Find the connection (or fabricate one, if we're the server & if
2849 * necessary) associated with this packet */
2851 rxi_FindConnection(socket, host, port, np->header.serviceId,
2852 np->header.cid, np->header.epoch, type,
2853 np->header.securityIndex);
2856 /* If no connection found or fabricated, just ignore the packet.
2857 * (An argument could be made for sending an abort packet for
2862 MUTEX_ENTER(&conn->conn_data_lock);
2863 if (conn->maxSerial < np->header.serial)
2864 conn->maxSerial = np->header.serial;
2865 MUTEX_EXIT(&conn->conn_data_lock);
2867 /* If the connection is in an error state, send an abort packet and ignore
2868 * the incoming packet */
2870 /* Don't respond to an abort packet--we don't want loops! */
2871 MUTEX_ENTER(&conn->conn_data_lock);
2872 if (np->header.type != RX_PACKET_TYPE_ABORT)
2873 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2874 MUTEX_ENTER(&rx_refcnt_mutex);
2876 MUTEX_EXIT(&rx_refcnt_mutex);
2877 MUTEX_EXIT(&conn->conn_data_lock);
2881 /* Check for connection-only requests (i.e. not call specific). */
2882 if (np->header.callNumber == 0) {
2883 switch (np->header.type) {
2884 case RX_PACKET_TYPE_ABORT: {
2885 /* What if the supplied error is zero? */
2886 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2887 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
2888 rxi_ConnectionError(conn, errcode);
2889 MUTEX_ENTER(&rx_refcnt_mutex);
2891 MUTEX_EXIT(&rx_refcnt_mutex);
2894 case RX_PACKET_TYPE_CHALLENGE:
2895 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2896 MUTEX_ENTER(&rx_refcnt_mutex);
2898 MUTEX_EXIT(&rx_refcnt_mutex);
2900 case RX_PACKET_TYPE_RESPONSE:
2901 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2902 MUTEX_ENTER(&rx_refcnt_mutex);
2904 MUTEX_EXIT(&rx_refcnt_mutex);
2906 case RX_PACKET_TYPE_PARAMS:
2907 case RX_PACKET_TYPE_PARAMS + 1:
2908 case RX_PACKET_TYPE_PARAMS + 2:
2909 /* ignore these packet types for now */
2910 MUTEX_ENTER(&rx_refcnt_mutex);
2912 MUTEX_EXIT(&rx_refcnt_mutex);
2917 /* Should not reach here, unless the peer is broken: send an
2919 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2920 MUTEX_ENTER(&conn->conn_data_lock);
2921 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2922 MUTEX_ENTER(&rx_refcnt_mutex);
2924 MUTEX_EXIT(&rx_refcnt_mutex);
2925 MUTEX_EXIT(&conn->conn_data_lock);
2930 channel = np->header.cid & RX_CHANNELMASK;
2931 call = conn->call[channel];
2932 #ifdef RX_ENABLE_LOCKS
2934 MUTEX_ENTER(&call->lock);
2935 /* Test to see if call struct is still attached to conn. */
2936 if (call != conn->call[channel]) {
2938 MUTEX_EXIT(&call->lock);
2939 if (type == RX_SERVER_CONNECTION) {
2940 call = conn->call[channel];
2941 /* If we started with no call attached and there is one now,
2942 * another thread is also running this routine and has gotten
2943 * the connection channel. We should drop this packet in the tests
2944 * below. If there was a call on this connection and it's now
2945 * gone, then we'll be making a new call below.
2946 * If there was previously a call and it's now different then
2947 * the old call was freed and another thread running this routine
2948 * has created a call on this channel. One of these two threads
2949 * has a packet for the old call and the code below handles those
2953 MUTEX_ENTER(&call->lock);
2955 /* This packet can't be for this call. If the new call address is
2956 * 0 then no call is running on this channel. If there is a call
2957 * then, since this is a client connection we're getting data for
2958 * it must be for the previous call.
2960 if (rx_stats_active)
2961 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2962 MUTEX_ENTER(&rx_refcnt_mutex);
2964 MUTEX_EXIT(&rx_refcnt_mutex);
2969 currentCallNumber = conn->callNumber[channel];
2971 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2972 if (np->header.callNumber < currentCallNumber) {
2973 if (rx_stats_active)
2974 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2975 #ifdef RX_ENABLE_LOCKS
2977 MUTEX_EXIT(&call->lock);
2979 MUTEX_ENTER(&rx_refcnt_mutex);
2981 MUTEX_EXIT(&rx_refcnt_mutex);
2985 MUTEX_ENTER(&conn->conn_call_lock);
2986 call = rxi_NewCall(conn, channel);
2987 MUTEX_EXIT(&conn->conn_call_lock);
2988 *call->callNumber = np->header.callNumber;
2990 if (np->header.callNumber == 0)
2991 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",
2992 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2993 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2994 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2996 call->state = RX_STATE_PRECALL;
2997 clock_GetTime(&call->queueTime);
2998 hzero(call->bytesSent);
2999 hzero(call->bytesRcvd);
3001 * If the number of queued calls exceeds the overload
3002 * threshold then abort this call.
3004 if ((rx_BusyThreshold > 0) &&
3005 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3006 struct rx_packet *tp;
3008 rxi_CallError(call, rx_BusyError);
3009 tp = rxi_SendCallAbort(call, np, 1, 0);
3010 MUTEX_EXIT(&call->lock);
3011 MUTEX_ENTER(&rx_refcnt_mutex);
3013 MUTEX_EXIT(&rx_refcnt_mutex);
3014 if (rx_stats_active)
3015 rx_atomic_inc(&rx_stats.nBusies);
3018 rxi_KeepAliveOn(call);
3019 } else if (np->header.callNumber != currentCallNumber) {
3020 /* Wait until the transmit queue is idle before deciding
3021 * whether to reset the current call. Chances are that the
3022 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3025 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3026 if (call->state == RX_STATE_ACTIVE) {
3027 rxi_WaitforTQBusy(call);
3029 * If we entered error state while waiting,
3030 * must call rxi_CallError to permit rxi_ResetCall
3031 * to processed when the tqWaiter count hits zero.
3034 rxi_CallError(call, call->error);
3035 MUTEX_EXIT(&call->lock);
3036 MUTEX_ENTER(&rx_refcnt_mutex);
3038 MUTEX_EXIT(&rx_refcnt_mutex);
3042 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3043 /* If the new call cannot be taken right now send a busy and set
3044 * the error condition in this call, so that it terminates as
3045 * quickly as possible */
3046 if (call->state == RX_STATE_ACTIVE) {
3047 struct rx_packet *tp;
3049 rxi_CallError(call, RX_CALL_DEAD);
3050 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3052 MUTEX_EXIT(&call->lock);
3053 MUTEX_ENTER(&rx_refcnt_mutex);
3055 MUTEX_EXIT(&rx_refcnt_mutex);
3058 rxi_ResetCall(call, 0);
3059 *call->callNumber = np->header.callNumber;
3061 if (np->header.callNumber == 0)
3062 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",
3063 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3064 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3065 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3067 call->state = RX_STATE_PRECALL;
3068 clock_GetTime(&call->queueTime);
3069 hzero(call->bytesSent);
3070 hzero(call->bytesRcvd);
3072 * If the number of queued calls exceeds the overload
3073 * threshold then abort this call.
3075 if ((rx_BusyThreshold > 0) &&
3076 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3077 struct rx_packet *tp;
3079 rxi_CallError(call, rx_BusyError);
3080 tp = rxi_SendCallAbort(call, np, 1, 0);
3081 MUTEX_EXIT(&call->lock);
3082 MUTEX_ENTER(&rx_refcnt_mutex);
3084 MUTEX_EXIT(&rx_refcnt_mutex);
3085 if (rx_stats_active)
3086 rx_atomic_inc(&rx_stats.nBusies);
3089 rxi_KeepAliveOn(call);
3091 /* Continuing call; do nothing here. */
3093 } else { /* we're the client */
3094 /* Ignore all incoming acknowledgements for calls in DALLY state */
3095 if (call && (call->state == RX_STATE_DALLY)
3096 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3097 if (rx_stats_active)
3098 rx_atomic_inc(&rx_stats.ignorePacketDally);
3099 #ifdef RX_ENABLE_LOCKS
3101 MUTEX_EXIT(&call->lock);
3104 MUTEX_ENTER(&rx_refcnt_mutex);
3106 MUTEX_EXIT(&rx_refcnt_mutex);
3110 /* Ignore anything that's not relevant to the current call. If there
3111 * isn't a current call, then no packet is relevant. */
3112 if (!call || (np->header.callNumber != currentCallNumber)) {
3113 if (rx_stats_active)
3114 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3115 #ifdef RX_ENABLE_LOCKS
3117 MUTEX_EXIT(&call->lock);
3120 MUTEX_ENTER(&rx_refcnt_mutex);
3122 MUTEX_EXIT(&rx_refcnt_mutex);
3125 /* If the service security object index stamped in the packet does not
3126 * match the connection's security index, ignore the packet */
3127 if (np->header.securityIndex != conn->securityIndex) {
3128 #ifdef RX_ENABLE_LOCKS
3129 MUTEX_EXIT(&call->lock);
3131 MUTEX_ENTER(&rx_refcnt_mutex);
3133 MUTEX_EXIT(&rx_refcnt_mutex);
3137 /* If we're receiving the response, then all transmit packets are
3138 * implicitly acknowledged. Get rid of them. */
3139 if (np->header.type == RX_PACKET_TYPE_DATA) {
3140 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3141 /* XXX Hack. Because we must release the global rx lock when
3142 * sending packets (osi_NetSend) we drop all acks while we're
3143 * traversing the tq in rxi_Start sending packets out because
3144 * packets may move to the freePacketQueue as result of being here!
3145 * So we drop these packets until we're safely out of the
3146 * traversing. Really ugly!
3147 * For fine grain RX locking, we set the acked field in the
3148 * packets and let rxi_Start remove them from the transmit queue.
3150 if (call->flags & RX_CALL_TQ_BUSY) {
3151 #ifdef RX_ENABLE_LOCKS
3152 rxi_SetAcksInTransmitQueue(call);
3154 MUTEX_ENTER(&rx_refcnt_mutex);
3156 MUTEX_EXIT(&rx_refcnt_mutex);
3157 return np; /* xmitting; drop packet */
3160 rxi_ClearTransmitQueue(call, 0);
3162 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3163 rxi_ClearTransmitQueue(call, 0);
3164 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3166 if (np->header.type == RX_PACKET_TYPE_ACK) {
3167 /* now check to see if this is an ack packet acknowledging that the
3168 * server actually *lost* some hard-acked data. If this happens we
3169 * ignore this packet, as it may indicate that the server restarted in
3170 * the middle of a call. It is also possible that this is an old ack
3171 * packet. We don't abort the connection in this case, because this
3172 * *might* just be an old ack packet. The right way to detect a server
3173 * restart in the midst of a call is to notice that the server epoch
3175 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3176 * XXX unacknowledged. I think that this is off-by-one, but
3177 * XXX I don't dare change it just yet, since it will
3178 * XXX interact badly with the server-restart detection
3179 * XXX code in receiveackpacket. */
3180 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3181 if (rx_stats_active)
3182 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3183 MUTEX_EXIT(&call->lock);
3184 MUTEX_ENTER(&rx_refcnt_mutex);
3186 MUTEX_EXIT(&rx_refcnt_mutex);
3190 } /* else not a data packet */
3193 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3194 /* Set remote user defined status from packet */
3195 call->remoteStatus = np->header.userStatus;
3197 /* Note the gap between the expected next packet and the actual
3198 * packet that arrived, when the new packet has a smaller serial number
3199 * than expected. Rioses frequently reorder packets all by themselves,
3200 * so this will be quite important with very large window sizes.
3201 * Skew is checked against 0 here to avoid any dependence on the type of
3202 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3204 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3205 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3206 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3208 MUTEX_ENTER(&conn->conn_data_lock);
3209 skew = conn->lastSerial - np->header.serial;
3210 conn->lastSerial = np->header.serial;
3211 MUTEX_EXIT(&conn->conn_data_lock);
3213 struct rx_peer *peer;
3215 if (skew > peer->inPacketSkew) {
3216 dpf(("*** In skew changed from %d to %d\n",
3217 peer->inPacketSkew, skew));
3218 peer->inPacketSkew = skew;
3222 /* Now do packet type-specific processing */
3223 switch (np->header.type) {
3224 case RX_PACKET_TYPE_DATA:
3225 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3228 case RX_PACKET_TYPE_ACK:
3229 /* Respond immediately to ack packets requesting acknowledgement
3231 if (np->header.flags & RX_REQUEST_ACK) {
3233 (void)rxi_SendCallAbort(call, 0, 1, 0);
3235 (void)rxi_SendAck(call, 0, np->header.serial,
3236 RX_ACK_PING_RESPONSE, 1);
3238 np = rxi_ReceiveAckPacket(call, np, 1);
3240 case RX_PACKET_TYPE_ABORT: {
3241 /* An abort packet: reset the call, passing the error up to the user. */
3242 /* What if error is zero? */
3243 /* What if the error is -1? the application will treat it as a timeout. */
3244 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3245 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3246 rxi_CallError(call, errdata);
3247 MUTEX_EXIT(&call->lock);
3248 MUTEX_ENTER(&rx_refcnt_mutex);
3250 MUTEX_EXIT(&rx_refcnt_mutex);
3251 return np; /* xmitting; drop packet */
3253 case RX_PACKET_TYPE_BUSY:
3256 case RX_PACKET_TYPE_ACKALL:
3257 /* All packets acknowledged, so we can drop all packets previously
3258 * readied for sending */
3259 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3260 /* XXX Hack. We because we can't release the global rx lock when
3261 * sending packets (osi_NetSend) we drop all ack pkts while we're
3262 * traversing the tq in rxi_Start sending packets out because
3263 * packets may move to the freePacketQueue as result of being
3264 * here! So we drop these packets until we're safely out of the
3265 * traversing. Really ugly!
3266 * For fine grain RX locking, we set the acked field in the packets
3267 * and let rxi_Start remove the packets from the transmit queue.
3269 if (call->flags & RX_CALL_TQ_BUSY) {
3270 #ifdef RX_ENABLE_LOCKS
3271 rxi_SetAcksInTransmitQueue(call);
3273 #else /* RX_ENABLE_LOCKS */
3274 MUTEX_EXIT(&call->lock);
3275 MUTEX_ENTER(&rx_refcnt_mutex);
3277 MUTEX_EXIT(&rx_refcnt_mutex);
3278 return np; /* xmitting; drop packet */
3279 #endif /* RX_ENABLE_LOCKS */
3281 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3282 rxi_ClearTransmitQueue(call, 0);
3283 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3286 /* Should not reach here, unless the peer is broken: send an abort
3288 rxi_CallError(call, RX_PROTOCOL_ERROR);
3289 np = rxi_SendCallAbort(call, np, 1, 0);
3292 /* Note when this last legitimate packet was received, for keep-alive
3293 * processing. Note, we delay getting the time until now in the hope that
3294 * the packet will be delivered to the user before any get time is required
3295 * (if not, then the time won't actually be re-evaluated here). */
3296 call->lastReceiveTime = clock_Sec();
3297 MUTEX_EXIT(&call->lock);
3298 MUTEX_ENTER(&rx_refcnt_mutex);
3300 MUTEX_EXIT(&rx_refcnt_mutex);
3304 /* return true if this is an "interesting" connection from the point of view
3305 of someone trying to debug the system */
3307 rxi_IsConnInteresting(struct rx_connection *aconn)
3310 struct rx_call *tcall;
3312 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3315 for (i = 0; i < RX_MAXCALLS; i++) {
3316 tcall = aconn->call[i];
3318 if ((tcall->state == RX_STATE_PRECALL)
3319 || (tcall->state == RX_STATE_ACTIVE))
3321 if ((tcall->mode == RX_MODE_SENDING)
3322 || (tcall->mode == RX_MODE_RECEIVING))
3330 /* if this is one of the last few packets AND it wouldn't be used by the
3331 receiving call to immediately satisfy a read request, then drop it on
3332 the floor, since accepting it might prevent a lock-holding thread from
3333 making progress in its reading. If a call has been cleared while in
3334 the precall state then ignore all subsequent packets until the call
3335 is assigned to a thread. */
3338 TooLow(struct rx_packet *ap, struct rx_call *acall)
3342 MUTEX_ENTER(&rx_quota_mutex);
3343 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3344 && (acall->state == RX_STATE_PRECALL))
3345 || ((rx_nFreePackets < rxi_dataQuota + 2)
3346 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3347 && (acall->flags & RX_CALL_READER_WAIT)))) {
3350 MUTEX_EXIT(&rx_quota_mutex);
3356 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3358 struct rx_connection *conn = arg1;
3359 struct rx_call *acall = arg2;
3360 struct rx_call *call = acall;
3361 struct clock when, now;
3364 MUTEX_ENTER(&conn->conn_data_lock);
3365 conn->checkReachEvent = NULL;
3366 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3368 MUTEX_ENTER(&rx_refcnt_mutex);
3370 MUTEX_EXIT(&rx_refcnt_mutex);
3372 MUTEX_EXIT(&conn->conn_data_lock);
3376 MUTEX_ENTER(&conn->conn_call_lock);
3377 MUTEX_ENTER(&conn->conn_data_lock);
3378 for (i = 0; i < RX_MAXCALLS; i++) {
3379 struct rx_call *tc = conn->call[i];
3380 if (tc && tc->state == RX_STATE_PRECALL) {
3386 /* Indicate that rxi_CheckReachEvent is no longer running by
3387 * clearing the flag. Must be atomic under conn_data_lock to
3388 * avoid a new call slipping by: rxi_CheckConnReach holds
3389 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3391 conn->flags &= ~RX_CONN_ATTACHWAIT;
3392 MUTEX_EXIT(&conn->conn_data_lock);
3393 MUTEX_EXIT(&conn->conn_call_lock);
3398 MUTEX_ENTER(&call->lock);
3399 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3401 MUTEX_EXIT(&call->lock);
3403 clock_GetTime(&now);
3405 when.sec += RX_CHECKREACH_TIMEOUT;
3406 MUTEX_ENTER(&conn->conn_data_lock);
3407 if (!conn->checkReachEvent) {
3408 MUTEX_ENTER(&rx_refcnt_mutex);
3410 MUTEX_EXIT(&rx_refcnt_mutex);
3411 conn->checkReachEvent =
3412 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3415 MUTEX_EXIT(&conn->conn_data_lock);
3421 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3423 struct rx_service *service = conn->service;
3424 struct rx_peer *peer = conn->peer;
3425 afs_uint32 now, lastReach;
3427 if (service->checkReach == 0)
3431 MUTEX_ENTER(&peer->peer_lock);
3432 lastReach = peer->lastReachTime;
3433 MUTEX_EXIT(&peer->peer_lock);
3434 if (now - lastReach < RX_CHECKREACH_TTL)
3437 MUTEX_ENTER(&conn->conn_data_lock);
3438 if (conn->flags & RX_CONN_ATTACHWAIT) {
3439 MUTEX_EXIT(&conn->conn_data_lock);
3442 conn->flags |= RX_CONN_ATTACHWAIT;
3443 MUTEX_EXIT(&conn->conn_data_lock);
3444 if (!conn->checkReachEvent)
3445 rxi_CheckReachEvent(NULL, conn, call);
3450 /* try to attach call, if authentication is complete */
3452 TryAttach(struct rx_call *acall, osi_socket socket,
3453 int *tnop, struct rx_call **newcallp,
3456 struct rx_connection *conn = acall->conn;
3458 if (conn->type == RX_SERVER_CONNECTION
3459 && acall->state == RX_STATE_PRECALL) {
3460 /* Don't attach until we have any req'd. authentication. */
3461 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3462 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3463 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3464 /* Note: this does not necessarily succeed; there
3465 * may not any proc available
3468 rxi_ChallengeOn(acall->conn);
3473 /* A data packet has been received off the interface. This packet is
3474 * appropriate to the call (the call is in the right state, etc.). This
3475 * routine can return a packet to the caller, for re-use */
3478 rxi_ReceiveDataPacket(struct rx_call *call,
3479 struct rx_packet *np, int istack,
3480 osi_socket socket, afs_uint32 host, u_short port,
3481 int *tnop, struct rx_call **newcallp)
3483 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3488 afs_uint32 serial=0, flags=0;
3490 struct rx_packet *tnp;
3491 struct clock when, now;
3492 if (rx_stats_active)
3493 rx_atomic_inc(&rx_stats.dataPacketsRead);
3496 /* If there are no packet buffers, drop this new packet, unless we can find
3497 * packet buffers from inactive calls */
3499 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3500 MUTEX_ENTER(&rx_freePktQ_lock);
3501 rxi_NeedMorePackets = TRUE;
3502 MUTEX_EXIT(&rx_freePktQ_lock);
3503 if (rx_stats_active)
3504 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3505 call->rprev = np->header.serial;
3506 rxi_calltrace(RX_TRACE_DROP, call);
3507 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3509 rxi_ClearReceiveQueue(call);
3510 clock_GetTime(&now);
3512 clock_Add(&when, &rx_softAckDelay);
3513 if (!call->delayedAckEvent
3514 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3515 rxevent_Cancel(call->delayedAckEvent, call,
3516 RX_CALL_REFCOUNT_DELAY);
3517 MUTEX_ENTER(&rx_refcnt_mutex);
3518 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3519 MUTEX_EXIT(&rx_refcnt_mutex);
3521 call->delayedAckEvent =
3522 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3524 /* we've damaged this call already, might as well do it in. */
3530 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3531 * packet is one of several packets transmitted as a single
3532 * datagram. Do not send any soft or hard acks until all packets
3533 * in a jumbogram have been processed. Send negative acks right away.
3535 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3536 /* tnp is non-null when there are more packets in the
3537 * current jumbo gram */
3544 seq = np->header.seq;
3545 serial = np->header.serial;
3546 flags = np->header.flags;
3548 /* If the call is in an error state, send an abort message */
3550 return rxi_SendCallAbort(call, np, istack, 0);
3552 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3553 * AFS 3.5 jumbogram. */
3554 if (flags & RX_JUMBO_PACKET) {
3555 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3560 if (np->header.spare != 0) {
3561 MUTEX_ENTER(&call->conn->conn_data_lock);
3562 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3563 MUTEX_EXIT(&call->conn->conn_data_lock);
3566 /* The usual case is that this is the expected next packet */
3567 if (seq == call->rnext) {
3569 /* Check to make sure it is not a duplicate of one already queued */
3570 if (queue_IsNotEmpty(&call->rq)
3571 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3572 if (rx_stats_active)
3573 rx_atomic_inc(&rx_stats.dupPacketsRead);
3574 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3575 rxevent_Cancel(call->delayedAckEvent, call,
3576 RX_CALL_REFCOUNT_DELAY);
3577 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3583 /* It's the next packet. Stick it on the receive queue
3584 * for this call. Set newPackets to make sure we wake
3585 * the reader once all packets have been processed */
3586 #ifdef RX_TRACK_PACKETS
3587 np->flags |= RX_PKTFLAG_RQ;
3589 queue_Prepend(&call->rq, np);
3590 #ifdef RXDEBUG_PACKET
3592 #endif /* RXDEBUG_PACKET */
3594 np = NULL; /* We can't use this anymore */
3597 /* If an ack is requested then set a flag to make sure we
3598 * send an acknowledgement for this packet */
3599 if (flags & RX_REQUEST_ACK) {
3600 ackNeeded = RX_ACK_REQUESTED;
3603 /* Keep track of whether we have received the last packet */
3604 if (flags & RX_LAST_PACKET) {
3605 call->flags |= RX_CALL_HAVE_LAST;
3609 /* Check whether we have all of the packets for this call */
3610 if (call->flags & RX_CALL_HAVE_LAST) {
3611 afs_uint32 tseq; /* temporary sequence number */
3612 struct rx_packet *tp; /* Temporary packet pointer */
3613 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3615 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3616 if (tseq != tp->header.seq)
3618 if (tp->header.flags & RX_LAST_PACKET) {
3619 call->flags |= RX_CALL_RECEIVE_DONE;
3626 /* Provide asynchronous notification for those who want it
3627 * (e.g. multi rx) */
3628 if (call->arrivalProc) {
3629 (*call->arrivalProc) (call, call->arrivalProcHandle,
3630 call->arrivalProcArg);
3631 call->arrivalProc = (void (*)())0;
3634 /* Update last packet received */
3637 /* If there is no server process serving this call, grab
3638 * one, if available. We only need to do this once. If a
3639 * server thread is available, this thread becomes a server
3640 * thread and the server thread becomes a listener thread. */
3642 TryAttach(call, socket, tnop, newcallp, 0);
3645 /* This is not the expected next packet. */
3647 /* Determine whether this is a new or old packet, and if it's
3648 * a new one, whether it fits into the current receive window.
3649 * Also figure out whether the packet was delivered in sequence.
3650 * We use the prev variable to determine whether the new packet
3651 * is the successor of its immediate predecessor in the
3652 * receive queue, and the missing flag to determine whether
3653 * any of this packets predecessors are missing. */
3655 afs_uint32 prev; /* "Previous packet" sequence number */
3656 struct rx_packet *tp; /* Temporary packet pointer */
3657 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3658 int missing; /* Are any predecessors missing? */
3660 /* If the new packet's sequence number has been sent to the
3661 * application already, then this is a duplicate */
3662 if (seq < call->rnext) {
3663 if (rx_stats_active)
3664 rx_atomic_inc(&rx_stats.dupPacketsRead);
3665 rxevent_Cancel(call->delayedAckEvent, call,
3666 RX_CALL_REFCOUNT_DELAY);
3667 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3673 /* If the sequence number is greater than what can be
3674 * accomodated by the current window, then send a negative
3675 * acknowledge and drop the packet */
3676 if ((call->rnext + call->rwind) <= seq) {
3677 rxevent_Cancel(call->delayedAckEvent, call,
3678 RX_CALL_REFCOUNT_DELAY);
3679 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3686 /* Look for the packet in the queue of old received packets */
3687 for (prev = call->rnext - 1, missing =
3688 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3689 /*Check for duplicate packet */
3690 if (seq == tp->header.seq) {
3691 if (rx_stats_active)
3692 rx_atomic_inc(&rx_stats.dupPacketsRead);
3693 rxevent_Cancel(call->delayedAckEvent, call,
3694 RX_CALL_REFCOUNT_DELAY);
3695 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3701 /* If we find a higher sequence packet, break out and
3702 * insert the new packet here. */
3703 if (seq < tp->header.seq)
3705 /* Check for missing packet */
3706 if (tp->header.seq != prev + 1) {
3710 prev = tp->header.seq;
3713 /* Keep track of whether we have received the last packet. */
3714 if (flags & RX_LAST_PACKET) {
3715 call->flags |= RX_CALL_HAVE_LAST;
3718 /* It's within the window: add it to the the receive queue.
3719 * tp is left by the previous loop either pointing at the
3720 * packet before which to insert the new packet, or at the
3721 * queue head if the queue is empty or the packet should be
3723 #ifdef RX_TRACK_PACKETS
3724 np->flags |= RX_PKTFLAG_RQ;
3726 #ifdef RXDEBUG_PACKET
3728 #endif /* RXDEBUG_PACKET */
3729 queue_InsertBefore(tp, np);
3733 /* Check whether we have all of the packets for this call */
3734 if ((call->flags & RX_CALL_HAVE_LAST)
3735 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3736 afs_uint32 tseq; /* temporary sequence number */
3739 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3740 if (tseq != tp->header.seq)
3742 if (tp->header.flags & RX_LAST_PACKET) {
3743 call->flags |= RX_CALL_RECEIVE_DONE;
3750 /* We need to send an ack of the packet is out of sequence,
3751 * or if an ack was requested by the peer. */
3752 if (seq != prev + 1 || missing) {
3753 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3754 } else if (flags & RX_REQUEST_ACK) {
3755 ackNeeded = RX_ACK_REQUESTED;
3758 /* Acknowledge the last packet for each call */
3759 if (flags & RX_LAST_PACKET) {
3770 * If the receiver is waiting for an iovec, fill the iovec
3771 * using the data from the receive queue */
3772 if (call->flags & RX_CALL_IOVEC_WAIT) {
3773 didHardAck = rxi_FillReadVec(call, serial);
3774 /* the call may have been aborted */
3783 /* Wakeup the reader if any */
3784 if ((call->flags & RX_CALL_READER_WAIT)
3785 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3786 || (call->iovNext >= call->iovMax)
3787 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3788 call->flags &= ~RX_CALL_READER_WAIT;
3789 #ifdef RX_ENABLE_LOCKS
3790 CV_BROADCAST(&call->cv_rq);
3792 osi_rxWakeup(&call->rq);
3798 * Send an ack when requested by the peer, or once every
3799 * rxi_SoftAckRate packets until the last packet has been
3800 * received. Always send a soft ack for the last packet in
3801 * the server's reply.
3803 * If we have received all of the packets for the call
3804 * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3805 * the peer can empty its packet queue and cancel all resend
3808 if (call->flags & RX_CALL_RECEIVE_DONE) {
3809 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3810 rxi_AckAll(NULL, call, 0);
3811 } else if (ackNeeded) {
3812 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3813 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3814 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3815 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3816 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3817 } else if (call->nSoftAcks) {
3818 clock_GetTime(&now);
3820 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3821 clock_Add(&when, &rx_lastAckDelay);
3823 clock_Add(&when, &rx_softAckDelay);
3825 if (!call->delayedAckEvent
3826 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3827 rxevent_Cancel(call->delayedAckEvent, call,
3828 RX_CALL_REFCOUNT_DELAY);
3829 MUTEX_ENTER(&rx_refcnt_mutex);
3830 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3831 MUTEX_EXIT(&rx_refcnt_mutex);
3832 call->delayedAckEvent =
3833 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3841 static void rxi_ComputeRate();
3845 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3847 struct rx_peer *peer = conn->peer;
3849 MUTEX_ENTER(&peer->peer_lock);
3850 peer->lastReachTime = clock_Sec();
3851 MUTEX_EXIT(&peer->peer_lock);
3853 MUTEX_ENTER(&conn->conn_data_lock);
3854 if (conn->flags & RX_CONN_ATTACHWAIT) {
3857 conn->flags &= ~RX_CONN_ATTACHWAIT;
3858 MUTEX_EXIT(&conn->conn_data_lock);
3860 for (i = 0; i < RX_MAXCALLS; i++) {
3861 struct rx_call *call = conn->call[i];
3864 MUTEX_ENTER(&call->lock);
3865 /* tnop can be null if newcallp is null */
3866 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3868 MUTEX_EXIT(&call->lock);
3872 MUTEX_EXIT(&conn->conn_data_lock);
3875 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3877 rx_ack_reason(int reason)
3880 case RX_ACK_REQUESTED:
3882 case RX_ACK_DUPLICATE:
3884 case RX_ACK_OUT_OF_SEQUENCE:
3886 case RX_ACK_EXCEEDS_WINDOW:
3888 case RX_ACK_NOSPACE:
3892 case RX_ACK_PING_RESPONSE:
3905 /* The real smarts of the whole thing. */
3907 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3910 struct rx_ackPacket *ap;
3912 struct rx_packet *tp;
3913 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3914 struct rx_connection *conn = call->conn;
3915 struct rx_peer *peer = conn->peer;
3916 struct clock now; /* Current time, for RTT calculations */
3920 /* because there are CM's that are bogus, sending weird values for this. */
3921 afs_uint32 skew = 0;
3926 int newAckCount = 0;
3927 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3928 int pktsize = 0; /* Set if we need to update the peer mtu */
3929 int conn_data_locked = 0;
3931 if (rx_stats_active)
3932 rx_atomic_inc(&rx_stats.ackPacketsRead);
3933 ap = (struct rx_ackPacket *)rx_DataOf(np);
3934 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3936 return np; /* truncated ack packet */
3938 /* depends on ack packet struct */
3939 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3940 first = ntohl(ap->firstPacket);
3941 prev = ntohl(ap->previousPacket);
3942 serial = ntohl(ap->serial);
3943 /* temporarily disabled -- needs to degrade over time
3944 * skew = ntohs(ap->maxSkew); */
3946 /* Ignore ack packets received out of order */
3947 if (first < call->tfirst ||
3948 (first == call->tfirst && prev < call->tprev)) {
3954 if (np->header.flags & RX_SLOW_START_OK) {
3955 call->flags |= RX_CALL_SLOW_START_OK;
3958 if (ap->reason == RX_ACK_PING_RESPONSE)
3959 rxi_UpdatePeerReach(conn, call);
3961 if (conn->lastPacketSizeSeq) {
3962 MUTEX_ENTER(&conn->conn_data_lock);
3963 conn_data_locked = 1;
3964 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
3965 pktsize = conn->lastPacketSize;
3966 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
3969 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
3970 if (!conn_data_locked) {
3971 MUTEX_ENTER(&conn->conn_data_lock);
3972 conn_data_locked = 1;
3974 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
3975 /* process mtu ping ack */
3976 pktsize = conn->lastPingSize;
3977 conn->lastPingSizeSer = conn->lastPingSize = 0;
3981 if (conn_data_locked) {
3982 MUTEX_EXIT(&conn->conn_data_lock);
3983 conn_data_locked = 0;
3987 if (rxdebug_active) {
3991 len = _snprintf(msg, sizeof(msg),
3992 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3993 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3994 ntohl(ap->serial), ntohl(ap->previousPacket),
3995 (unsigned int)np->header.seq, (unsigned int)skew,
3996 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4000 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4001 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4005 OutputDebugString(msg);
4007 #else /* AFS_NT40_ENV */
4010 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4011 ap->reason, ntohl(ap->previousPacket),
4012 (unsigned int)np->header.seq, (unsigned int)serial,
4013 (unsigned int)skew, ntohl(ap->firstPacket));
4016 for (offset = 0; offset < nAcks; offset++)
4017 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4022 #endif /* AFS_NT40_ENV */
4025 MUTEX_ENTER(&peer->peer_lock);
4028 * Start somewhere. Can't assume we can send what we can receive,
4029 * but we are clearly receiving.
4031 if (!peer->maxPacketSize)
4032 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4034 if (pktsize > peer->maxPacketSize) {
4035 peer->maxPacketSize = pktsize;
4036 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4037 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4038 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4039 rxi_ScheduleGrowMTUEvent(call, 1);
4044 /* Update the outgoing packet skew value to the latest value of
4045 * the peer's incoming packet skew value. The ack packet, of
4046 * course, could arrive out of order, but that won't affect things
4048 peer->outPacketSkew = skew;
4050 /* Check for packets that no longer need to be transmitted, and
4051 * discard them. This only applies to packets positively
4052 * acknowledged as having been sent to the peer's upper level.
4053 * All other packets must be retained. So only packets with
4054 * sequence numbers < ap->firstPacket are candidates. */
4056 clock_GetTime(&now);
4058 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4059 if (tp->header.seq >= first)
4061 call->tfirst = tp->header.seq + 1;
4063 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4066 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4070 rxi_ComputeRate(call->conn->peer, call, p, np, ap->reason);
4073 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4074 /* XXX Hack. Because we have to release the global rx lock when sending
4075 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4076 * in rxi_Start sending packets out because packets may move to the
4077 * freePacketQueue as result of being here! So we drop these packets until
4078 * we're safely out of the traversing. Really ugly!
4079 * To make it even uglier, if we're using fine grain locking, we can
4080 * set the ack bits in the packets and have rxi_Start remove the packets
4081 * when it's done transmitting.
4083 if (call->flags & RX_CALL_TQ_BUSY) {
4084 #ifdef RX_ENABLE_LOCKS
4085 tp->flags |= RX_PKTFLAG_ACKED;
4086 call->flags |= RX_CALL_TQ_SOME_ACKED;
4087 #else /* RX_ENABLE_LOCKS */
4089 #endif /* RX_ENABLE_LOCKS */
4091 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4094 #ifdef RX_TRACK_PACKETS
4095 tp->flags &= ~RX_PKTFLAG_TQ;
4097 #ifdef RXDEBUG_PACKET
4099 #endif /* RXDEBUG_PACKET */
4100 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4105 /* Give rate detector a chance to respond to ping requests */
4106 if (ap->reason == RX_ACK_PING_RESPONSE) {
4107 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4111 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4113 /* Now go through explicit acks/nacks and record the results in
4114 * the waiting packets. These are packets that can't be released
4115 * yet, even with a positive acknowledge. This positive
4116 * acknowledge only means the packet has been received by the
4117 * peer, not that it will be retained long enough to be sent to
4118 * the peer's upper level. In addition, reset the transmit timers
4119 * of any missing packets (those packets that must be missing
4120 * because this packet was out of sequence) */
4122 call->nSoftAcked = 0;
4123 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4125 /* Set the acknowledge flag per packet based on the
4126 * information in the ack packet. An acknowlegded packet can
4127 * be downgraded when the server has discarded a packet it
4128 * soacked previously, or when an ack packet is received
4129 * out of sequence. */
4130 if (tp->header.seq < first) {
4131 /* Implicit ack information */
4132 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4135 tp->flags |= RX_PKTFLAG_ACKED;
4136 } else if (tp->header.seq < first + nAcks) {
4137 /* Explicit ack information: set it in the packet appropriately */
4138 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4139 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4141 tp->flags |= RX_PKTFLAG_ACKED;
4143 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4145 rxi_ComputeRate(call->conn->peer, call, tp, np,
4154 } else /* RX_ACK_TYPE_NACK */ {
4155 tp->flags &= ~RX_PKTFLAG_ACKED;
4159 if (tp->flags & RX_PKTFLAG_ACKED) {
4160 tp->flags &= ~RX_PKTFLAG_ACKED;
4166 * Following the suggestion of Phil Kern, we back off the peer's
4167 * timeout value for future packets until a successful response
4168 * is received for an initial transmission.
4170 if (missing && !peer->backedOff) {
4171 struct clock c = peer->timeout;
4172 struct clock max_to = {3, 0};
4174 clock_Add(&peer->timeout, &c);
4175 if (clock_Gt(&peer->timeout, &max_to))
4176 peer->timeout = max_to;
4177 peer->backedOff = 1;
4180 /* If packet isn't yet acked, and it has been transmitted at least
4181 * once, reset retransmit time using latest timeout
4182 * ie, this should readjust the retransmit timer for all outstanding
4183 * packets... So we don't just retransmit when we should know better*/
4185 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4186 tp->retryTime = tp->timeSent;
4187 clock_Add(&tp->retryTime, &peer->timeout);
4188 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4189 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4193 /* If the window has been extended by this acknowledge packet,
4194 * then wakeup a sender waiting in alloc for window space, or try
4195 * sending packets now, if he's been sitting on packets due to
4196 * lack of window space */
4197 if (call->tnext < (call->tfirst + call->twind)) {
4198 #ifdef RX_ENABLE_LOCKS
4199 CV_SIGNAL(&call->cv_twind);
4201 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4202 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4203 osi_rxWakeup(&call->twind);
4206 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4207 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4211 /* if the ack packet has a receivelen field hanging off it,
4212 * update our state */
4213 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4216 /* If the ack packet has a "recommended" size that is less than
4217 * what I am using now, reduce my size to match */
4218 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4219 (int)sizeof(afs_int32), &tSize);
4220 tSize = (afs_uint32) ntohl(tSize);
4221 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4223 /* Get the maximum packet size to send to this peer */
4224 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4226 tSize = (afs_uint32) ntohl(tSize);
4227 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4228 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4230 /* sanity check - peer might have restarted with different params.
4231 * If peer says "send less", dammit, send less... Peer should never
4232 * be unable to accept packets of the size that prior AFS versions would
4233 * send without asking. */
4234 if (peer->maxMTU != tSize) {
4235 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4237 peer->maxMTU = tSize;
4238 peer->MTU = MIN(tSize, peer->MTU);
4239 call->MTU = MIN(call->MTU, tSize);
4242 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4245 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4246 (int)sizeof(afs_int32), &tSize);
4247 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4248 if (tSize < call->twind) { /* smaller than our send */
4249 call->twind = tSize; /* window, we must send less... */
4250 call->ssthresh = MIN(call->twind, call->ssthresh);
4251 call->conn->twind[call->channel] = call->twind;
4254 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4255 * network MTU confused with the loopback MTU. Calculate the
4256 * maximum MTU here for use in the slow start code below.
4258 /* Did peer restart with older RX version? */
4259 if (peer->maxDgramPackets > 1) {
4260 peer->maxDgramPackets = 1;
4262 } else if (np->length >=
4263 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4266 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4267 sizeof(afs_int32), &tSize);
4268 tSize = (afs_uint32) ntohl(tSize);
4270 * As of AFS 3.5 we set the send window to match the receive window.
4272 if (tSize < call->twind) {
4273 call->twind = tSize;
4274 call->conn->twind[call->channel] = call->twind;
4275 call->ssthresh = MIN(call->twind, call->ssthresh);
4276 } else if (tSize > call->twind) {
4277 call->twind = tSize;
4278 call->conn->twind[call->channel] = call->twind;
4282 * As of AFS 3.5, a jumbogram is more than one fixed size
4283 * packet transmitted in a single UDP datagram. If the remote
4284 * MTU is smaller than our local MTU then never send a datagram
4285 * larger than the natural MTU.
4288 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4289 (int)sizeof(afs_int32), &tSize);
4290 maxDgramPackets = (afs_uint32) ntohl(tSize);
4291 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4293 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4294 if (maxDgramPackets > 1) {
4295 peer->maxDgramPackets = maxDgramPackets;
4296 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4298 peer->maxDgramPackets = 1;
4299 call->MTU = peer->natMTU;
4301 } else if (peer->maxDgramPackets > 1) {
4302 /* Restarted with lower version of RX */
4303 peer->maxDgramPackets = 1;
4305 } else if (peer->maxDgramPackets > 1
4306 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4307 /* Restarted with lower version of RX */
4308 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4309 peer->natMTU = OLD_MAX_PACKET_SIZE;
4310 peer->MTU = OLD_MAX_PACKET_SIZE;
4311 peer->maxDgramPackets = 1;
4312 peer->nDgramPackets = 1;
4314 call->MTU = OLD_MAX_PACKET_SIZE;
4319 * Calculate how many datagrams were successfully received after
4320 * the first missing packet and adjust the negative ack counter
4325 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4326 if (call->nNacks < nNacked) {
4327 call->nNacks = nNacked;
4330 call->nAcks += newAckCount;
4334 if (call->flags & RX_CALL_FAST_RECOVER) {
4336 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4338 call->flags &= ~RX_CALL_FAST_RECOVER;
4339 call->cwind = call->nextCwind;
4340 call->nextCwind = 0;
4343 call->nCwindAcks = 0;
4344 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4345 /* Three negative acks in a row trigger congestion recovery */
4346 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4347 MUTEX_EXIT(&peer->peer_lock);
4348 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4349 /* someone else is waiting to start recovery */
4352 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4353 rxi_WaitforTQBusy(call);
4354 MUTEX_ENTER(&peer->peer_lock);
4355 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4356 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4357 call->flags |= RX_CALL_FAST_RECOVER;
4358 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4360 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4361 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4362 call->nextCwind = call->ssthresh;
4365 peer->MTU = call->MTU;
4366 peer->cwind = call->nextCwind;
4367 peer->nDgramPackets = call->nDgramPackets;
4369 call->congestSeq = peer->congestSeq;
4370 /* Reset the resend times on the packets that were nacked
4371 * so we will retransmit as soon as the window permits*/
4372 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4374 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4375 clock_Zero(&tp->retryTime);
4377 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4382 /* If cwind is smaller than ssthresh, then increase
4383 * the window one packet for each ack we receive (exponential
4385 * If cwind is greater than or equal to ssthresh then increase
4386 * the congestion window by one packet for each cwind acks we
4387 * receive (linear growth). */
4388 if (call->cwind < call->ssthresh) {
4390 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4391 call->nCwindAcks = 0;
4393 call->nCwindAcks += newAckCount;
4394 if (call->nCwindAcks >= call->cwind) {
4395 call->nCwindAcks = 0;
4396 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4400 * If we have received several acknowledgements in a row then
4401 * it is time to increase the size of our datagrams
4403 if ((int)call->nAcks > rx_nDgramThreshold) {
4404 if (peer->maxDgramPackets > 1) {
4405 if (call->nDgramPackets < peer->maxDgramPackets) {
4406 call->nDgramPackets++;
4408 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4409 } else if (call->MTU < peer->maxMTU) {
4410 /* don't upgrade if we can't handle it */
4411 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4412 call->MTU = peer->ifMTU;
4414 call->MTU += peer->natMTU;
4415 call->MTU = MIN(call->MTU, peer->maxMTU);
4422 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4424 /* Servers need to hold the call until all response packets have
4425 * been acknowledged. Soft acks are good enough since clients
4426 * are not allowed to clear their receive queues. */
4427 if (call->state == RX_STATE_HOLD
4428 && call->tfirst + call->nSoftAcked >= call->tnext) {
4429 call->state = RX_STATE_DALLY;
4430 rxi_ClearTransmitQueue(call, 0);
4431 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4432 } else if (!queue_IsEmpty(&call->tq)) {
4433 rxi_Start(0, call, 0, istack);
4438 /* Received a response to a challenge packet */
4440 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4441 struct rx_packet *np, int istack)
4445 /* Ignore the packet if we're the client */
4446 if (conn->type == RX_CLIENT_CONNECTION)
4449 /* If already authenticated, ignore the packet (it's probably a retry) */
4450 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4453 /* Otherwise, have the security object evaluate the response packet */
4454 error = RXS_CheckResponse(conn->securityObject, conn, np);
4456 /* If the response is invalid, reset the connection, sending
4457 * an abort to the peer */
4461 rxi_ConnectionError(conn, error);
4462 MUTEX_ENTER(&conn->conn_data_lock);
4463 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4464 MUTEX_EXIT(&conn->conn_data_lock);
4467 /* If the response is valid, any calls waiting to attach
4468 * servers can now do so */
4471 for (i = 0; i < RX_MAXCALLS; i++) {
4472 struct rx_call *call = conn->call[i];
4474 MUTEX_ENTER(&call->lock);
4475 if (call->state == RX_STATE_PRECALL)
4476 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4477 /* tnop can be null if newcallp is null */
4478 MUTEX_EXIT(&call->lock);
4482 /* Update the peer reachability information, just in case
4483 * some calls went into attach-wait while we were waiting
4484 * for authentication..
4486 rxi_UpdatePeerReach(conn, NULL);
4491 /* A client has received an authentication challenge: the security
4492 * object is asked to cough up a respectable response packet to send
4493 * back to the server. The server is responsible for retrying the
4494 * challenge if it fails to get a response. */
4497 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4498 struct rx_packet *np, int istack)
4502 /* Ignore the challenge if we're the server */
4503 if (conn->type == RX_SERVER_CONNECTION)
4506 /* Ignore the challenge if the connection is otherwise idle; someone's
4507 * trying to use us as an oracle. */
4508 if (!rxi_HasActiveCalls(conn))
4511 /* Send the security object the challenge packet. It is expected to fill
4512 * in the response. */
4513 error = RXS_GetResponse(conn->securityObject, conn, np);
4515 /* If the security object is unable to return a valid response, reset the
4516 * connection and send an abort to the peer. Otherwise send the response
4517 * packet to the peer connection. */
4519 rxi_ConnectionError(conn, error);
4520 MUTEX_ENTER(&conn->conn_data_lock);
4521 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4522 MUTEX_EXIT(&conn->conn_data_lock);
4524 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4525 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4531 /* Find an available server process to service the current request in
4532 * the given call structure. If one isn't available, queue up this
4533 * call so it eventually gets one */
4535 rxi_AttachServerProc(struct rx_call *call,
4536 osi_socket socket, int *tnop,
4537 struct rx_call **newcallp)
4539 struct rx_serverQueueEntry *sq;
4540 struct rx_service *service = call->conn->service;
4543 /* May already be attached */
4544 if (call->state == RX_STATE_ACTIVE)
4547 MUTEX_ENTER(&rx_serverPool_lock);
4549 haveQuota = QuotaOK(service);
4550 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4551 /* If there are no processes available to service this call,
4552 * put the call on the incoming call queue (unless it's
4553 * already on the queue).
4555 #ifdef RX_ENABLE_LOCKS
4557 ReturnToServerPool(service);
4558 #endif /* RX_ENABLE_LOCKS */
4560 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4561 call->flags |= RX_CALL_WAIT_PROC;
4562 rx_atomic_inc(&rx_nWaiting);
4563 rx_atomic_inc(&rx_nWaited);
4564 rxi_calltrace(RX_CALL_ARRIVAL, call);
4565 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4566 queue_Append(&rx_incomingCallQueue, call);
4569 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4571 /* If hot threads are enabled, and both newcallp and sq->socketp
4572 * are non-null, then this thread will process the call, and the
4573 * idle server thread will start listening on this threads socket.
4576 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4579 *sq->socketp = socket;
4580 clock_GetTime(&call->startTime);
4581 MUTEX_ENTER(&rx_refcnt_mutex);
4582 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4583 MUTEX_EXIT(&rx_refcnt_mutex);
4587 if (call->flags & RX_CALL_WAIT_PROC) {
4588 /* Conservative: I don't think this should happen */
4589 call->flags &= ~RX_CALL_WAIT_PROC;
4590 if (queue_IsOnQueue(call)) {
4593 rx_atomic_dec(&rx_nWaiting);
4596 call->state = RX_STATE_ACTIVE;
4597 call->mode = RX_MODE_RECEIVING;
4598 #ifdef RX_KERNEL_TRACE
4600 int glockOwner = ISAFS_GLOCK();
4603 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4604 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4610 if (call->flags & RX_CALL_CLEARED) {
4611 /* send an ack now to start the packet flow up again */
4612 call->flags &= ~RX_CALL_CLEARED;
4613 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4615 #ifdef RX_ENABLE_LOCKS
4618 service->nRequestsRunning++;
4619 MUTEX_ENTER(&rx_quota_mutex);
4620 if (service->nRequestsRunning <= service->minProcs)
4623 MUTEX_EXIT(&rx_quota_mutex);
4627 MUTEX_EXIT(&rx_serverPool_lock);
4630 /* Delay the sending of an acknowledge event for a short while, while
4631 * a new call is being prepared (in the case of a client) or a reply
4632 * is being prepared (in the case of a server). Rather than sending
4633 * an ack packet, an ACKALL packet is sent. */
4635 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4637 #ifdef RX_ENABLE_LOCKS
4639 MUTEX_ENTER(&call->lock);
4640 call->delayedAckEvent = NULL;
4641 MUTEX_ENTER(&rx_refcnt_mutex);
4642 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4643 MUTEX_EXIT(&rx_refcnt_mutex);
4645 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4646 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4648 MUTEX_EXIT(&call->lock);
4649 #else /* RX_ENABLE_LOCKS */
4651 call->delayedAckEvent = NULL;
4652 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4653 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4654 #endif /* RX_ENABLE_LOCKS */
4658 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4660 struct rx_call *call = arg1;
4661 #ifdef RX_ENABLE_LOCKS
4663 MUTEX_ENTER(&call->lock);
4664 if (event == call->delayedAckEvent)
4665 call->delayedAckEvent = NULL;
4666 MUTEX_ENTER(&rx_refcnt_mutex);
4667 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4668 MUTEX_EXIT(&rx_refcnt_mutex);
4670 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4672 MUTEX_EXIT(&call->lock);
4673 #else /* RX_ENABLE_LOCKS */
4675 call->delayedAckEvent = NULL;
4676 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4677 #endif /* RX_ENABLE_LOCKS */
4681 #ifdef RX_ENABLE_LOCKS
4682 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4683 * clearing them out.
4686 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4688 struct rx_packet *p, *tp;
4691 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4692 p->flags |= RX_PKTFLAG_ACKED;
4696 call->flags |= RX_CALL_TQ_CLEARME;
4697 call->flags |= RX_CALL_TQ_SOME_ACKED;
4700 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4701 call->tfirst = call->tnext;
4702 call->nSoftAcked = 0;
4704 if (call->flags & RX_CALL_FAST_RECOVER) {
4705 call->flags &= ~RX_CALL_FAST_RECOVER;
4706 call->cwind = call->nextCwind;
4707 call->nextCwind = 0;
4710 CV_SIGNAL(&call->cv_twind);
4712 #endif /* RX_ENABLE_LOCKS */
4714 /* Clear out the transmit queue for the current call (all packets have
4715 * been received by peer) */
4717 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4719 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4720 struct rx_packet *p, *tp;
4722 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4724 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4725 p->flags |= RX_PKTFLAG_ACKED;
4729 call->flags |= RX_CALL_TQ_CLEARME;
4730 call->flags |= RX_CALL_TQ_SOME_ACKED;
4733 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4734 #ifdef RXDEBUG_PACKET
4736 #endif /* RXDEBUG_PACKET */
4737 rxi_FreePackets(0, &call->tq);
4738 rxi_WakeUpTransmitQueue(call);
4739 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4740 call->flags &= ~RX_CALL_TQ_CLEARME;
4742 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4744 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4745 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4746 call->nSoftAcked = 0;
4748 if (call->flags & RX_CALL_FAST_RECOVER) {
4749 call->flags &= ~RX_CALL_FAST_RECOVER;
4750 call->cwind = call->nextCwind;
4752 #ifdef RX_ENABLE_LOCKS
4753 CV_SIGNAL(&call->cv_twind);
4755 osi_rxWakeup(&call->twind);
4760 rxi_ClearReceiveQueue(struct rx_call *call)
4762 if (queue_IsNotEmpty(&call->rq)) {
4765 count = rxi_FreePackets(0, &call->rq);
4766 rx_packetReclaims += count;
4767 #ifdef RXDEBUG_PACKET
4769 if ( call->rqc != 0 )
4770 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
4772 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4774 if (call->state == RX_STATE_PRECALL) {
4775 call->flags |= RX_CALL_CLEARED;
4779 /* Send an abort packet for the specified call */
4781 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4782 int istack, int force)
4785 struct clock when, now;
4790 /* Clients should never delay abort messages */
4791 if (rx_IsClientConn(call->conn))
4794 if (call->abortCode != call->error) {
4795 call->abortCode = call->error;
4796 call->abortCount = 0;
4799 if (force || rxi_callAbortThreshhold == 0
4800 || call->abortCount < rxi_callAbortThreshhold) {
4801 if (call->delayedAbortEvent) {
4802 rxevent_Cancel(call->delayedAbortEvent, call,
4803 RX_CALL_REFCOUNT_ABORT);
4805 error = htonl(call->error);
4808 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4809 (char *)&error, sizeof(error), istack);
4810 } else if (!call->delayedAbortEvent) {
4811 clock_GetTime(&now);
4813 clock_Addmsec(&when, rxi_callAbortDelay);
4814 MUTEX_ENTER(&rx_refcnt_mutex);
4815 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4816 MUTEX_EXIT(&rx_refcnt_mutex);
4817 call->delayedAbortEvent =
4818 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4823 /* Send an abort packet for the specified connection. Packet is an
4824 * optional pointer to a packet that can be used to send the abort.
4825 * Once the number of abort messages reaches the threshhold, an
4826 * event is scheduled to send the abort. Setting the force flag
4827 * overrides sending delayed abort messages.
4829 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4830 * to send the abort packet.
4833 rxi_SendConnectionAbort(struct rx_connection *conn,
4834 struct rx_packet *packet, int istack, int force)
4837 struct clock when, now;
4842 /* Clients should never delay abort messages */
4843 if (rx_IsClientConn(conn))
4846 if (force || rxi_connAbortThreshhold == 0
4847 || conn->abortCount < rxi_connAbortThreshhold) {
4848 if (conn->delayedAbortEvent) {
4849 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4851 error = htonl(conn->error);
4853 MUTEX_EXIT(&conn->conn_data_lock);
4855 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4856 RX_PACKET_TYPE_ABORT, (char *)&error,
4857 sizeof(error), istack);
4858 MUTEX_ENTER(&conn->conn_data_lock);
4859 } else if (!conn->delayedAbortEvent) {
4860 clock_GetTime(&now);
4862 clock_Addmsec(&when, rxi_connAbortDelay);
4863 conn->delayedAbortEvent =
4864 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4869 /* Associate an error all of the calls owned by a connection. Called
4870 * with error non-zero. This is only for really fatal things, like
4871 * bad authentication responses. The connection itself is set in
4872 * error at this point, so that future packets received will be
4875 rxi_ConnectionError(struct rx_connection *conn,
4881 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
4883 MUTEX_ENTER(&conn->conn_data_lock);
4884 if (conn->challengeEvent)
4885 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4886 if (conn->natKeepAliveEvent)
4887 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
4888 if (conn->checkReachEvent) {
4889 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4890 conn->checkReachEvent = 0;
4891 conn->flags &= ~RX_CONN_ATTACHWAIT;
4892 MUTEX_ENTER(&rx_refcnt_mutex);
4894 MUTEX_EXIT(&rx_refcnt_mutex);
4896 MUTEX_EXIT(&conn->conn_data_lock);
4897 for (i = 0; i < RX_MAXCALLS; i++) {
4898 struct rx_call *call = conn->call[i];
4900 MUTEX_ENTER(&call->lock);
4901 rxi_CallError(call, error);
4902 MUTEX_EXIT(&call->lock);
4905 conn->error = error;
4906 if (rx_stats_active)
4907 rx_atomic_inc(&rx_stats.fatalErrors);
4912 * Interrupt an in-progress call with the specified error and wakeup waiters.
4914 * @param[in] call The call to interrupt
4915 * @param[in] error The error code to send to the peer
4918 rx_InterruptCall(struct rx_call *call, afs_int32 error)
4920 MUTEX_ENTER(&call->lock);
4921 rxi_CallError(call, error);
4922 rxi_SendCallAbort(call, NULL, 0, 1);
4923 MUTEX_EXIT(&call->lock);
4927 rxi_CallError(struct rx_call *call, afs_int32 error)
4930 osirx_AssertMine(&call->lock, "rxi_CallError");
4932 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
4934 error = call->error;
4936 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4937 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4938 rxi_ResetCall(call, 0);
4941 rxi_ResetCall(call, 0);
4943 call->error = error;
4946 /* Reset various fields in a call structure, and wakeup waiting
4947 * processes. Some fields aren't changed: state & mode are not
4948 * touched (these must be set by the caller), and bufptr, nLeft, and
4949 * nFree are not reset, since these fields are manipulated by
4950 * unprotected macros, and may only be reset by non-interrupting code.
4953 /* this code requires that call->conn be set properly as a pre-condition. */
4954 #endif /* ADAPT_WINDOW */
4957 rxi_ResetCall(struct rx_call *call, int newcall)
4960 struct rx_peer *peer;
4961 struct rx_packet *packet;
4963 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4965 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
4967 /* Notify anyone who is waiting for asynchronous packet arrival */
4968 if (call->arrivalProc) {
4969 (*call->arrivalProc) (call, call->arrivalProcHandle,
4970 call->arrivalProcArg);
4971 call->arrivalProc = (void (*)())0;
4974 if (call->delayedAbortEvent) {
4975 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4976 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4978 rxi_SendCallAbort(call, packet, 0, 1);
4979 rxi_FreePacket(packet);
4984 * Update the peer with the congestion information in this call
4985 * so other calls on this connection can pick up where this call
4986 * left off. If the congestion sequence numbers don't match then
4987 * another call experienced a retransmission.
4989 peer = call->conn->peer;
4990 MUTEX_ENTER(&peer->peer_lock);
4992 if (call->congestSeq == peer->congestSeq) {
4993 peer->cwind = MAX(peer->cwind, call->cwind);
4994 peer->MTU = MAX(peer->MTU, call->MTU);
4995 peer->nDgramPackets =
4996 MAX(peer->nDgramPackets, call->nDgramPackets);
4999 call->abortCode = 0;
5000 call->abortCount = 0;
5002 if (peer->maxDgramPackets > 1) {
5003 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5005 call->MTU = peer->MTU;
5007 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5008 call->ssthresh = rx_maxSendWindow;
5009 call->nDgramPackets = peer->nDgramPackets;
5010 call->congestSeq = peer->congestSeq;
5011 MUTEX_EXIT(&peer->peer_lock);
5013 flags = call->flags;
5014 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5015 rxi_WaitforTQBusy(call);
5016 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5018 rxi_ClearTransmitQueue(call, 1);
5019 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5020 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5024 rxi_ClearReceiveQueue(call);
5025 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5029 call->twind = call->conn->twind[call->channel];
5030 call->rwind = call->conn->rwind[call->channel];
5031 call->nSoftAcked = 0;
5032 call->nextCwind = 0;
5035 call->nCwindAcks = 0;
5036 call->nSoftAcks = 0;
5037 call->nHardAcks = 0;
5039 call->tfirst = call->rnext = call->tnext = 1;
5042 call->lastAcked = 0;
5043 call->localStatus = call->remoteStatus = 0;
5045 if (flags & RX_CALL_READER_WAIT) {
5046 #ifdef RX_ENABLE_LOCKS
5047 CV_BROADCAST(&call->cv_rq);
5049 osi_rxWakeup(&call->rq);
5052 if (flags & RX_CALL_WAIT_PACKETS) {
5053 MUTEX_ENTER(&rx_freePktQ_lock);
5054 rxi_PacketsUnWait(); /* XXX */
5055 MUTEX_EXIT(&rx_freePktQ_lock);
5057 #ifdef RX_ENABLE_LOCKS
5058 CV_SIGNAL(&call->cv_twind);
5060 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5061 osi_rxWakeup(&call->twind);
5064 #ifdef RX_ENABLE_LOCKS
5065 /* The following ensures that we don't mess with any queue while some
5066 * other thread might also be doing so. The call_queue_lock field is
5067 * is only modified under the call lock. If the call is in the process
5068 * of being removed from a queue, the call is not locked until the
5069 * the queue lock is dropped and only then is the call_queue_lock field
5070 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5071 * Note that any other routine which removes a call from a queue has to
5072 * obtain the queue lock before examing the queue and removing the call.
5074 if (call->call_queue_lock) {
5075 MUTEX_ENTER(call->call_queue_lock);
5076 if (queue_IsOnQueue(call)) {
5078 if (flags & RX_CALL_WAIT_PROC) {
5079 rx_atomic_dec(&rx_nWaiting);
5082 MUTEX_EXIT(call->call_queue_lock);
5083 CLEAR_CALL_QUEUE_LOCK(call);
5085 #else /* RX_ENABLE_LOCKS */
5086 if (queue_IsOnQueue(call)) {
5088 if (flags & RX_CALL_WAIT_PROC)
5089 rx_atomic_dec(&rx_nWaiting);
5091 #endif /* RX_ENABLE_LOCKS */
5093 rxi_KeepAliveOff(call);
5094 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5097 /* Send an acknowledge for the indicated packet (seq,serial) of the
5098 * indicated call, for the indicated reason (reason). This
5099 * acknowledge will specifically acknowledge receiving the packet, and
5100 * will also specify which other packets for this call have been
5101 * received. This routine returns the packet that was used to the
5102 * caller. The caller is responsible for freeing it or re-using it.
5103 * This acknowledgement also returns the highest sequence number
5104 * actually read out by the higher level to the sender; the sender
5105 * promises to keep around packets that have not been read by the
5106 * higher level yet (unless, of course, the sender decides to abort
5107 * the call altogether). Any of p, seq, serial, pflags, or reason may
5108 * be set to zero without ill effect. That is, if they are zero, they
5109 * will not convey any information.
5110 * NOW there is a trailer field, after the ack where it will safely be
5111 * ignored by mundanes, which indicates the maximum size packet this
5112 * host can swallow. */
5114 struct rx_packet *optionalPacket; use to send ack (or null)
5115 int seq; Sequence number of the packet we are acking
5116 int serial; Serial number of the packet
5117 int pflags; Flags field from packet header
5118 int reason; Reason an acknowledge was prompted
5122 rxi_SendAck(struct rx_call *call,
5123 struct rx_packet *optionalPacket, int serial, int reason,
5126 struct rx_ackPacket *ap;
5127 struct rx_packet *rqp;
5128 struct rx_packet *nxp; /* For queue_Scan */
5129 struct rx_packet *p;
5132 afs_uint32 padbytes = 0;
5133 #ifdef RX_ENABLE_TSFPQ
5134 struct rx_ts_info_t * rx_ts_info;
5138 * Open the receive window once a thread starts reading packets
5140 if (call->rnext > 1) {
5141 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5144 /* Don't attempt to grow MTU if this is a critical ping */
5145 if (reason == RX_ACK_MTU) {
5146 /* keep track of per-call attempts, if we're over max, do in small
5147 * otherwise in larger? set a size to increment by, decrease
5150 if (call->conn->peer->maxPacketSize &&
5151 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5153 padbytes = call->conn->peer->maxPacketSize+16;
5155 padbytes = call->conn->peer->maxMTU + 128;
5157 /* do always try a minimum size ping */
5158 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5160 /* subtract the ack payload */
5161 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5162 reason = RX_ACK_PING;
5165 call->nHardAcks = 0;
5166 call->nSoftAcks = 0;
5167 if (call->rnext > call->lastAcked)
5168 call->lastAcked = call->rnext;
5172 rx_computelen(p, p->length); /* reset length, you never know */
5173 } /* where that's been... */
5174 #ifdef RX_ENABLE_TSFPQ
5176 RX_TS_INFO_GET(rx_ts_info);
5177 if ((p = rx_ts_info->local_special_packet)) {
5178 rx_computelen(p, p->length);
5179 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5180 rx_ts_info->local_special_packet = p;
5181 } else { /* We won't send the ack, but don't panic. */
5182 return optionalPacket;
5186 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5187 /* We won't send the ack, but don't panic. */
5188 return optionalPacket;
5193 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5196 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5197 #ifndef RX_ENABLE_TSFPQ
5198 if (!optionalPacket)
5201 return optionalPacket;
5203 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5204 if (rx_Contiguous(p) < templ) {
5205 #ifndef RX_ENABLE_TSFPQ
5206 if (!optionalPacket)
5209 return optionalPacket;
5214 /* MTUXXX failing to send an ack is very serious. We should */
5215 /* try as hard as possible to send even a partial ack; it's */
5216 /* better than nothing. */
5217 ap = (struct rx_ackPacket *)rx_DataOf(p);
5218 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5219 ap->reason = reason;
5221 /* The skew computation used to be bogus, I think it's better now. */
5222 /* We should start paying attention to skew. XXX */
5223 ap->serial = htonl(serial);
5224 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5226 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5227 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5229 /* No fear of running out of ack packet here because there can only be at most
5230 * one window full of unacknowledged packets. The window size must be constrained
5231 * to be less than the maximum ack size, of course. Also, an ack should always
5232 * fit into a single packet -- it should not ever be fragmented. */
5233 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5234 if (!rqp || !call->rq.next
5235 || (rqp->header.seq > (call->rnext + call->rwind))) {
5236 #ifndef RX_ENABLE_TSFPQ
5237 if (!optionalPacket)
5240 rxi_CallError(call, RX_CALL_DEAD);
5241 return optionalPacket;
5244 while (rqp->header.seq > call->rnext + offset)
5245 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5246 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5248 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5249 #ifndef RX_ENABLE_TSFPQ
5250 if (!optionalPacket)
5253 rxi_CallError(call, RX_CALL_DEAD);
5254 return optionalPacket;
5259 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5261 /* these are new for AFS 3.3 */
5262 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5263 templ = htonl(templ);
5264 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5265 templ = htonl(call->conn->peer->ifMTU);
5266 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5267 sizeof(afs_int32), &templ);
5269 /* new for AFS 3.4 */
5270 templ = htonl(call->rwind);
5271 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5272 sizeof(afs_int32), &templ);
5274 /* new for AFS 3.5 */
5275 templ = htonl(call->conn->peer->ifDgramPackets);
5276 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5277 sizeof(afs_int32), &templ);
5279 p->header.serviceId = call->conn->serviceId;
5280 p->header.cid = (call->conn->cid | call->channel);
5281 p->header.callNumber = *call->callNumber;
5283 p->header.securityIndex = call->conn->securityIndex;
5284 p->header.epoch = call->conn->epoch;
5285 p->header.type = RX_PACKET_TYPE_ACK;
5286 p->header.flags = RX_SLOW_START_OK;
5287 if (reason == RX_ACK_PING) {
5288 p->header.flags |= RX_REQUEST_ACK;
5290 clock_GetTime(&call->pingRequestTime);
5293 p->length = padbytes +
5294 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5297 /* not fast but we can potentially use this if truncated
5298 * fragments are delivered to figure out the mtu.
5300 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5301 sizeof(afs_int32), sizeof(afs_int32),
5305 if (call->conn->type == RX_CLIENT_CONNECTION)
5306 p->header.flags |= RX_CLIENT_INITIATED;
5310 if (rxdebug_active) {
5314 len = _snprintf(msg, sizeof(msg),
5315 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5316 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5317 ntohl(ap->serial), ntohl(ap->previousPacket),
5318 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5319 ap->nAcks, ntohs(ap->bufferSpace) );
5323 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5324 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5328 OutputDebugString(msg);
5330 #else /* AFS_NT40_ENV */
5332 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5333 ap->reason, ntohl(ap->previousPacket),
5334 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5336 for (offset = 0; offset < ap->nAcks; offset++)
5337 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5342 #endif /* AFS_NT40_ENV */
5345 int i, nbytes = p->length;
5347 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5348 if (nbytes <= p->wirevec[i].iov_len) {
5351 savelen = p->wirevec[i].iov_len;
5353 p->wirevec[i].iov_len = nbytes;
5355 rxi_Send(call, p, istack);
5356 p->wirevec[i].iov_len = savelen;
5360 nbytes -= p->wirevec[i].iov_len;
5363 if (rx_stats_active)
5364 rx_atomic_inc(&rx_stats.ackPacketsSent);
5365 #ifndef RX_ENABLE_TSFPQ
5366 if (!optionalPacket)
5369 return optionalPacket; /* Return packet for re-use by caller */
5373 struct rx_packet **list;
5378 /* Send all of the packets in the list in single datagram */
5380 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5381 int istack, int moreFlag)
5386 struct clock now, retryTime;
5387 struct rx_connection *conn = call->conn;
5388 struct rx_peer *peer = conn->peer;
5390 MUTEX_ENTER(&peer->peer_lock);
5391 peer->nSent += xmit->len;
5392 if (xmit->resending)
5393 peer->reSends += xmit->len;
5394 retryTime = peer->timeout;
5395 MUTEX_EXIT(&peer->peer_lock);
5397 if (rx_stats_active) {
5398 if (xmit->resending)
5399 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5401 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5404 clock_GetTime(&now);
5405 clock_Add(&retryTime, &now);
5407 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5411 /* Set the packet flags and schedule the resend events */
5412 /* Only request an ack for the last packet in the list */
5413 for (i = 0; i < xmit->len; i++) {
5414 struct rx_packet *packet = xmit->list[i];
5416 packet->retryTime = retryTime;
5417 if (packet->header.serial) {
5418 /* Exponentially backoff retry times */
5419 if (packet->backoff < MAXBACKOFF) {
5420 /* so it can't stay == 0 */
5421 packet->backoff = (packet->backoff << 1) + 1;
5424 clock_Addmsec(&(packet->retryTime),
5425 ((afs_uint32) packet->backoff) << 8);
5428 /* Wait a little extra for the ack on the last packet */
5430 && !(packet->header.flags & RX_CLIENT_INITIATED)) {
5431 clock_Addmsec(&(packet->retryTime), 400);
5434 /* Record the time sent */
5435 packet->timeSent = now;
5437 /* Ask for an ack on retransmitted packets, on every other packet
5438 * if the peer doesn't support slow start. Ask for an ack on every
5439 * packet until the congestion window reaches the ack rate. */
5440 if (packet->header.serial) {
5443 /* improved RTO calculation- not Karn */
5444 packet->firstSent = now;
5445 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5446 || (!(call->flags & RX_CALL_SLOW_START_OK)
5447 && (packet->header.seq & 1)))) {
5452 /* Tag this packet as not being the last in this group,
5453 * for the receiver's benefit */
5454 if (i < xmit->len - 1 || moreFlag) {
5455 packet->header.flags |= RX_MORE_PACKETS;
5460 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5463 /* Since we're about to send a data packet to the peer, it's
5464 * safe to nuke any scheduled end-of-packets ack */
5465 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5467 MUTEX_EXIT(&call->lock);
5468 MUTEX_ENTER(&rx_refcnt_mutex);
5469 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5470 MUTEX_EXIT(&rx_refcnt_mutex);
5471 if (xmit->len > 1) {
5472 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5474 rxi_SendPacket(call, conn, xmit->list[0], istack);
5476 MUTEX_ENTER(&call->lock);
5477 MUTEX_ENTER(&rx_refcnt_mutex);
5478 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5479 MUTEX_EXIT(&rx_refcnt_mutex);
5481 /* Update last send time for this call (for keep-alive
5482 * processing), and for the connection (so that we can discover
5483 * idle connections) */
5484 conn->lastSendTime = call->lastSendTime = clock_Sec();
5485 /* Let a set of retransmits trigger an idle timeout */
5486 if (!xmit->resending)
5487 call->lastSendData = call->lastSendTime;
5490 /* When sending packets we need to follow these rules:
5491 * 1. Never send more than maxDgramPackets in a jumbogram.
5492 * 2. Never send a packet with more than two iovecs in a jumbogram.
5493 * 3. Never send a retransmitted packet in a jumbogram.
5494 * 4. Never send more than cwind/4 packets in a jumbogram
5495 * We always keep the last list we should have sent so we
5496 * can set the RX_MORE_PACKETS flags correctly.
5500 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5504 struct xmitlist working;
5505 struct xmitlist last;
5507 struct rx_peer *peer = call->conn->peer;
5508 int morePackets = 0;
5510 memset(&last, 0, sizeof(struct xmitlist));
5511 working.list = &list[0];
5513 working.resending = 0;
5515 for (i = 0; i < len; i++) {
5516 /* Does the current packet force us to flush the current list? */
5518 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5519 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5521 /* This sends the 'last' list and then rolls the current working
5522 * set into the 'last' one, and resets the working set */
5525 rxi_SendList(call, &last, istack, 1);
5526 /* If the call enters an error state stop sending, or if
5527 * we entered congestion recovery mode, stop sending */
5528 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5533 working.resending = 0;
5534 working.list = &list[i];
5536 /* Add the current packet to the list if it hasn't been acked.
5537 * Otherwise adjust the list pointer to skip the current packet. */
5538 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5541 if (list[i]->header.serial)
5542 working.resending = 1;
5544 /* Do we need to flush the list? */
5545 if (working.len >= (int)peer->maxDgramPackets
5546 || working.len >= (int)call->nDgramPackets
5547 || working.len >= (int)call->cwind
5548 || list[i]->header.serial
5549 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5551 rxi_SendList(call, &last, istack, 1);
5552 /* If the call enters an error state stop sending, or if
5553 * we entered congestion recovery mode, stop sending */
5555 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5560 working.resending = 0;
5561 working.list = &list[i + 1];
5564 if (working.len != 0) {
5565 osi_Panic("rxi_SendList error");
5567 working.list = &list[i + 1];
5571 /* Send the whole list when the call is in receive mode, when
5572 * the call is in eof mode, when we are in fast recovery mode,
5573 * and when we have the last packet */
5574 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5575 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5576 || (call->flags & RX_CALL_FAST_RECOVER)) {
5577 /* Check for the case where the current list contains
5578 * an acked packet. Since we always send retransmissions
5579 * in a separate packet, we only need to check the first
5580 * packet in the list */
5581 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5585 rxi_SendList(call, &last, istack, morePackets);
5586 /* If the call enters an error state stop sending, or if
5587 * we entered congestion recovery mode, stop sending */
5588 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5592 rxi_SendList(call, &working, istack, 0);
5594 } else if (last.len > 0) {
5595 rxi_SendList(call, &last, istack, 0);
5596 /* Packets which are in 'working' are not sent by this call */
5600 #ifdef RX_ENABLE_LOCKS
5601 /* Call rxi_Start, below, but with the call lock held. */
5603 rxi_StartUnlocked(struct rxevent *event,
5604 void *arg0, void *arg1, int istack)
5606 struct rx_call *call = arg0;
5608 MUTEX_ENTER(&call->lock);
5609 rxi_Start(event, call, arg1, istack);
5610 MUTEX_EXIT(&call->lock);
5612 #endif /* RX_ENABLE_LOCKS */
5614 /* This routine is called when new packets are readied for
5615 * transmission and when retransmission may be necessary, or when the
5616 * transmission window or burst count are favourable. This should be
5617 * better optimized for new packets, the usual case, now that we've
5618 * got rid of queues of send packets. XXXXXXXXXXX */
5620 rxi_Start(struct rxevent *event,
5621 void *arg0, void *arg1, int istack)
5623 struct rx_call *call = arg0;
5625 struct rx_packet *p;
5626 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5627 struct clock now, usenow, retryTime;
5632 /* If rxi_Start is being called as a result of a resend event,
5633 * then make sure that the event pointer is removed from the call
5634 * structure, since there is no longer a per-call retransmission
5636 if (event && event == call->resendEvent) {
5637 MUTEX_ENTER(&rx_refcnt_mutex);
5638 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5639 MUTEX_EXIT(&rx_refcnt_mutex);
5640 call->resendEvent = NULL;
5641 if (queue_IsEmpty(&call->tq)) {
5648 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5649 if (rx_stats_active)
5650 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5655 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5657 clock_GetTime(&now);
5660 /* Send (or resend) any packets that need it, subject to
5661 * window restrictions and congestion burst control
5662 * restrictions. Ask for an ack on the last packet sent in
5663 * this burst. For now, we're relying upon the window being
5664 * considerably bigger than the largest number of packets that
5665 * are typically sent at once by one initial call to
5666 * rxi_Start. This is probably bogus (perhaps we should ask
5667 * for an ack when we're half way through the current
5668 * window?). Also, for non file transfer applications, this
5669 * may end up asking for an ack for every packet. Bogus. XXXX
5672 * But check whether we're here recursively, and let the other guy
5675 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5676 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5677 call->flags |= RX_CALL_TQ_BUSY;
5679 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5681 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5682 call->flags &= ~RX_CALL_NEED_START;
5683 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5685 maxXmitPackets = MIN(call->twind, call->cwind);
5686 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5687 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5688 /* We shouldn't be sending packets if a thread is waiting
5689 * to initiate congestion recovery */
5690 dpf(("call %d waiting to initiate fast recovery\n",
5691 *(call->callNumber)));
5695 && (call->flags & RX_CALL_FAST_RECOVER)) {
5696 /* Only send one packet during fast recovery */
5697 dpf(("call %d restricted to one packet per send during fast recovery\n",
5698 *(call->callNumber)));
5701 #ifdef RX_TRACK_PACKETS
5702 if ((p->flags & RX_PKTFLAG_FREE)
5703 || (!queue_IsEnd(&call->tq, nxp)
5704 && (nxp->flags & RX_PKTFLAG_FREE))
5705 || (p == (struct rx_packet *)&rx_freePacketQueue)
5706 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5707 osi_Panic("rxi_Start: xmit queue clobbered");
5710 if (p->flags & RX_PKTFLAG_ACKED) {
5711 /* Since we may block, don't trust this */
5712 usenow.sec = usenow.usec = 0;
5713 if (rx_stats_active)
5714 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5715 continue; /* Ignore this packet if it has been acknowledged */
5718 /* Turn off all flags except these ones, which are the same
5719 * on each transmission */
5720 p->header.flags &= RX_PRESET_FLAGS;
5722 if (p->header.seq >=
5723 call->tfirst + MIN((int)call->twind,
5724 (int)(call->nSoftAcked +
5726 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5727 /* Note: if we're waiting for more window space, we can
5728 * still send retransmits; hence we don't return here, but
5729 * break out to schedule a retransmit event */
5730 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5731 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5736 /* Transmit the packet if it needs to be sent. */
5737 if (!clock_Lt(&now, &p->retryTime)) {
5738 if (nXmitPackets == maxXmitPackets) {
5739 rxi_SendXmitList(call, call->xmitList,
5740 nXmitPackets, istack);
5743 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u\n",
5744 *(call->callNumber), p,
5746 p->retryTime.sec, p->retryTime.usec));
5747 call->xmitList[nXmitPackets++] = p;
5751 /* xmitList now hold pointers to all of the packets that are
5752 * ready to send. Now we loop to send the packets */
5753 if (nXmitPackets > 0) {
5754 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
5758 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5760 * TQ references no longer protected by this flag; they must remain
5761 * protected by the global lock.
5763 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5764 call->flags &= ~RX_CALL_TQ_BUSY;
5765 rxi_WakeUpTransmitQueue(call);
5769 /* We went into the error state while sending packets. Now is
5770 * the time to reset the call. This will also inform the using
5771 * process that the call is in an error state.
5773 if (rx_stats_active)
5774 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
5775 call->flags &= ~RX_CALL_TQ_BUSY;
5776 rxi_WakeUpTransmitQueue(call);
5777 rxi_CallError(call, call->error);
5780 #ifdef RX_ENABLE_LOCKS
5781 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5783 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5784 /* Some packets have received acks. If they all have, we can clear
5785 * the transmit queue.
5788 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5789 if (p->header.seq < call->tfirst
5790 && (p->flags & RX_PKTFLAG_ACKED)) {
5792 #ifdef RX_TRACK_PACKETS
5793 p->flags &= ~RX_PKTFLAG_TQ;
5795 #ifdef RXDEBUG_PACKET
5803 call->flags |= RX_CALL_TQ_CLEARME;
5805 #endif /* RX_ENABLE_LOCKS */
5806 /* Don't bother doing retransmits if the TQ is cleared. */
5807 if (call->flags & RX_CALL_TQ_CLEARME) {
5808 rxi_ClearTransmitQueue(call, 1);
5810 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5813 /* Always post a resend event, if there is anything in the
5814 * queue, and resend is possible. There should be at least
5815 * one unacknowledged packet in the queue ... otherwise none
5816 * of these packets should be on the queue in the first place.
5818 if (call->resendEvent) {
5819 /* Cancel the existing event and post a new one */
5820 rxevent_Cancel(call->resendEvent, call,
5821 RX_CALL_REFCOUNT_RESEND);
5824 /* The retry time is the retry time on the first unacknowledged
5825 * packet inside the current window */
5827 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5828 /* Don't set timers for packets outside the window */
5829 if (p->header.seq >= call->tfirst + call->twind) {
5833 if (!(p->flags & RX_PKTFLAG_ACKED)
5834 && !clock_IsZero(&p->retryTime)) {
5836 retryTime = p->retryTime;
5841 /* Post a new event to re-run rxi_Start when retries may be needed */
5842 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5843 #ifdef RX_ENABLE_LOCKS
5844 MUTEX_ENTER(&rx_refcnt_mutex);
5845 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5846 MUTEX_EXIT(&rx_refcnt_mutex);
5848 rxevent_PostNow2(&retryTime, &usenow,
5850 (void *)call, 0, istack);
5851 #else /* RX_ENABLE_LOCKS */
5853 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5854 (void *)call, 0, istack);
5855 #endif /* RX_ENABLE_LOCKS */
5858 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5859 } while (call->flags & RX_CALL_NEED_START);
5861 * TQ references no longer protected by this flag; they must remain
5862 * protected by the global lock.
5864 call->flags &= ~RX_CALL_TQ_BUSY;
5865 rxi_WakeUpTransmitQueue(call);
5867 call->flags |= RX_CALL_NEED_START;
5869 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5871 if (call->resendEvent) {
5872 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5877 /* Also adjusts the keep alive parameters for the call, to reflect
5878 * that we have just sent a packet (so keep alives aren't sent
5881 rxi_Send(struct rx_call *call, struct rx_packet *p,
5884 struct rx_connection *conn = call->conn;
5886 /* Stamp each packet with the user supplied status */
5887 p->header.userStatus = call->localStatus;
5889 /* Allow the security object controlling this call's security to
5890 * make any last-minute changes to the packet */
5891 RXS_SendPacket(conn->securityObject, call, p);
5893 /* Since we're about to send SOME sort of packet to the peer, it's
5894 * safe to nuke any scheduled end-of-packets ack */
5895 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5897 /* Actually send the packet, filling in more connection-specific fields */
5898 MUTEX_EXIT(&call->lock);
5899 MUTEX_ENTER(&rx_refcnt_mutex);
5900 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5901 MUTEX_EXIT(&rx_refcnt_mutex);
5902 rxi_SendPacket(call, conn, p, istack);
5903 MUTEX_ENTER(&rx_refcnt_mutex);
5904 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5905 MUTEX_EXIT(&rx_refcnt_mutex);
5906 MUTEX_ENTER(&call->lock);
5908 /* Update last send time for this call (for keep-alive
5909 * processing), and for the connection (so that we can discover
5910 * idle connections) */
5911 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5912 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
5913 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
5915 conn->lastSendTime = call->lastSendTime = clock_Sec();
5916 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
5917 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5918 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
5919 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
5920 RX_ACK_PING_RESPONSE)))
5921 call->lastSendData = call->lastSendTime;
5925 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5926 * that things are fine. Also called periodically to guarantee that nothing
5927 * falls through the cracks (e.g. (error + dally) connections have keepalive
5928 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5930 * haveCTLock Set if calling from rxi_ReapConnections
5932 #ifdef RX_ENABLE_LOCKS
5934 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5935 #else /* RX_ENABLE_LOCKS */
5937 rxi_CheckCall(struct rx_call *call)
5938 #endif /* RX_ENABLE_LOCKS */
5940 struct rx_connection *conn = call->conn;
5942 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
5943 afs_uint32 fudgeFactor;
5947 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5948 if (call->flags & RX_CALL_TQ_BUSY) {
5949 /* Call is active and will be reset by rxi_Start if it's
5950 * in an error state.
5955 /* RTT + 8*MDEV, rounded up to the next second. */
5956 fudgeFactor = (((afs_uint32) conn->peer->rtt >> 3) +
5957 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5959 deadTime = conn->secondsUntilDead + fudgeFactor;
5961 /* These are computed to the second (+- 1 second). But that's
5962 * good enough for these values, which should be a significant
5963 * number of seconds. */
5964 if (now > (call->lastReceiveTime + deadTime)) {
5965 if (call->state == RX_STATE_ACTIVE) {
5967 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5969 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5970 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5971 ip_stack_t *ipst = ns->netstack_ip;
5973 ire = ire_cache_lookup(conn->peer->host
5974 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5976 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5978 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5985 if (ire && ire->ire_max_frag > 0)
5986 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
5988 #if defined(GLOBAL_NETSTACKID)
5992 #endif /* ADAPT_PMTU */
5993 cerror = RX_CALL_DEAD;
5996 #ifdef RX_ENABLE_LOCKS
5997 /* Cancel pending events */
5998 rxevent_Cancel(call->delayedAckEvent, call,
5999 RX_CALL_REFCOUNT_DELAY);
6000 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6001 rxevent_Cancel(call->keepAliveEvent, call,
6002 RX_CALL_REFCOUNT_ALIVE);
6003 MUTEX_ENTER(&rx_refcnt_mutex);
6004 if (call->refCount == 0) {
6005 rxi_FreeCall(call, haveCTLock);
6006 MUTEX_EXIT(&rx_refcnt_mutex);
6009 MUTEX_EXIT(&rx_refcnt_mutex);
6011 #else /* RX_ENABLE_LOCKS */
6012 rxi_FreeCall(call, 0);
6014 #endif /* RX_ENABLE_LOCKS */
6016 /* Non-active calls are destroyed if they are not responding
6017 * to pings; active calls are simply flagged in error, so the
6018 * attached process can die reasonably gracefully. */
6021 if (conn->idleDeadTime) {
6022 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6025 /* see if we have a non-activity timeout */
6026 if (call->startWait && idleDeadTime
6027 && ((call->startWait + idleDeadTime) < now) &&
6028 (call->flags & RX_CALL_READER_WAIT)) {
6029 if (call->state == RX_STATE_ACTIVE) {
6030 cerror = RX_CALL_TIMEOUT;
6034 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6035 && ((call->lastSendData + idleDeadTime) < now)) {
6036 if (call->state == RX_STATE_ACTIVE) {
6037 cerror = conn->idleDeadErr;
6043 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6046 /* see if we have a hard timeout */
6048 && (now > (hardDeadTime + call->startTime.sec))) {
6049 if (call->state == RX_STATE_ACTIVE)
6050 rxi_CallError(call, RX_CALL_TIMEOUT);
6055 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6056 && call->lastReceiveTime) {
6057 int oldMTU = conn->peer->ifMTU;
6059 /* if we thought we could send more, perhaps things got worse */
6060 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6061 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6062 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6063 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6065 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6067 /* minimum capped in SetPeerMtu */
6068 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6071 conn->lastPacketSize = 0;
6073 /* needed so ResetCall doesn't clobber us. */
6074 call->MTU = conn->peer->ifMTU;
6076 /* if we never succeeded, let the error pass out as-is */
6077 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6078 cerror = conn->msgsizeRetryErr;
6081 rxi_CallError(call, cerror);
6086 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6088 struct rx_connection *conn = arg1;
6089 struct rx_header theader;
6091 struct sockaddr_in taddr;
6094 struct iovec tmpiov[2];
6097 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6100 tp = &tbuffer[sizeof(struct rx_header)];
6101 taddr.sin_family = AF_INET;
6102 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6103 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6104 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6105 taddr.sin_len = sizeof(struct sockaddr_in);
6107 memset(&theader, 0, sizeof(theader));
6108 theader.epoch = htonl(999);
6110 theader.callNumber = 0;
6113 theader.type = RX_PACKET_TYPE_VERSION;
6114 theader.flags = RX_LAST_PACKET;
6115 theader.serviceId = 0;
6117 memcpy(tbuffer, &theader, sizeof(theader));
6118 memcpy(tp, &a, sizeof(a));
6119 tmpiov[0].iov_base = tbuffer;
6120 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6122 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6124 MUTEX_ENTER(&conn->conn_data_lock);
6125 MUTEX_ENTER(&rx_refcnt_mutex);
6126 /* Only reschedule ourselves if the connection would not be destroyed */
6127 if (conn->refCount <= 1) {
6128 conn->natKeepAliveEvent = NULL;
6129 MUTEX_EXIT(&rx_refcnt_mutex);
6130 MUTEX_EXIT(&conn->conn_data_lock);
6131 rx_DestroyConnection(conn); /* drop the reference for this */
6133 conn->refCount--; /* drop the reference for this */
6134 MUTEX_EXIT(&rx_refcnt_mutex);
6135 conn->natKeepAliveEvent = NULL;
6136 rxi_ScheduleNatKeepAliveEvent(conn);
6137 MUTEX_EXIT(&conn->conn_data_lock);
6142 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6144 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6145 struct clock when, now;
6146 clock_GetTime(&now);
6148 when.sec += conn->secondsUntilNatPing;
6149 MUTEX_ENTER(&rx_refcnt_mutex);
6150 conn->refCount++; /* hold a reference for this */
6151 MUTEX_EXIT(&rx_refcnt_mutex);
6152 conn->natKeepAliveEvent =
6153 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6158 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6160 MUTEX_ENTER(&conn->conn_data_lock);
6161 conn->secondsUntilNatPing = seconds;
6163 rxi_ScheduleNatKeepAliveEvent(conn);
6164 MUTEX_EXIT(&conn->conn_data_lock);
6168 rxi_NatKeepAliveOn(struct rx_connection *conn)
6170 MUTEX_ENTER(&conn->conn_data_lock);
6171 rxi_ScheduleNatKeepAliveEvent(conn);
6172 MUTEX_EXIT(&conn->conn_data_lock);
6175 /* When a call is in progress, this routine is called occasionally to
6176 * make sure that some traffic has arrived (or been sent to) the peer.
6177 * If nothing has arrived in a reasonable amount of time, the call is
6178 * declared dead; if nothing has been sent for a while, we send a
6179 * keep-alive packet (if we're actually trying to keep the call alive)
6182 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6184 struct rx_call *call = arg1;
6185 struct rx_connection *conn;
6188 MUTEX_ENTER(&rx_refcnt_mutex);
6189 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6190 MUTEX_EXIT(&rx_refcnt_mutex);
6191 MUTEX_ENTER(&call->lock);
6192 if (event == call->keepAliveEvent)
6193 call->keepAliveEvent = NULL;
6196 #ifdef RX_ENABLE_LOCKS
6197 if (rxi_CheckCall(call, 0)) {
6198 MUTEX_EXIT(&call->lock);
6201 #else /* RX_ENABLE_LOCKS */
6202 if (rxi_CheckCall(call))
6204 #endif /* RX_ENABLE_LOCKS */
6206 /* Don't try to keep alive dallying calls */
6207 if (call->state == RX_STATE_DALLY) {
6208 MUTEX_EXIT(&call->lock);
6213 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6214 /* Don't try to send keepalives if there is unacknowledged data */
6215 /* the rexmit code should be good enough, this little hack
6216 * doesn't quite work XXX */
6217 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6219 rxi_ScheduleKeepAliveEvent(call);
6220 MUTEX_EXIT(&call->lock);
6223 /* Does what's on the nameplate. */
6225 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6227 struct rx_call *call = arg1;
6228 struct rx_connection *conn;
6230 MUTEX_ENTER(&rx_refcnt_mutex);
6231 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6232 MUTEX_EXIT(&rx_refcnt_mutex);
6233 MUTEX_ENTER(&call->lock);
6235 if (event == call->growMTUEvent)
6236 call->growMTUEvent = NULL;
6238 #ifdef RX_ENABLE_LOCKS
6239 if (rxi_CheckCall(call, 0)) {
6240 MUTEX_EXIT(&call->lock);
6243 #else /* RX_ENABLE_LOCKS */
6244 if (rxi_CheckCall(call))
6246 #endif /* RX_ENABLE_LOCKS */
6248 /* Don't bother with dallying calls */
6249 if (call->state == RX_STATE_DALLY) {
6250 MUTEX_EXIT(&call->lock);
6257 * keep being scheduled, just don't do anything if we're at peak,
6258 * or we're not set up to be properly handled (idle timeout required)
6260 if ((conn->peer->maxPacketSize != 0) &&
6261 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6262 (conn->idleDeadErr))
6263 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6264 rxi_ScheduleGrowMTUEvent(call, 0);
6265 MUTEX_EXIT(&call->lock);
6269 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6271 if (!call->keepAliveEvent) {
6272 struct clock when, now;
6273 clock_GetTime(&now);
6275 when.sec += call->conn->secondsUntilPing;
6276 MUTEX_ENTER(&rx_refcnt_mutex);
6277 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6278 MUTEX_EXIT(&rx_refcnt_mutex);
6279 call->keepAliveEvent =
6280 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6285 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6287 if (!call->growMTUEvent) {
6288 struct clock when, now;
6290 clock_GetTime(&now);
6293 if (call->conn->secondsUntilPing)
6294 secs = (6*call->conn->secondsUntilPing)-1;
6296 if (call->conn->secondsUntilDead)
6297 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6301 MUTEX_ENTER(&rx_refcnt_mutex);
6302 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6303 MUTEX_EXIT(&rx_refcnt_mutex);
6304 call->growMTUEvent =
6305 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6309 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6311 rxi_KeepAliveOn(struct rx_call *call)
6313 /* Pretend last packet received was received now--i.e. if another
6314 * packet isn't received within the keep alive time, then the call
6315 * will die; Initialize last send time to the current time--even
6316 * if a packet hasn't been sent yet. This will guarantee that a
6317 * keep-alive is sent within the ping time */
6318 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6319 rxi_ScheduleKeepAliveEvent(call);
6323 rxi_GrowMTUOn(struct rx_call *call)
6325 struct rx_connection *conn = call->conn;
6326 MUTEX_ENTER(&conn->conn_data_lock);
6327 conn->lastPingSizeSer = conn->lastPingSize = 0;
6328 MUTEX_EXIT(&conn->conn_data_lock);
6329 rxi_ScheduleGrowMTUEvent(call, 1);
6332 /* This routine is called to send connection abort messages
6333 * that have been delayed to throttle looping clients. */
6335 rxi_SendDelayedConnAbort(struct rxevent *event,
6336 void *arg1, void *unused)
6338 struct rx_connection *conn = arg1;
6341 struct rx_packet *packet;
6343 MUTEX_ENTER(&conn->conn_data_lock);
6344 conn->delayedAbortEvent = NULL;
6345 error = htonl(conn->error);
6347 MUTEX_EXIT(&conn->conn_data_lock);
6348 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6351 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6352 RX_PACKET_TYPE_ABORT, (char *)&error,
6354 rxi_FreePacket(packet);
6358 /* This routine is called to send call abort messages
6359 * that have been delayed to throttle looping clients. */
6361 rxi_SendDelayedCallAbort(struct rxevent *event,
6362 void *arg1, void *dummy)
6364 struct rx_call *call = arg1;
6367 struct rx_packet *packet;
6369 MUTEX_ENTER(&call->lock);
6370 call->delayedAbortEvent = NULL;
6371 error = htonl(call->error);
6373 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6376 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6377 (char *)&error, sizeof(error), 0);
6378 rxi_FreePacket(packet);
6380 MUTEX_EXIT(&call->lock);
6381 MUTEX_ENTER(&rx_refcnt_mutex);
6382 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6383 MUTEX_EXIT(&rx_refcnt_mutex);
6386 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6387 * seconds) to ask the client to authenticate itself. The routine
6388 * issues a challenge to the client, which is obtained from the
6389 * security object associated with the connection */
6391 rxi_ChallengeEvent(struct rxevent *event,
6392 void *arg0, void *arg1, int tries)
6394 struct rx_connection *conn = arg0;
6396 conn->challengeEvent = NULL;
6397 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6398 struct rx_packet *packet;
6399 struct clock when, now;
6402 /* We've failed to authenticate for too long.
6403 * Reset any calls waiting for authentication;
6404 * they are all in RX_STATE_PRECALL.
6408 MUTEX_ENTER(&conn->conn_call_lock);
6409 for (i = 0; i < RX_MAXCALLS; i++) {
6410 struct rx_call *call = conn->call[i];
6412 MUTEX_ENTER(&call->lock);
6413 if (call->state == RX_STATE_PRECALL) {
6414 rxi_CallError(call, RX_CALL_DEAD);
6415 rxi_SendCallAbort(call, NULL, 0, 0);
6417 MUTEX_EXIT(&call->lock);
6420 MUTEX_EXIT(&conn->conn_call_lock);
6424 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6426 /* If there's no packet available, do this later. */
6427 RXS_GetChallenge(conn->securityObject, conn, packet);
6428 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6429 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6430 rxi_FreePacket(packet);
6432 clock_GetTime(&now);
6434 when.sec += RX_CHALLENGE_TIMEOUT;
6435 conn->challengeEvent =
6436 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6441 /* Call this routine to start requesting the client to authenticate
6442 * itself. This will continue until authentication is established,
6443 * the call times out, or an invalid response is returned. The
6444 * security object associated with the connection is asked to create
6445 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6446 * defined earlier. */
6448 rxi_ChallengeOn(struct rx_connection *conn)
6450 if (!conn->challengeEvent) {
6451 RXS_CreateChallenge(conn->securityObject, conn);
6452 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6457 /* rxi_ComputeRoundTripTime is called with peer locked. */
6458 /* peer may be null */
6460 rxi_ComputeRoundTripTime(struct rx_packet *p,
6461 struct rx_ackPacket *ack,
6462 struct rx_peer *peer,
6465 struct clock thisRtt, *sentp;
6469 /* If the ACK is delayed, then do nothing */
6470 if (ack->reason == RX_ACK_DELAY)
6473 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6474 * their RTT multiple times, so only include the RTT of the last packet
6476 if (p->flags & RX_JUMBO_PACKET)
6479 /* Use the serial number to determine which transmission the ACK is for,
6480 * and set the sent time to match this. If we have no serial number, then
6481 * only use the ACK for RTT calculations if the packet has not been
6485 serial = ntohl(ack->serial);
6487 if (serial == p->header.serial) {
6488 sentp = &p->timeSent;
6489 } else if (serial == p->firstSerial) {
6490 sentp = &p->firstSent;
6491 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6492 sentp = &p->firstSent;
6496 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6497 sentp = &p->firstSent;
6504 if (clock_Lt(&thisRtt, sentp))
6505 return; /* somebody set the clock back, don't count this time. */
6507 clock_Sub(&thisRtt, sentp);
6508 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6509 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6511 if (clock_IsZero(&thisRtt)) {
6513 * The actual round trip time is shorter than the
6514 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6515 * Since we can't tell which at the moment we will assume 1ms.
6517 thisRtt.usec = 1000;
6520 if (rx_stats_active) {
6521 MUTEX_ENTER(&rx_stats_mutex);
6522 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6523 rx_stats.minRtt = thisRtt;
6524 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6525 if (thisRtt.sec > 60) {
6526 MUTEX_EXIT(&rx_stats_mutex);
6527 return; /* somebody set the clock ahead */
6529 rx_stats.maxRtt = thisRtt;
6531 clock_Add(&rx_stats.totalRtt, &thisRtt);
6532 rx_atomic_inc(&rx_stats.nRttSamples);
6533 MUTEX_EXIT(&rx_stats_mutex);
6536 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6538 /* Apply VanJacobson round-trip estimations */
6543 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6544 * srtt is stored as fixed point with 3 bits after the binary
6545 * point (i.e., scaled by 8). The following magic is
6546 * equivalent to the smoothing algorithm in rfc793 with an
6547 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6548 * srtt'*8 = rtt + srtt*7
6549 * srtt'*8 = srtt*8 + rtt - srtt
6550 * srtt' = srtt + rtt/8 - srtt/8
6551 * srtt' = srtt + (rtt - srtt)/8
6554 delta = _8THMSEC(&thisRtt) - peer->rtt;
6555 peer->rtt += (delta >> 3);
6558 * We accumulate a smoothed rtt variance (actually, a smoothed
6559 * mean difference), then set the retransmit timer to smoothed
6560 * rtt + 4 times the smoothed variance (was 2x in van's original
6561 * paper, but 4x works better for me, and apparently for him as
6563 * rttvar is stored as
6564 * fixed point with 2 bits after the binary point (scaled by
6565 * 4). The following is equivalent to rfc793 smoothing with
6566 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6567 * rttvar'*4 = rttvar*3 + |delta|
6568 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6569 * rttvar' = rttvar + |delta|/4 - rttvar/4
6570 * rttvar' = rttvar + (|delta| - rttvar)/4
6571 * This replaces rfc793's wired-in beta.
6572 * dev*4 = dev*4 + (|actual - expected| - dev)
6578 delta -= (peer->rtt_dev << 1);
6579 peer->rtt_dev += (delta >> 3);
6581 /* I don't have a stored RTT so I start with this value. Since I'm
6582 * probably just starting a call, and will be pushing more data down
6583 * this, I expect congestion to increase rapidly. So I fudge a
6584 * little, and I set deviance to half the rtt. In practice,
6585 * deviance tends to approach something a little less than
6586 * half the smoothed rtt. */
6587 peer->rtt = _8THMSEC(&thisRtt) + 8;
6588 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6590 /* the timeout is RTT + 4*MDEV + rx_minPeerTimeout msec.
6591 * This is because one end or the other of these connections is usually
6592 * in a user process, and can be switched and/or swapped out. So on fast,
6593 * reliable networks, the timeout would otherwise be too short. */
6594 rtt_timeout = ((peer->rtt >> 3) + peer->rtt_dev) + rx_minPeerTimeout;
6595 clock_Zero(&(peer->timeout));
6596 clock_Addmsec(&(peer->timeout), rtt_timeout);
6598 /* Reset the backedOff flag since we just computed a new timeout value */
6599 peer->backedOff = 0;
6601 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6602 p->header.callNumber, p, MSEC(&thisRtt), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6606 /* Find all server connections that have not been active for a long time, and
6609 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6611 struct clock now, when;
6612 clock_GetTime(&now);
6614 /* Find server connection structures that haven't been used for
6615 * greater than rx_idleConnectionTime */
6617 struct rx_connection **conn_ptr, **conn_end;
6618 int i, havecalls = 0;
6619 MUTEX_ENTER(&rx_connHashTable_lock);
6620 for (conn_ptr = &rx_connHashTable[0], conn_end =
6621 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6623 struct rx_connection *conn, *next;
6624 struct rx_call *call;
6628 for (conn = *conn_ptr; conn; conn = next) {
6629 /* XXX -- Shouldn't the connection be locked? */
6632 for (i = 0; i < RX_MAXCALLS; i++) {
6633 call = conn->call[i];
6637 code = MUTEX_TRYENTER(&call->lock);
6640 #ifdef RX_ENABLE_LOCKS
6641 result = rxi_CheckCall(call, 1);
6642 #else /* RX_ENABLE_LOCKS */
6643 result = rxi_CheckCall(call);
6644 #endif /* RX_ENABLE_LOCKS */
6645 MUTEX_EXIT(&call->lock);
6647 /* If CheckCall freed the call, it might
6648 * have destroyed the connection as well,
6649 * which screws up the linked lists.
6655 if (conn->type == RX_SERVER_CONNECTION) {
6656 /* This only actually destroys the connection if
6657 * there are no outstanding calls */
6658 MUTEX_ENTER(&conn->conn_data_lock);
6659 MUTEX_ENTER(&rx_refcnt_mutex);
6660 if (!havecalls && !conn->refCount
6661 && ((conn->lastSendTime + rx_idleConnectionTime) <
6663 conn->refCount++; /* it will be decr in rx_DestroyConn */
6664 MUTEX_EXIT(&rx_refcnt_mutex);
6665 MUTEX_EXIT(&conn->conn_data_lock);
6666 #ifdef RX_ENABLE_LOCKS
6667 rxi_DestroyConnectionNoLock(conn);
6668 #else /* RX_ENABLE_LOCKS */
6669 rxi_DestroyConnection(conn);
6670 #endif /* RX_ENABLE_LOCKS */
6672 #ifdef RX_ENABLE_LOCKS
6674 MUTEX_EXIT(&rx_refcnt_mutex);
6675 MUTEX_EXIT(&conn->conn_data_lock);
6677 #endif /* RX_ENABLE_LOCKS */
6681 #ifdef RX_ENABLE_LOCKS
6682 while (rx_connCleanup_list) {
6683 struct rx_connection *conn;
6684 conn = rx_connCleanup_list;
6685 rx_connCleanup_list = rx_connCleanup_list->next;
6686 MUTEX_EXIT(&rx_connHashTable_lock);
6687 rxi_CleanupConnection(conn);
6688 MUTEX_ENTER(&rx_connHashTable_lock);
6690 MUTEX_EXIT(&rx_connHashTable_lock);
6691 #endif /* RX_ENABLE_LOCKS */
6694 /* Find any peer structures that haven't been used (haven't had an
6695 * associated connection) for greater than rx_idlePeerTime */
6697 struct rx_peer **peer_ptr, **peer_end;
6701 * Why do we need to hold the rx_peerHashTable_lock across
6702 * the incrementing of peer_ptr since the rx_peerHashTable
6703 * array is not changing? We don't.
6705 * By dropping the lock periodically we can permit other
6706 * activities to be performed while a rxi_ReapConnections
6707 * call is in progress. The goal of reap connections
6708 * is to clean up quickly without causing large amounts
6709 * of contention. Therefore, it is important that global
6710 * mutexes not be held for extended periods of time.
6712 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6713 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6715 struct rx_peer *peer, *next, *prev;
6717 MUTEX_ENTER(&rx_peerHashTable_lock);
6718 for (prev = peer = *peer_ptr; peer; peer = next) {
6720 code = MUTEX_TRYENTER(&peer->peer_lock);
6721 if ((code) && (peer->refCount == 0)
6722 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6723 rx_interface_stat_p rpc_stat, nrpc_stat;
6727 * now know that this peer object is one to be
6728 * removed from the hash table. Once it is removed
6729 * it can't be referenced by other threads.
6730 * Lets remove it first and decrement the struct
6731 * nPeerStructs count.
6733 if (peer == *peer_ptr) {
6739 if (rx_stats_active)
6740 rx_atomic_dec(&rx_stats.nPeerStructs);
6743 * Now if we hold references on 'prev' and 'next'
6744 * we can safely drop the rx_peerHashTable_lock
6745 * while we destroy this 'peer' object.
6751 MUTEX_EXIT(&rx_peerHashTable_lock);
6753 MUTEX_EXIT(&peer->peer_lock);
6754 MUTEX_DESTROY(&peer->peer_lock);
6756 (&peer->rpcStats, rpc_stat, nrpc_stat,
6757 rx_interface_stat)) {
6758 unsigned int num_funcs;
6761 queue_Remove(&rpc_stat->queue_header);
6762 queue_Remove(&rpc_stat->all_peers);
6763 num_funcs = rpc_stat->stats[0].func_total;
6765 sizeof(rx_interface_stat_t) +
6766 rpc_stat->stats[0].func_total *
6767 sizeof(rx_function_entry_v1_t);
6769 rxi_Free(rpc_stat, space);
6771 MUTEX_ENTER(&rx_rpc_stats);
6772 rxi_rpc_peer_stat_cnt -= num_funcs;
6773 MUTEX_EXIT(&rx_rpc_stats);
6778 * Regain the rx_peerHashTable_lock and
6779 * decrement the reference count on 'prev'
6782 MUTEX_ENTER(&rx_peerHashTable_lock);
6789 MUTEX_EXIT(&peer->peer_lock);
6794 MUTEX_EXIT(&rx_peerHashTable_lock);
6798 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6799 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6800 * GC, just below. Really, we shouldn't have to keep moving packets from
6801 * one place to another, but instead ought to always know if we can
6802 * afford to hold onto a packet in its particular use. */
6803 MUTEX_ENTER(&rx_freePktQ_lock);
6804 if (rx_waitingForPackets) {
6805 rx_waitingForPackets = 0;
6806 #ifdef RX_ENABLE_LOCKS
6807 CV_BROADCAST(&rx_waitingForPackets_cv);
6809 osi_rxWakeup(&rx_waitingForPackets);
6812 MUTEX_EXIT(&rx_freePktQ_lock);
6815 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6816 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6820 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6821 * rx.h is sort of strange this is better. This is called with a security
6822 * object before it is discarded. Each connection using a security object has
6823 * its own refcount to the object so it won't actually be freed until the last
6824 * connection is destroyed.
6826 * This is the only rxs module call. A hold could also be written but no one
6830 rxs_Release(struct rx_securityClass *aobj)
6832 return RXS_Close(aobj);
6836 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6837 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6838 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6839 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6841 /* Adjust our estimate of the transmission rate to this peer, given
6842 * that the packet p was just acked. We can adjust peer->timeout and
6843 * call->twind. Pragmatically, this is called
6844 * only with packets of maximal length.
6845 * Called with peer and call locked.
6849 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6850 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6852 afs_int32 xferSize, xferMs;
6856 /* Count down packets */
6857 if (peer->rateFlag > 0)
6859 /* Do nothing until we're enabled */
6860 if (peer->rateFlag != 0)
6865 /* Count only when the ack seems legitimate */
6866 switch (ackReason) {
6867 case RX_ACK_REQUESTED:
6869 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6873 case RX_ACK_PING_RESPONSE:
6874 if (p) /* want the response to ping-request, not data send */
6876 clock_GetTime(&newTO);
6877 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6878 clock_Sub(&newTO, &call->pingRequestTime);
6879 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6883 xferSize = rx_AckDataSize(rx_maxSendWindow) + RX_HEADER_SIZE;
6890 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)\n",
6891 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
6892 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6894 /* Track only packets that are big enough. */
6895 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6899 /* absorb RTT data (in milliseconds) for these big packets */
6900 if (peer->smRtt == 0) {
6901 peer->smRtt = xferMs;
6903 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6908 if (peer->countDown) {
6912 peer->countDown = 10; /* recalculate only every so often */
6914 /* In practice, we can measure only the RTT for full packets,
6915 * because of the way Rx acks the data that it receives. (If it's
6916 * smaller than a full packet, it often gets implicitly acked
6917 * either by the call response (from a server) or by the next call
6918 * (from a client), and either case confuses transmission times
6919 * with processing times.) Therefore, replace the above
6920 * more-sophisticated processing with a simpler version, where the
6921 * smoothed RTT is kept for full-size packets, and the time to
6922 * transmit a windowful of full-size packets is simply RTT *
6923 * windowSize. Again, we take two steps:
6924 - ensure the timeout is large enough for a single packet's RTT;
6925 - ensure that the window is small enough to fit in the desired timeout.*/
6927 /* First, the timeout check. */
6928 minTime = peer->smRtt;
6929 /* Get a reasonable estimate for a timeout period */
6931 newTO.sec = minTime / 1000;
6932 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6934 /* Increase the timeout period so that we can always do at least
6935 * one packet exchange */
6936 if (clock_Gt(&newTO, &peer->timeout)) {
6938 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u)\n",
6939 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
6940 newTO.sec, newTO.usec, peer->smRtt));
6942 peer->timeout = newTO;
6945 /* Now, get an estimate for the transmit window size. */
6946 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6947 /* Now, convert to the number of full packets that could fit in a
6948 * reasonable fraction of that interval */
6949 minTime /= (peer->smRtt << 1);
6950 minTime = MAX(minTime, rx_minPeerTimeout);
6951 xferSize = minTime; /* (make a copy) */
6953 /* Now clamp the size to reasonable bounds. */
6956 else if (minTime > rx_maxSendWindow)
6957 minTime = rx_maxSendWindow;
6958 /* if (minTime != peer->maxWindow) {
6959 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u)\n",
6960 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6961 peer->timeout.sec, peer->timeout.usec, peer->smRtt));
6962 peer->maxWindow = minTime;
6963 elide... call->twind = minTime;
6967 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6968 * Discern this by calculating the timeout necessary for rx_Window
6970 if ((xferSize > rx_maxSendWindow) && (peer->timeout.sec >= 3)) {
6971 /* calculate estimate for transmission interval in milliseconds */
6972 minTime = rx_maxSendWindow * peer->smRtt;
6973 if (minTime < 1000) {
6974 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u)\n",
6975 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6976 peer->timeout.usec, peer->smRtt));
6978 newTO.sec = 0; /* cut back on timeout by half a second */
6979 newTO.usec = 500000;
6980 clock_Sub(&peer->timeout, &newTO);
6985 } /* end of rxi_ComputeRate */
6986 #endif /* ADAPT_WINDOW */
6994 #define TRACE_OPTION_RX_DEBUG 16
7002 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7003 0, KEY_QUERY_VALUE, &parmKey);
7004 if (code != ERROR_SUCCESS)
7007 dummyLen = sizeof(TraceOption);
7008 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7009 (BYTE *) &TraceOption, &dummyLen);
7010 if (code == ERROR_SUCCESS) {
7011 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7013 RegCloseKey (parmKey);
7014 #endif /* AFS_NT40_ENV */
7019 rx_DebugOnOff(int on)
7023 rxdebug_active = on;
7029 rx_StatsOnOff(int on)
7031 rx_stats_active = on;
7035 /* Don't call this debugging routine directly; use dpf */
7037 rxi_DebugPrint(char *format, ...)
7046 va_start(ap, format);
7048 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7051 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7053 OutputDebugString(msg);
7059 va_start(ap, format);
7061 clock_GetTime(&now);
7062 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7063 (unsigned int)now.usec);
7064 vfprintf(rx_Log, format, ap);
7072 * This function is used to process the rx_stats structure that is local
7073 * to a process as well as an rx_stats structure received from a remote
7074 * process (via rxdebug). Therefore, it needs to do minimal version
7078 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7079 afs_int32 freePackets, char version)
7083 if (size != sizeof(struct rx_statistics)) {
7085 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7086 size, sizeof(struct rx_statistics));
7089 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7092 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7093 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7094 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7095 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7096 s->specialPktAllocFailures);
7098 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7099 s->receivePktAllocFailures, s->sendPktAllocFailures,
7100 s->specialPktAllocFailures);
7104 " greedy %u, " "bogusReads %u (last from host %x), "
7105 "noPackets %u, " "noBuffers %u, " "selects %u, "
7106 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7107 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7108 s->selects, s->sendSelects);
7110 fprintf(file, " packets read: ");
7111 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7112 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7114 fprintf(file, "\n");
7117 " other read counters: data %u, " "ack %u, " "dup %u "
7118 "spurious %u " "dally %u\n", s->dataPacketsRead,
7119 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7120 s->ignorePacketDally);
7122 fprintf(file, " packets sent: ");
7123 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7124 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7126 fprintf(file, "\n");
7129 " other send counters: ack %u, " "data %u (not resends), "
7130 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7131 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7132 s->dataPacketsPushed, s->ignoreAckedPacket);
7135 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7136 s->netSendFailures, (int)s->fatalErrors);
7138 if (s->nRttSamples) {
7139 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7140 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7142 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7143 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7147 " %d server connections, " "%d client connections, "
7148 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7149 s->nServerConns, s->nClientConns, s->nPeerStructs,
7150 s->nCallStructs, s->nFreeCallStructs);
7152 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7153 fprintf(file, " %d clock updates\n", clock_nUpdates);
7157 /* for backward compatibility */
7159 rx_PrintStats(FILE * file)
7161 MUTEX_ENTER(&rx_stats_mutex);
7162 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7163 sizeof(rx_stats), rx_nFreePackets,
7165 MUTEX_EXIT(&rx_stats_mutex);
7169 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7171 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7172 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7173 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7176 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7177 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7178 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7181 " Packet size %d, " "max in packet skew %d, "
7182 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7183 (int)peer->outPacketSkew);
7187 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7189 * This mutex protects the following static variables:
7193 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7194 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7196 #define LOCK_RX_DEBUG
7197 #define UNLOCK_RX_DEBUG
7198 #endif /* AFS_PTHREAD_ENV */
7200 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7202 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7203 u_char type, void *inputData, size_t inputLength,
7204 void *outputData, size_t outputLength)
7206 static afs_int32 counter = 100;
7207 time_t waitTime, waitCount;
7208 struct rx_header theader;
7211 struct timeval tv_now, tv_wake, tv_delta;
7212 struct sockaddr_in taddr, faddr;
7226 tp = &tbuffer[sizeof(struct rx_header)];
7227 taddr.sin_family = AF_INET;
7228 taddr.sin_port = remotePort;
7229 taddr.sin_addr.s_addr = remoteAddr;
7230 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7231 taddr.sin_len = sizeof(struct sockaddr_in);
7234 memset(&theader, 0, sizeof(theader));
7235 theader.epoch = htonl(999);
7237 theader.callNumber = htonl(counter);
7240 theader.type = type;
7241 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7242 theader.serviceId = 0;
7244 memcpy(tbuffer, &theader, sizeof(theader));
7245 memcpy(tp, inputData, inputLength);
7247 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7248 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7250 /* see if there's a packet available */
7251 gettimeofday(&tv_wake,0);
7252 tv_wake.tv_sec += waitTime;
7255 FD_SET(socket, &imask);
7256 tv_delta.tv_sec = tv_wake.tv_sec;
7257 tv_delta.tv_usec = tv_wake.tv_usec;
7258 gettimeofday(&tv_now, 0);
7260 if (tv_delta.tv_usec < tv_now.tv_usec) {
7262 tv_delta.tv_usec += 1000000;
7265 tv_delta.tv_usec -= tv_now.tv_usec;
7267 if (tv_delta.tv_sec < tv_now.tv_sec) {
7271 tv_delta.tv_sec -= tv_now.tv_sec;
7274 code = select(0, &imask, 0, 0, &tv_delta);
7275 #else /* AFS_NT40_ENV */
7276 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7277 #endif /* AFS_NT40_ENV */
7278 if (code == 1 && FD_ISSET(socket, &imask)) {
7279 /* now receive a packet */
7280 faddrLen = sizeof(struct sockaddr_in);
7282 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7283 (struct sockaddr *)&faddr, &faddrLen);
7286 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7287 if (counter == ntohl(theader.callNumber))
7295 /* see if we've timed out */
7303 code -= sizeof(struct rx_header);
7304 if (code > outputLength)
7305 code = outputLength;
7306 memcpy(outputData, tp, code);
7309 #endif /* RXDEBUG */
7312 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7313 afs_uint16 remotePort, struct rx_debugStats * stat,
7314 afs_uint32 * supportedValues)
7316 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7318 struct rx_debugIn in;
7320 *supportedValues = 0;
7321 in.type = htonl(RX_DEBUGI_GETSTATS);
7324 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7325 &in, sizeof(in), stat, sizeof(*stat));
7328 * If the call was successful, fixup the version and indicate
7329 * what contents of the stat structure are valid.
7330 * Also do net to host conversion of fields here.
7334 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7335 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7337 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7338 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7340 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7341 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7343 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7344 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7346 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7347 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7349 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7350 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7352 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7353 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7355 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7356 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7358 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7359 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7361 stat->nFreePackets = ntohl(stat->nFreePackets);
7362 stat->packetReclaims = ntohl(stat->packetReclaims);
7363 stat->callsExecuted = ntohl(stat->callsExecuted);
7364 stat->nWaiting = ntohl(stat->nWaiting);
7365 stat->idleThreads = ntohl(stat->idleThreads);
7366 stat->nWaited = ntohl(stat->nWaited);
7367 stat->nPackets = ntohl(stat->nPackets);
7376 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7377 afs_uint16 remotePort, struct rx_statistics * stat,
7378 afs_uint32 * supportedValues)
7380 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7382 struct rx_debugIn in;
7383 afs_int32 *lp = (afs_int32 *) stat;
7387 * supportedValues is currently unused, but added to allow future
7388 * versioning of this function.
7391 *supportedValues = 0;
7392 in.type = htonl(RX_DEBUGI_RXSTATS);
7394 memset(stat, 0, sizeof(*stat));
7396 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7397 &in, sizeof(in), stat, sizeof(*stat));
7402 * Do net to host conversion here
7405 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7416 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7417 afs_uint16 remotePort, size_t version_length,
7420 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7422 return MakeDebugCall(socket, remoteAddr, remotePort,
7423 RX_PACKET_TYPE_VERSION, a, 1, version,
7431 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7432 afs_uint16 remotePort, afs_int32 * nextConnection,
7433 int allConnections, afs_uint32 debugSupportedValues,
7434 struct rx_debugConn * conn,
7435 afs_uint32 * supportedValues)
7437 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7439 struct rx_debugIn in;
7443 * supportedValues is currently unused, but added to allow future
7444 * versioning of this function.
7447 *supportedValues = 0;
7448 if (allConnections) {
7449 in.type = htonl(RX_DEBUGI_GETALLCONN);
7451 in.type = htonl(RX_DEBUGI_GETCONN);
7453 in.index = htonl(*nextConnection);
7454 memset(conn, 0, sizeof(*conn));
7456 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7457 &in, sizeof(in), conn, sizeof(*conn));
7460 *nextConnection += 1;
7463 * Convert old connection format to new structure.
7466 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7467 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7468 #define MOVEvL(a) (conn->a = vL->a)
7470 /* any old or unrecognized version... */
7471 for (i = 0; i < RX_MAXCALLS; i++) {
7472 MOVEvL(callState[i]);
7473 MOVEvL(callMode[i]);
7474 MOVEvL(callFlags[i]);
7475 MOVEvL(callOther[i]);
7477 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7478 MOVEvL(secStats.type);
7479 MOVEvL(secStats.level);
7480 MOVEvL(secStats.flags);
7481 MOVEvL(secStats.expires);
7482 MOVEvL(secStats.packetsReceived);
7483 MOVEvL(secStats.packetsSent);
7484 MOVEvL(secStats.bytesReceived);
7485 MOVEvL(secStats.bytesSent);
7490 * Do net to host conversion here
7492 * I don't convert host or port since we are most likely
7493 * going to want these in NBO.
7495 conn->cid = ntohl(conn->cid);
7496 conn->serial = ntohl(conn->serial);
7497 for (i = 0; i < RX_MAXCALLS; i++) {
7498 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7500 conn->error = ntohl(conn->error);
7501 conn->secStats.flags = ntohl(conn->secStats.flags);
7502 conn->secStats.expires = ntohl(conn->secStats.expires);
7503 conn->secStats.packetsReceived =
7504 ntohl(conn->secStats.packetsReceived);
7505 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7506 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7507 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7508 conn->epoch = ntohl(conn->epoch);
7509 conn->natMTU = ntohl(conn->natMTU);
7518 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7519 afs_uint16 remotePort, afs_int32 * nextPeer,
7520 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7521 afs_uint32 * supportedValues)
7523 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7525 struct rx_debugIn in;
7528 * supportedValues is currently unused, but added to allow future
7529 * versioning of this function.
7532 *supportedValues = 0;
7533 in.type = htonl(RX_DEBUGI_GETPEER);
7534 in.index = htonl(*nextPeer);
7535 memset(peer, 0, sizeof(*peer));
7537 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7538 &in, sizeof(in), peer, sizeof(*peer));
7544 * Do net to host conversion here
7546 * I don't convert host or port since we are most likely
7547 * going to want these in NBO.
7549 peer->ifMTU = ntohs(peer->ifMTU);
7550 peer->idleWhen = ntohl(peer->idleWhen);
7551 peer->refCount = ntohs(peer->refCount);
7552 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7553 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7554 peer->rtt = ntohl(peer->rtt);
7555 peer->rtt_dev = ntohl(peer->rtt_dev);
7556 peer->timeout.sec = ntohl(peer->timeout.sec);
7557 peer->timeout.usec = ntohl(peer->timeout.usec);
7558 peer->nSent = ntohl(peer->nSent);
7559 peer->reSends = ntohl(peer->reSends);
7560 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7561 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7562 peer->rateFlag = ntohl(peer->rateFlag);
7563 peer->natMTU = ntohs(peer->natMTU);
7564 peer->maxMTU = ntohs(peer->maxMTU);
7565 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7566 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7567 peer->MTU = ntohs(peer->MTU);
7568 peer->cwind = ntohs(peer->cwind);
7569 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7570 peer->congestSeq = ntohs(peer->congestSeq);
7571 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7572 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7573 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7574 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7583 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7584 struct rx_debugPeer * peerStats)
7587 afs_int32 error = 1; /* default to "did not succeed" */
7588 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7590 MUTEX_ENTER(&rx_peerHashTable_lock);
7591 for(tp = rx_peerHashTable[hashValue];
7592 tp != NULL; tp = tp->next) {
7593 if (tp->host == peerHost)
7599 MUTEX_EXIT(&rx_peerHashTable_lock);
7603 MUTEX_ENTER(&tp->peer_lock);
7604 peerStats->host = tp->host;
7605 peerStats->port = tp->port;
7606 peerStats->ifMTU = tp->ifMTU;
7607 peerStats->idleWhen = tp->idleWhen;
7608 peerStats->refCount = tp->refCount;
7609 peerStats->burstSize = tp->burstSize;
7610 peerStats->burst = tp->burst;
7611 peerStats->burstWait.sec = tp->burstWait.sec;
7612 peerStats->burstWait.usec = tp->burstWait.usec;
7613 peerStats->rtt = tp->rtt;
7614 peerStats->rtt_dev = tp->rtt_dev;
7615 peerStats->timeout.sec = tp->timeout.sec;
7616 peerStats->timeout.usec = tp->timeout.usec;
7617 peerStats->nSent = tp->nSent;
7618 peerStats->reSends = tp->reSends;
7619 peerStats->inPacketSkew = tp->inPacketSkew;
7620 peerStats->outPacketSkew = tp->outPacketSkew;
7621 peerStats->rateFlag = tp->rateFlag;
7622 peerStats->natMTU = tp->natMTU;
7623 peerStats->maxMTU = tp->maxMTU;
7624 peerStats->maxDgramPackets = tp->maxDgramPackets;
7625 peerStats->ifDgramPackets = tp->ifDgramPackets;
7626 peerStats->MTU = tp->MTU;
7627 peerStats->cwind = tp->cwind;
7628 peerStats->nDgramPackets = tp->nDgramPackets;
7629 peerStats->congestSeq = tp->congestSeq;
7630 peerStats->bytesSent.high = tp->bytesSent.high;
7631 peerStats->bytesSent.low = tp->bytesSent.low;
7632 peerStats->bytesReceived.high = tp->bytesReceived.high;
7633 peerStats->bytesReceived.low = tp->bytesReceived.low;
7634 MUTEX_EXIT(&tp->peer_lock);
7636 MUTEX_ENTER(&rx_peerHashTable_lock);
7639 MUTEX_EXIT(&rx_peerHashTable_lock);
7647 struct rx_serverQueueEntry *np;
7650 struct rx_call *call;
7651 struct rx_serverQueueEntry *sq;
7655 if (rxinit_status == 1) {
7657 return; /* Already shutdown. */
7661 #ifndef AFS_PTHREAD_ENV
7662 FD_ZERO(&rx_selectMask);
7663 #endif /* AFS_PTHREAD_ENV */
7664 rxi_dataQuota = RX_MAX_QUOTA;
7665 #ifndef AFS_PTHREAD_ENV
7667 #endif /* AFS_PTHREAD_ENV */
7670 #ifndef AFS_PTHREAD_ENV
7671 #ifndef AFS_USE_GETTIMEOFDAY
7673 #endif /* AFS_USE_GETTIMEOFDAY */
7674 #endif /* AFS_PTHREAD_ENV */
7676 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7677 call = queue_First(&rx_freeCallQueue, rx_call);
7679 rxi_Free(call, sizeof(struct rx_call));
7682 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7683 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7689 struct rx_peer **peer_ptr, **peer_end;
7690 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7691 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7693 struct rx_peer *peer, *next;
7695 MUTEX_ENTER(&rx_peerHashTable_lock);
7696 for (peer = *peer_ptr; peer; peer = next) {
7697 rx_interface_stat_p rpc_stat, nrpc_stat;
7700 MUTEX_ENTER(&rx_rpc_stats);
7701 MUTEX_ENTER(&peer->peer_lock);
7703 (&peer->rpcStats, rpc_stat, nrpc_stat,
7704 rx_interface_stat)) {
7705 unsigned int num_funcs;
7708 queue_Remove(&rpc_stat->queue_header);
7709 queue_Remove(&rpc_stat->all_peers);
7710 num_funcs = rpc_stat->stats[0].func_total;
7712 sizeof(rx_interface_stat_t) +
7713 rpc_stat->stats[0].func_total *
7714 sizeof(rx_function_entry_v1_t);
7716 rxi_Free(rpc_stat, space);
7718 /* rx_rpc_stats must be held */
7719 rxi_rpc_peer_stat_cnt -= num_funcs;
7721 MUTEX_EXIT(&peer->peer_lock);
7722 MUTEX_EXIT(&rx_rpc_stats);
7726 if (rx_stats_active)
7727 rx_atomic_dec(&rx_stats.nPeerStructs);
7729 MUTEX_EXIT(&rx_peerHashTable_lock);
7732 for (i = 0; i < RX_MAX_SERVICES; i++) {
7734 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7736 for (i = 0; i < rx_hashTableSize; i++) {
7737 struct rx_connection *tc, *ntc;
7738 MUTEX_ENTER(&rx_connHashTable_lock);
7739 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7741 for (j = 0; j < RX_MAXCALLS; j++) {
7743 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7746 rxi_Free(tc, sizeof(*tc));
7748 MUTEX_EXIT(&rx_connHashTable_lock);
7751 MUTEX_ENTER(&freeSQEList_lock);
7753 while ((np = rx_FreeSQEList)) {
7754 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7755 MUTEX_DESTROY(&np->lock);
7756 rxi_Free(np, sizeof(*np));
7759 MUTEX_EXIT(&freeSQEList_lock);
7760 MUTEX_DESTROY(&freeSQEList_lock);
7761 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7762 MUTEX_DESTROY(&rx_connHashTable_lock);
7763 MUTEX_DESTROY(&rx_peerHashTable_lock);
7764 MUTEX_DESTROY(&rx_serverPool_lock);
7766 osi_Free(rx_connHashTable,
7767 rx_hashTableSize * sizeof(struct rx_connection *));
7768 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7770 UNPIN(rx_connHashTable,
7771 rx_hashTableSize * sizeof(struct rx_connection *));
7772 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7774 rxi_FreeAllPackets();
7776 MUTEX_ENTER(&rx_quota_mutex);
7777 rxi_dataQuota = RX_MAX_QUOTA;
7778 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7779 MUTEX_EXIT(&rx_quota_mutex);
7784 #ifdef RX_ENABLE_LOCKS
7786 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7788 if (!MUTEX_ISMINE(lockaddr))
7789 osi_Panic("Lock not held: %s", msg);
7791 #endif /* RX_ENABLE_LOCKS */
7796 * Routines to implement connection specific data.
7800 rx_KeyCreate(rx_destructor_t rtn)
7803 MUTEX_ENTER(&rxi_keyCreate_lock);
7804 key = rxi_keyCreate_counter++;
7805 rxi_keyCreate_destructor = (rx_destructor_t *)
7806 realloc((void *)rxi_keyCreate_destructor,
7807 (key + 1) * sizeof(rx_destructor_t));
7808 rxi_keyCreate_destructor[key] = rtn;
7809 MUTEX_EXIT(&rxi_keyCreate_lock);
7814 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7817 MUTEX_ENTER(&conn->conn_data_lock);
7818 if (!conn->specific) {
7819 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7820 for (i = 0; i < key; i++)
7821 conn->specific[i] = NULL;
7822 conn->nSpecific = key + 1;
7823 conn->specific[key] = ptr;
7824 } else if (key >= conn->nSpecific) {
7825 conn->specific = (void **)
7826 realloc(conn->specific, (key + 1) * sizeof(void *));
7827 for (i = conn->nSpecific; i < key; i++)
7828 conn->specific[i] = NULL;
7829 conn->nSpecific = key + 1;
7830 conn->specific[key] = ptr;
7832 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7833 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7834 conn->specific[key] = ptr;
7836 MUTEX_EXIT(&conn->conn_data_lock);
7840 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7843 MUTEX_ENTER(&svc->svc_data_lock);
7844 if (!svc->specific) {
7845 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7846 for (i = 0; i < key; i++)
7847 svc->specific[i] = NULL;
7848 svc->nSpecific = key + 1;
7849 svc->specific[key] = ptr;
7850 } else if (key >= svc->nSpecific) {
7851 svc->specific = (void **)
7852 realloc(svc->specific, (key + 1) * sizeof(void *));
7853 for (i = svc->nSpecific; i < key; i++)
7854 svc->specific[i] = NULL;
7855 svc->nSpecific = key + 1;
7856 svc->specific[key] = ptr;
7858 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7859 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7860 svc->specific[key] = ptr;
7862 MUTEX_EXIT(&svc->svc_data_lock);
7866 rx_GetSpecific(struct rx_connection *conn, int key)
7869 MUTEX_ENTER(&conn->conn_data_lock);
7870 if (key >= conn->nSpecific)
7873 ptr = conn->specific[key];
7874 MUTEX_EXIT(&conn->conn_data_lock);
7879 rx_GetServiceSpecific(struct rx_service *svc, int key)
7882 MUTEX_ENTER(&svc->svc_data_lock);
7883 if (key >= svc->nSpecific)
7886 ptr = svc->specific[key];
7887 MUTEX_EXIT(&svc->svc_data_lock);
7892 #endif /* !KERNEL */
7895 * processStats is a queue used to store the statistics for the local
7896 * process. Its contents are similar to the contents of the rpcStats
7897 * queue on a rx_peer structure, but the actual data stored within
7898 * this queue contains totals across the lifetime of the process (assuming
7899 * the stats have not been reset) - unlike the per peer structures
7900 * which can come and go based upon the peer lifetime.
7903 static struct rx_queue processStats = { &processStats, &processStats };
7906 * peerStats is a queue used to store the statistics for all peer structs.
7907 * Its contents are the union of all the peer rpcStats queues.
7910 static struct rx_queue peerStats = { &peerStats, &peerStats };
7913 * rxi_monitor_processStats is used to turn process wide stat collection
7917 static int rxi_monitor_processStats = 0;
7920 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7923 static int rxi_monitor_peerStats = 0;
7926 * rxi_AddRpcStat - given all of the information for a particular rpc
7927 * call, create (if needed) and update the stat totals for the rpc.
7931 * IN stats - the queue of stats that will be updated with the new value
7933 * IN rxInterface - a unique number that identifies the rpc interface
7935 * IN currentFunc - the index of the function being invoked
7937 * IN totalFunc - the total number of functions in this interface
7939 * IN queueTime - the amount of time this function waited for a thread
7941 * IN execTime - the amount of time this function invocation took to execute
7943 * IN bytesSent - the number bytes sent by this invocation
7945 * IN bytesRcvd - the number bytes received by this invocation
7947 * IN isServer - if true, this invocation was made to a server
7949 * IN remoteHost - the ip address of the remote host
7951 * IN remotePort - the port of the remote host
7953 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7955 * INOUT counter - if a new stats structure is allocated, the counter will
7956 * be updated with the new number of allocated stat structures
7964 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7965 afs_uint32 currentFunc, afs_uint32 totalFunc,
7966 struct clock *queueTime, struct clock *execTime,
7967 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7968 afs_uint32 remoteHost, afs_uint32 remotePort,
7969 int addToPeerList, unsigned int *counter)
7972 rx_interface_stat_p rpc_stat, nrpc_stat;
7975 * See if there's already a structure for this interface
7978 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7979 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7980 && (rpc_stat->stats[0].remote_is_server == isServer))
7985 * Didn't find a match so allocate a new structure and add it to the
7989 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7990 || (rpc_stat->stats[0].interfaceId != rxInterface)
7991 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7996 sizeof(rx_interface_stat_t) +
7997 totalFunc * sizeof(rx_function_entry_v1_t);
7999 rpc_stat = rxi_Alloc(space);
8000 if (rpc_stat == NULL) {
8004 *counter += totalFunc;
8005 for (i = 0; i < totalFunc; i++) {
8006 rpc_stat->stats[i].remote_peer = remoteHost;
8007 rpc_stat->stats[i].remote_port = remotePort;
8008 rpc_stat->stats[i].remote_is_server = isServer;
8009 rpc_stat->stats[i].interfaceId = rxInterface;
8010 rpc_stat->stats[i].func_total = totalFunc;
8011 rpc_stat->stats[i].func_index = i;
8012 hzero(rpc_stat->stats[i].invocations);
8013 hzero(rpc_stat->stats[i].bytes_sent);
8014 hzero(rpc_stat->stats[i].bytes_rcvd);
8015 rpc_stat->stats[i].queue_time_sum.sec = 0;
8016 rpc_stat->stats[i].queue_time_sum.usec = 0;
8017 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8018 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8019 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8020 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8021 rpc_stat->stats[i].queue_time_max.sec = 0;
8022 rpc_stat->stats[i].queue_time_max.usec = 0;
8023 rpc_stat->stats[i].execution_time_sum.sec = 0;
8024 rpc_stat->stats[i].execution_time_sum.usec = 0;
8025 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8026 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8027 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8028 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8029 rpc_stat->stats[i].execution_time_max.sec = 0;
8030 rpc_stat->stats[i].execution_time_max.usec = 0;
8032 queue_Prepend(stats, rpc_stat);
8033 if (addToPeerList) {
8034 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8039 * Increment the stats for this function
8042 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8043 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8044 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8045 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8046 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8047 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8048 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8050 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8051 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8053 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8054 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8056 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8057 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8059 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8060 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8068 * rx_IncrementTimeAndCount - increment the times and count for a particular
8073 * IN peer - the peer who invoked the rpc
8075 * IN rxInterface - a unique number that identifies the rpc interface
8077 * IN currentFunc - the index of the function being invoked
8079 * IN totalFunc - the total number of functions in this interface
8081 * IN queueTime - the amount of time this function waited for a thread
8083 * IN execTime - the amount of time this function invocation took to execute
8085 * IN bytesSent - the number bytes sent by this invocation
8087 * IN bytesRcvd - the number bytes received by this invocation
8089 * IN isServer - if true, this invocation was made to a server
8097 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8098 afs_uint32 currentFunc, afs_uint32 totalFunc,
8099 struct clock *queueTime, struct clock *execTime,
8100 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8104 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8107 MUTEX_ENTER(&rx_rpc_stats);
8109 if (rxi_monitor_peerStats) {
8110 MUTEX_ENTER(&peer->peer_lock);
8111 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8112 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8113 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8114 MUTEX_EXIT(&peer->peer_lock);
8117 if (rxi_monitor_processStats) {
8118 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8119 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8120 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8123 MUTEX_EXIT(&rx_rpc_stats);
8128 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8132 * IN callerVersion - the rpc stat version of the caller.
8134 * IN count - the number of entries to marshall.
8136 * IN stats - pointer to stats to be marshalled.
8138 * OUT ptr - Where to store the marshalled data.
8145 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8146 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8152 * We only support the first version
8154 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8155 *(ptr++) = stats->remote_peer;
8156 *(ptr++) = stats->remote_port;
8157 *(ptr++) = stats->remote_is_server;
8158 *(ptr++) = stats->interfaceId;
8159 *(ptr++) = stats->func_total;
8160 *(ptr++) = stats->func_index;
8161 *(ptr++) = hgethi(stats->invocations);
8162 *(ptr++) = hgetlo(stats->invocations);
8163 *(ptr++) = hgethi(stats->bytes_sent);
8164 *(ptr++) = hgetlo(stats->bytes_sent);
8165 *(ptr++) = hgethi(stats->bytes_rcvd);
8166 *(ptr++) = hgetlo(stats->bytes_rcvd);
8167 *(ptr++) = stats->queue_time_sum.sec;
8168 *(ptr++) = stats->queue_time_sum.usec;
8169 *(ptr++) = stats->queue_time_sum_sqr.sec;
8170 *(ptr++) = stats->queue_time_sum_sqr.usec;
8171 *(ptr++) = stats->queue_time_min.sec;
8172 *(ptr++) = stats->queue_time_min.usec;
8173 *(ptr++) = stats->queue_time_max.sec;
8174 *(ptr++) = stats->queue_time_max.usec;
8175 *(ptr++) = stats->execution_time_sum.sec;
8176 *(ptr++) = stats->execution_time_sum.usec;
8177 *(ptr++) = stats->execution_time_sum_sqr.sec;
8178 *(ptr++) = stats->execution_time_sum_sqr.usec;
8179 *(ptr++) = stats->execution_time_min.sec;
8180 *(ptr++) = stats->execution_time_min.usec;
8181 *(ptr++) = stats->execution_time_max.sec;
8182 *(ptr++) = stats->execution_time_max.usec;
8188 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8193 * IN callerVersion - the rpc stat version of the caller
8195 * OUT myVersion - the rpc stat version of this function
8197 * OUT clock_sec - local time seconds
8199 * OUT clock_usec - local time microseconds
8201 * OUT allocSize - the number of bytes allocated to contain stats
8203 * OUT statCount - the number stats retrieved from this process.
8205 * OUT stats - the actual stats retrieved from this process.
8209 * Returns void. If successful, stats will != NULL.
8213 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8214 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8215 size_t * allocSize, afs_uint32 * statCount,
8216 afs_uint32 ** stats)
8226 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8229 * Check to see if stats are enabled
8232 MUTEX_ENTER(&rx_rpc_stats);
8233 if (!rxi_monitor_processStats) {
8234 MUTEX_EXIT(&rx_rpc_stats);
8238 clock_GetTime(&now);
8239 *clock_sec = now.sec;
8240 *clock_usec = now.usec;
8243 * Allocate the space based upon the caller version
8245 * If the client is at an older version than we are,
8246 * we return the statistic data in the older data format, but
8247 * we still return our version number so the client knows we
8248 * are maintaining more data than it can retrieve.
8251 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8252 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8253 *statCount = rxi_rpc_process_stat_cnt;
8256 * This can't happen yet, but in the future version changes
8257 * can be handled by adding additional code here
8261 if (space > (size_t) 0) {
8263 ptr = *stats = rxi_Alloc(space);
8266 rx_interface_stat_p rpc_stat, nrpc_stat;
8270 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8272 * Copy the data based upon the caller version
8274 rx_MarshallProcessRPCStats(callerVersion,
8275 rpc_stat->stats[0].func_total,
8276 rpc_stat->stats, &ptr);
8282 MUTEX_EXIT(&rx_rpc_stats);
8287 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8291 * IN callerVersion - the rpc stat version of the caller
8293 * OUT myVersion - the rpc stat version of this function
8295 * OUT clock_sec - local time seconds
8297 * OUT clock_usec - local time microseconds
8299 * OUT allocSize - the number of bytes allocated to contain stats
8301 * OUT statCount - the number of stats retrieved from the individual
8304 * OUT stats - the actual stats retrieved from the individual peer structures.
8308 * Returns void. If successful, stats will != NULL.
8312 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8313 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8314 size_t * allocSize, afs_uint32 * statCount,
8315 afs_uint32 ** stats)
8325 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8328 * Check to see if stats are enabled
8331 MUTEX_ENTER(&rx_rpc_stats);
8332 if (!rxi_monitor_peerStats) {
8333 MUTEX_EXIT(&rx_rpc_stats);
8337 clock_GetTime(&now);
8338 *clock_sec = now.sec;
8339 *clock_usec = now.usec;
8342 * Allocate the space based upon the caller version
8344 * If the client is at an older version than we are,
8345 * we return the statistic data in the older data format, but
8346 * we still return our version number so the client knows we
8347 * are maintaining more data than it can retrieve.
8350 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8351 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8352 *statCount = rxi_rpc_peer_stat_cnt;
8355 * This can't happen yet, but in the future version changes
8356 * can be handled by adding additional code here
8360 if (space > (size_t) 0) {
8362 ptr = *stats = rxi_Alloc(space);
8365 rx_interface_stat_p rpc_stat, nrpc_stat;
8369 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8371 * We have to fix the offset of rpc_stat since we are
8372 * keeping this structure on two rx_queues. The rx_queue
8373 * package assumes that the rx_queue member is the first
8374 * member of the structure. That is, rx_queue assumes that
8375 * any one item is only on one queue at a time. We are
8376 * breaking that assumption and so we have to do a little
8377 * math to fix our pointers.
8380 fix_offset = (char *)rpc_stat;
8381 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8382 rpc_stat = (rx_interface_stat_p) fix_offset;
8385 * Copy the data based upon the caller version
8387 rx_MarshallProcessRPCStats(callerVersion,
8388 rpc_stat->stats[0].func_total,
8389 rpc_stat->stats, &ptr);
8395 MUTEX_EXIT(&rx_rpc_stats);
8400 * rx_FreeRPCStats - free memory allocated by
8401 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8405 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8406 * rx_RetrievePeerRPCStats
8408 * IN allocSize - the number of bytes in stats.
8416 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8418 rxi_Free(stats, allocSize);
8422 * rx_queryProcessRPCStats - see if process rpc stat collection is
8423 * currently enabled.
8429 * Returns 0 if stats are not enabled != 0 otherwise
8433 rx_queryProcessRPCStats(void)
8436 MUTEX_ENTER(&rx_rpc_stats);
8437 rc = rxi_monitor_processStats;
8438 MUTEX_EXIT(&rx_rpc_stats);
8443 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8449 * Returns 0 if stats are not enabled != 0 otherwise
8453 rx_queryPeerRPCStats(void)
8456 MUTEX_ENTER(&rx_rpc_stats);
8457 rc = rxi_monitor_peerStats;
8458 MUTEX_EXIT(&rx_rpc_stats);
8463 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8473 rx_enableProcessRPCStats(void)
8475 MUTEX_ENTER(&rx_rpc_stats);
8476 rx_enable_stats = 1;
8477 rxi_monitor_processStats = 1;
8478 MUTEX_EXIT(&rx_rpc_stats);
8482 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8492 rx_enablePeerRPCStats(void)
8494 MUTEX_ENTER(&rx_rpc_stats);
8495 rx_enable_stats = 1;
8496 rxi_monitor_peerStats = 1;
8497 MUTEX_EXIT(&rx_rpc_stats);
8501 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8511 rx_disableProcessRPCStats(void)
8513 rx_interface_stat_p rpc_stat, nrpc_stat;
8516 MUTEX_ENTER(&rx_rpc_stats);
8519 * Turn off process statistics and if peer stats is also off, turn
8523 rxi_monitor_processStats = 0;
8524 if (rxi_monitor_peerStats == 0) {
8525 rx_enable_stats = 0;
8528 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8529 unsigned int num_funcs = 0;
8532 queue_Remove(rpc_stat);
8533 num_funcs = rpc_stat->stats[0].func_total;
8535 sizeof(rx_interface_stat_t) +
8536 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8538 rxi_Free(rpc_stat, space);
8539 rxi_rpc_process_stat_cnt -= num_funcs;
8541 MUTEX_EXIT(&rx_rpc_stats);
8545 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8555 rx_disablePeerRPCStats(void)
8557 struct rx_peer **peer_ptr, **peer_end;
8561 * Turn off peer statistics and if process stats is also off, turn
8565 rxi_monitor_peerStats = 0;
8566 if (rxi_monitor_processStats == 0) {
8567 rx_enable_stats = 0;
8570 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8571 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8573 struct rx_peer *peer, *next, *prev;
8575 MUTEX_ENTER(&rx_peerHashTable_lock);
8576 MUTEX_ENTER(&rx_rpc_stats);
8577 for (prev = peer = *peer_ptr; peer; peer = next) {
8579 code = MUTEX_TRYENTER(&peer->peer_lock);
8581 rx_interface_stat_p rpc_stat, nrpc_stat;
8584 if (prev == *peer_ptr) {
8595 MUTEX_EXIT(&rx_peerHashTable_lock);
8598 (&peer->rpcStats, rpc_stat, nrpc_stat,
8599 rx_interface_stat)) {
8600 unsigned int num_funcs = 0;
8603 queue_Remove(&rpc_stat->queue_header);
8604 queue_Remove(&rpc_stat->all_peers);
8605 num_funcs = rpc_stat->stats[0].func_total;
8607 sizeof(rx_interface_stat_t) +
8608 rpc_stat->stats[0].func_total *
8609 sizeof(rx_function_entry_v1_t);
8611 rxi_Free(rpc_stat, space);
8612 rxi_rpc_peer_stat_cnt -= num_funcs;
8614 MUTEX_EXIT(&peer->peer_lock);
8616 MUTEX_ENTER(&rx_peerHashTable_lock);
8626 MUTEX_EXIT(&rx_rpc_stats);
8627 MUTEX_EXIT(&rx_peerHashTable_lock);
8632 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8637 * IN clearFlag - flag indicating which stats to clear
8645 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8647 rx_interface_stat_p rpc_stat, nrpc_stat;
8649 MUTEX_ENTER(&rx_rpc_stats);
8651 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8652 unsigned int num_funcs = 0, i;
8653 num_funcs = rpc_stat->stats[0].func_total;
8654 for (i = 0; i < num_funcs; i++) {
8655 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8656 hzero(rpc_stat->stats[i].invocations);
8658 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8659 hzero(rpc_stat->stats[i].bytes_sent);
8661 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8662 hzero(rpc_stat->stats[i].bytes_rcvd);
8664 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8665 rpc_stat->stats[i].queue_time_sum.sec = 0;
8666 rpc_stat->stats[i].queue_time_sum.usec = 0;
8668 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8669 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8670 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8672 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8673 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8674 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8676 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8677 rpc_stat->stats[i].queue_time_max.sec = 0;
8678 rpc_stat->stats[i].queue_time_max.usec = 0;
8680 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8681 rpc_stat->stats[i].execution_time_sum.sec = 0;
8682 rpc_stat->stats[i].execution_time_sum.usec = 0;
8684 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8685 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8686 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8688 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8689 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8690 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8692 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8693 rpc_stat->stats[i].execution_time_max.sec = 0;
8694 rpc_stat->stats[i].execution_time_max.usec = 0;
8699 MUTEX_EXIT(&rx_rpc_stats);
8703 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8708 * IN clearFlag - flag indicating which stats to clear
8716 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8718 rx_interface_stat_p rpc_stat, nrpc_stat;
8720 MUTEX_ENTER(&rx_rpc_stats);
8722 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8723 unsigned int num_funcs = 0, i;
8726 * We have to fix the offset of rpc_stat since we are
8727 * keeping this structure on two rx_queues. The rx_queue
8728 * package assumes that the rx_queue member is the first
8729 * member of the structure. That is, rx_queue assumes that
8730 * any one item is only on one queue at a time. We are
8731 * breaking that assumption and so we have to do a little
8732 * math to fix our pointers.
8735 fix_offset = (char *)rpc_stat;
8736 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8737 rpc_stat = (rx_interface_stat_p) fix_offset;
8739 num_funcs = rpc_stat->stats[0].func_total;
8740 for (i = 0; i < num_funcs; i++) {
8741 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8742 hzero(rpc_stat->stats[i].invocations);
8744 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8745 hzero(rpc_stat->stats[i].bytes_sent);
8747 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8748 hzero(rpc_stat->stats[i].bytes_rcvd);
8750 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8751 rpc_stat->stats[i].queue_time_sum.sec = 0;
8752 rpc_stat->stats[i].queue_time_sum.usec = 0;
8754 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8755 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8756 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8758 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8759 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8760 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8762 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8763 rpc_stat->stats[i].queue_time_max.sec = 0;
8764 rpc_stat->stats[i].queue_time_max.usec = 0;
8766 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8767 rpc_stat->stats[i].execution_time_sum.sec = 0;
8768 rpc_stat->stats[i].execution_time_sum.usec = 0;
8770 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8771 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8772 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8774 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8775 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8776 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8778 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8779 rpc_stat->stats[i].execution_time_max.sec = 0;
8780 rpc_stat->stats[i].execution_time_max.usec = 0;
8785 MUTEX_EXIT(&rx_rpc_stats);
8789 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8790 * is authorized to enable/disable/clear RX statistics.
8792 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8795 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8797 rxi_rxstat_userok = proc;
8801 rx_RxStatUserOk(struct rx_call *call)
8803 if (!rxi_rxstat_userok)
8805 return rxi_rxstat_userok(call);
8810 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8811 * function in the MSVC runtime DLL (msvcrt.dll).
8813 * Note: the system serializes calls to this function.
8816 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8817 DWORD reason, /* reason function is being called */
8818 LPVOID reserved) /* reserved for future use */
8821 case DLL_PROCESS_ATTACH:
8822 /* library is being attached to a process */
8826 case DLL_PROCESS_DETACH:
8833 #endif /* AFS_NT40_ENV */
8836 int rx_DumpCalls(FILE *outputFile, char *cookie)
8838 #ifdef RXDEBUG_PACKET
8839 #ifdef KDUMP_RX_LOCK
8840 struct rx_call_rx_lock *c;
8847 #define RXDPRINTF sprintf
8848 #define RXDPRINTOUT output
8850 #define RXDPRINTF fprintf
8851 #define RXDPRINTOUT outputFile
8854 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8856 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8859 for (c = rx_allCallsp; c; c = c->allNextp) {
8860 u_short rqc, tqc, iovqc;
8861 struct rx_packet *p, *np;
8863 MUTEX_ENTER(&c->lock);
8864 queue_Count(&c->rq, p, np, rx_packet, rqc);
8865 queue_Count(&c->tq, p, np, rx_packet, tqc);
8866 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8868 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, "
8869 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8870 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8871 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8872 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8873 #ifdef RX_ENABLE_LOCKS
8876 #ifdef RX_REFCOUNT_CHECK
8877 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8878 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8881 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,
8882 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8883 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8884 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8885 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8886 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8887 #ifdef RX_ENABLE_LOCKS
8888 , (afs_uint32)c->refCount
8890 #ifdef RX_REFCOUNT_CHECK
8891 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8894 MUTEX_EXIT(&c->lock);
8897 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8900 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8902 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8904 #endif /* RXDEBUG_PACKET */