2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
30 # include "inet/common.h"
32 # include "inet/ip_ire.h"
34 # include "afs/afs_args.h"
35 # include "afs/afs_osi.h"
36 # ifdef RX_KERNEL_TRACE
37 # include "rx_kcommon.h"
39 # if defined(AFS_AIX_ENV)
43 # undef RXDEBUG /* turn off debugging */
45 # if defined(AFS_SGI_ENV)
46 # include "sys/debug.h"
49 # include "afs/sysincludes.h"
50 # include "afsincludes.h"
51 # endif /* !UKERNEL */
52 # include "afs/lock.h"
53 # include "rx_kmutex.h"
54 # include "rx_kernel.h"
55 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
56 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
57 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
58 extern afs_int32 afs_termState;
60 # include "sys/lockl.h"
61 # include "sys/lock_def.h"
62 # endif /* AFS_AIX41_ENV */
63 # include "afs/rxgen_consts.h"
68 # include <afs/afsutil.h>
69 # include <WINNT\afsreg.h>
78 #include "rx_atomic.h"
79 #include "rx_globals.h"
81 #include "rx_internal.h"
84 #include <afs/rxgen_consts.h>
87 #ifdef AFS_PTHREAD_ENV
89 int (*registerProgram) (pid_t, char *) = 0;
90 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
93 int (*registerProgram) (PROCESS, char *) = 0;
94 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
98 /* Local static routines */
99 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
100 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
101 struct rx_peer *, struct clock *);
103 #ifdef RX_ENABLE_LOCKS
104 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
107 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
109 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
110 rx_atomic_t rxi_start_in_error;
112 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
115 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
116 * currently allocated within rx. This number is used to allocate the
117 * memory required to return the statistics when queried.
118 * Protected by the rx_rpc_stats mutex.
121 static unsigned int rxi_rpc_peer_stat_cnt;
124 * rxi_rpc_process_stat_cnt counts the total number of local process stat
125 * structures currently allocated within rx. The number is used to allocate
126 * the memory required to return the statistics when queried.
127 * Protected by the rx_rpc_stats mutex.
130 static unsigned int rxi_rpc_process_stat_cnt;
133 * rxi_busyChannelError is the error to return to the application when a call
134 * channel appears busy (inferred from the receipt of RX_PACKET_TYPE_BUSY
135 * packets on the channel), and there are other call channels in the
136 * connection that are not busy. If 0, we do not return errors upon receiving
137 * busy packets; we just keep trying on the same call channel until we hit a
140 static afs_int32 rxi_busyChannelError = 0;
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 /* Forward prototypes */
154 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
156 #ifdef AFS_PTHREAD_ENV
159 * Use procedural initialization of mutexes/condition variables
163 extern afs_kmutex_t rx_quota_mutex;
164 extern afs_kmutex_t rx_pthread_mutex;
165 extern afs_kmutex_t rx_packets_mutex;
166 extern afs_kmutex_t rx_refcnt_mutex;
167 extern afs_kmutex_t des_init_mutex;
168 extern afs_kmutex_t des_random_mutex;
169 extern afs_kmutex_t rx_clock_mutex;
170 extern afs_kmutex_t rxi_connCacheMutex;
171 extern afs_kmutex_t rx_event_mutex;
172 extern afs_kmutex_t event_handler_mutex;
173 extern afs_kmutex_t listener_mutex;
174 extern afs_kmutex_t rx_if_init_mutex;
175 extern afs_kmutex_t rx_if_mutex;
176 extern afs_kmutex_t rxkad_client_uid_mutex;
177 extern afs_kmutex_t rxkad_random_mutex;
179 extern afs_kcondvar_t rx_event_handler_cond;
180 extern afs_kcondvar_t rx_listener_cond;
182 static afs_kmutex_t epoch_mutex;
183 static afs_kmutex_t rx_init_mutex;
184 static afs_kmutex_t rx_debug_mutex;
185 static afs_kmutex_t rx_rpc_stats;
188 rxi_InitPthread(void)
190 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
191 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
192 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
193 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
194 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
209 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
210 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
212 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
213 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
215 rxkad_global_stats_init();
217 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
219 #ifdef RX_ENABLE_LOCKS
222 #endif /* RX_LOCKS_DB */
223 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
224 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
226 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
228 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
230 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
232 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
233 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
234 #endif /* RX_ENABLE_LOCKS */
237 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
238 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
240 * The rx_stats_mutex mutex protects the following global variables:
241 * rxi_lowConnRefCount
242 * rxi_lowPeerRefCount
251 * The rx_quota_mutex mutex protects the following global variables:
259 * The rx_freePktQ_lock protects the following global variables:
264 * The rx_packets_mutex mutex protects the following global variables:
272 * The rx_pthread_mutex mutex protects the following global variables:
273 * rxi_fcfs_thread_num
276 #define INIT_PTHREAD_LOCKS
280 /* Variables for handling the minProcs implementation. availProcs gives the
281 * number of threads available in the pool at this moment (not counting dudes
282 * executing right now). totalMin gives the total number of procs required
283 * for handling all minProcs requests. minDeficit is a dynamic variable
284 * tracking the # of procs required to satisfy all of the remaining minProcs
286 * For fine grain locking to work, the quota check and the reservation of
287 * a server thread has to come while rxi_availProcs and rxi_minDeficit
288 * are locked. To this end, the code has been modified under #ifdef
289 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
290 * same time. A new function, ReturnToServerPool() returns the allocation.
292 * A call can be on several queue's (but only one at a time). When
293 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
294 * that no one else is touching the queue. To this end, we store the address
295 * of the queue lock in the call structure (under the call lock) when we
296 * put the call on a queue, and we clear the call_queue_lock when the
297 * call is removed from a queue (once the call lock has been obtained).
298 * This allows rxi_ResetCall to safely synchronize with others wishing
299 * to manipulate the queue.
302 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
303 static afs_kmutex_t rx_rpc_stats;
304 static void rxi_StartUnlocked(struct rxevent *event, void *call,
305 void *arg1, int istack);
308 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
309 ** pretty good that the next packet coming in is from the same connection
310 ** as the last packet, since we're send multiple packets in a transmit window.
312 struct rx_connection *rxLastConn = 0;
314 #ifdef RX_ENABLE_LOCKS
315 /* The locking hierarchy for rx fine grain locking is composed of these
318 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
319 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
320 * call->lock - locks call data fields.
321 * These are independent of each other:
322 * rx_freeCallQueue_lock
327 * serverQueueEntry->lock
328 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
330 * peer->lock - locks peer data fields.
331 * conn_data_lock - that more than one thread is not updating a conn data
332 * field at the same time.
343 * Do we need a lock to protect the peer field in the conn structure?
344 * conn->peer was previously a constant for all intents and so has no
345 * lock protecting this field. The multihomed client delta introduced
346 * a RX code change : change the peer field in the connection structure
347 * to that remote interface from which the last packet for this
348 * connection was sent out. This may become an issue if further changes
351 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
352 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
354 /* rxdb_fileID is used to identify the lock location, along with line#. */
355 static int rxdb_fileID = RXDB_FILE_RX;
356 #endif /* RX_LOCKS_DB */
357 #else /* RX_ENABLE_LOCKS */
358 #define SET_CALL_QUEUE_LOCK(C, L)
359 #define CLEAR_CALL_QUEUE_LOCK(C)
360 #endif /* RX_ENABLE_LOCKS */
361 struct rx_serverQueueEntry *rx_waitForPacket = 0;
362 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
364 /* ------------Exported Interfaces------------- */
366 /* This function allows rxkad to set the epoch to a suitably random number
367 * which rx_NewConnection will use in the future. The principle purpose is to
368 * get rxnull connections to use the same epoch as the rxkad connections do, at
369 * least once the first rxkad connection is established. This is important now
370 * that the host/port addresses aren't used in FindConnection: the uniqueness
371 * of epoch/cid matters and the start time won't do. */
373 #ifdef AFS_PTHREAD_ENV
375 * This mutex protects the following global variables:
379 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
380 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
384 #endif /* AFS_PTHREAD_ENV */
387 rx_SetEpoch(afs_uint32 epoch)
394 /* Initialize rx. A port number may be mentioned, in which case this
395 * becomes the default port number for any service installed later.
396 * If 0 is provided for the port number, a random port will be chosen
397 * by the kernel. Whether this will ever overlap anything in
398 * /etc/services is anybody's guess... Returns 0 on success, -1 on
403 int rxinit_status = 1;
404 #ifdef AFS_PTHREAD_ENV
406 * This mutex protects the following global variables:
410 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
411 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
414 #define UNLOCK_RX_INIT
418 rx_InitHost(u_int host, u_int port)
425 char *htable, *ptable;
432 if (rxinit_status == 0) {
433 tmp_status = rxinit_status;
435 return tmp_status; /* Already started; return previous error code. */
441 if (afs_winsockInit() < 0)
447 * Initialize anything necessary to provide a non-premptive threading
450 rxi_InitializeThreadSupport();
453 /* Allocate and initialize a socket for client and perhaps server
456 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
457 if (rx_socket == OSI_NULLSOCKET) {
461 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
464 #endif /* RX_LOCKS_DB */
465 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
466 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
467 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
468 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
469 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
470 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
471 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
472 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
475 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
477 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
479 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
481 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
482 #if defined(AFS_HPUX110_ENV)
484 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
485 #endif /* AFS_HPUX110_ENV */
486 #endif /* RX_ENABLE_LOCKS && KERNEL */
489 rx_connDeadTime = 12;
490 rx_tranquil = 0; /* reset flag */
491 rxi_ResetStatistics();
493 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
494 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
495 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
496 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
497 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
498 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
500 /* Malloc up a bunch of packets & buffers */
502 queue_Init(&rx_freePacketQueue);
503 rxi_NeedMorePackets = FALSE;
504 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
506 /* enforce a minimum number of allocated packets */
507 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
508 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
510 /* allocate the initial free packet pool */
511 #ifdef RX_ENABLE_TSFPQ
512 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
513 #else /* RX_ENABLE_TSFPQ */
514 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
515 #endif /* RX_ENABLE_TSFPQ */
522 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
523 tv.tv_sec = clock_now.sec;
524 tv.tv_usec = clock_now.usec;
525 srand((unsigned int)tv.tv_usec);
532 #if defined(KERNEL) && !defined(UKERNEL)
533 /* Really, this should never happen in a real kernel */
536 struct sockaddr_in addr;
538 int addrlen = sizeof(addr);
540 socklen_t addrlen = sizeof(addr);
542 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
546 rx_port = addr.sin_port;
549 rx_stats.minRtt.sec = 9999999;
551 rx_SetEpoch(tv.tv_sec | 0x80000000);
553 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
554 * will provide a randomer value. */
556 MUTEX_ENTER(&rx_quota_mutex);
557 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
558 MUTEX_EXIT(&rx_quota_mutex);
559 /* *Slightly* random start time for the cid. This is just to help
560 * out with the hashing function at the peer */
561 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
562 rx_connHashTable = (struct rx_connection **)htable;
563 rx_peerHashTable = (struct rx_peer **)ptable;
565 rx_lastAckDelay.sec = 0;
566 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
567 rx_hardAckDelay.sec = 0;
568 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
569 rx_softAckDelay.sec = 0;
570 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
572 rxevent_Init(20, rxi_ReScheduleEvents);
574 /* Initialize various global queues */
575 queue_Init(&rx_idleServerQueue);
576 queue_Init(&rx_incomingCallQueue);
577 queue_Init(&rx_freeCallQueue);
579 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
580 /* Initialize our list of usable IP addresses. */
584 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
585 /* Start listener process (exact function is dependent on the
586 * implementation environment--kernel or user space) */
591 tmp_status = rxinit_status = 0;
599 return rx_InitHost(htonl(INADDR_ANY), port);
603 * Sets the error generated when a busy call channel is detected.
605 * @param[in] error The error to return for a call on a busy channel.
607 * @pre Neither rx_Init nor rx_InitHost have been called yet
610 rx_SetBusyChannelError(afs_int32 error)
612 osi_Assert(rxinit_status != 0);
613 rxi_busyChannelError = error;
616 /* called with unincremented nRequestsRunning to see if it is OK to start
617 * a new thread in this service. Could be "no" for two reasons: over the
618 * max quota, or would prevent others from reaching their min quota.
620 #ifdef RX_ENABLE_LOCKS
621 /* This verion of QuotaOK reserves quota if it's ok while the
622 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
625 QuotaOK(struct rx_service *aservice)
627 /* check if over max quota */
628 if (aservice->nRequestsRunning >= aservice->maxProcs) {
632 /* under min quota, we're OK */
633 /* otherwise, can use only if there are enough to allow everyone
634 * to go to their min quota after this guy starts.
637 MUTEX_ENTER(&rx_quota_mutex);
638 if ((aservice->nRequestsRunning < aservice->minProcs)
639 || (rxi_availProcs > rxi_minDeficit)) {
640 aservice->nRequestsRunning++;
641 /* just started call in minProcs pool, need fewer to maintain
643 if (aservice->nRequestsRunning <= aservice->minProcs)
646 MUTEX_EXIT(&rx_quota_mutex);
649 MUTEX_EXIT(&rx_quota_mutex);
655 ReturnToServerPool(struct rx_service *aservice)
657 aservice->nRequestsRunning--;
658 MUTEX_ENTER(&rx_quota_mutex);
659 if (aservice->nRequestsRunning < aservice->minProcs)
662 MUTEX_EXIT(&rx_quota_mutex);
665 #else /* RX_ENABLE_LOCKS */
667 QuotaOK(struct rx_service *aservice)
670 /* under min quota, we're OK */
671 if (aservice->nRequestsRunning < aservice->minProcs)
674 /* check if over max quota */
675 if (aservice->nRequestsRunning >= aservice->maxProcs)
678 /* otherwise, can use only if there are enough to allow everyone
679 * to go to their min quota after this guy starts.
681 MUTEX_ENTER(&rx_quota_mutex);
682 if (rxi_availProcs > rxi_minDeficit)
684 MUTEX_EXIT(&rx_quota_mutex);
687 #endif /* RX_ENABLE_LOCKS */
690 /* Called by rx_StartServer to start up lwp's to service calls.
691 NExistingProcs gives the number of procs already existing, and which
692 therefore needn't be created. */
694 rxi_StartServerProcs(int nExistingProcs)
696 struct rx_service *service;
701 /* For each service, reserve N processes, where N is the "minimum"
702 * number of processes that MUST be able to execute a request in parallel,
703 * at any time, for that process. Also compute the maximum difference
704 * between any service's maximum number of processes that can run
705 * (i.e. the maximum number that ever will be run, and a guarantee
706 * that this number will run if other services aren't running), and its
707 * minimum number. The result is the extra number of processes that
708 * we need in order to provide the latter guarantee */
709 for (i = 0; i < RX_MAX_SERVICES; i++) {
711 service = rx_services[i];
712 if (service == (struct rx_service *)0)
714 nProcs += service->minProcs;
715 diff = service->maxProcs - service->minProcs;
719 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
720 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
721 for (i = 0; i < nProcs; i++) {
722 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
728 /* This routine is only required on Windows */
730 rx_StartClientThread(void)
732 #ifdef AFS_PTHREAD_ENV
734 pid = pthread_self();
735 #endif /* AFS_PTHREAD_ENV */
737 #endif /* AFS_NT40_ENV */
739 /* This routine must be called if any services are exported. If the
740 * donateMe flag is set, the calling process is donated to the server
743 rx_StartServer(int donateMe)
745 struct rx_service *service;
751 /* Start server processes, if necessary (exact function is dependent
752 * on the implementation environment--kernel or user space). DonateMe
753 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
754 * case, one less new proc will be created rx_StartServerProcs.
756 rxi_StartServerProcs(donateMe);
758 /* count up the # of threads in minProcs, and add set the min deficit to
759 * be that value, too.
761 for (i = 0; i < RX_MAX_SERVICES; i++) {
762 service = rx_services[i];
763 if (service == (struct rx_service *)0)
765 MUTEX_ENTER(&rx_quota_mutex);
766 rxi_totalMin += service->minProcs;
767 /* below works even if a thread is running, since minDeficit would
768 * still have been decremented and later re-incremented.
770 rxi_minDeficit += service->minProcs;
771 MUTEX_EXIT(&rx_quota_mutex);
774 /* Turn on reaping of idle server connections */
775 rxi_ReapConnections(NULL, NULL, NULL);
784 #ifdef AFS_PTHREAD_ENV
786 pid = afs_pointer_to_int(pthread_self());
787 #else /* AFS_PTHREAD_ENV */
789 LWP_CurrentProcess(&pid);
790 #endif /* AFS_PTHREAD_ENV */
792 sprintf(name, "srv_%d", ++nProcs);
794 (*registerProgram) (pid, name);
796 #endif /* AFS_NT40_ENV */
797 rx_ServerProc(NULL); /* Never returns */
799 #ifdef RX_ENABLE_TSFPQ
800 /* no use leaving packets around in this thread's local queue if
801 * it isn't getting donated to the server thread pool.
803 rxi_FlushLocalPacketsTSFPQ();
804 #endif /* RX_ENABLE_TSFPQ */
808 /* Create a new client connection to the specified service, using the
809 * specified security object to implement the security model for this
811 struct rx_connection *
812 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
813 struct rx_securityClass *securityObject,
814 int serviceSecurityIndex)
818 struct rx_connection *conn;
823 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
824 "serviceSecurityIndex %d)\n",
825 ntohl(shost), ntohs(sport), sservice, securityObject,
826 serviceSecurityIndex));
828 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
829 * the case of kmem_alloc? */
830 conn = rxi_AllocConnection();
831 #ifdef RX_ENABLE_LOCKS
832 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
833 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
834 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
837 MUTEX_ENTER(&rx_connHashTable_lock);
838 cid = (rx_nextCid += RX_MAXCALLS);
839 conn->type = RX_CLIENT_CONNECTION;
841 conn->epoch = rx_epoch;
842 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
843 conn->serviceId = sservice;
844 conn->securityObject = securityObject;
845 conn->securityData = (void *) 0;
846 conn->securityIndex = serviceSecurityIndex;
847 rx_SetConnDeadTime(conn, rx_connDeadTime);
848 rx_SetConnSecondsUntilNatPing(conn, 0);
849 conn->ackRate = RX_FAST_ACK_RATE;
851 conn->specific = NULL;
852 conn->challengeEvent = NULL;
853 conn->delayedAbortEvent = NULL;
854 conn->abortCount = 0;
856 for (i = 0; i < RX_MAXCALLS; i++) {
857 conn->twind[i] = rx_initSendWindow;
858 conn->rwind[i] = rx_initReceiveWindow;
859 conn->lastBusy[i] = 0;
862 RXS_NewConnection(securityObject, conn);
864 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
866 conn->refCount++; /* no lock required since only this thread knows... */
867 conn->next = rx_connHashTable[hashindex];
868 rx_connHashTable[hashindex] = conn;
870 rx_atomic_inc(&rx_stats.nClientConns);
871 MUTEX_EXIT(&rx_connHashTable_lock);
877 * Ensure a connection's timeout values are valid.
879 * @param[in] conn The connection to check
881 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
882 * unless idleDeadTime and/or hardDeadTime are not set
886 rxi_CheckConnTimeouts(struct rx_connection *conn)
888 /* a connection's timeouts must have the relationship
889 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
890 * total loss of network to a peer may cause an idle timeout instead of a
891 * dead timeout, simply because the idle timeout gets hit first. Also set
892 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
893 /* this logic is slightly complicated by the fact that
894 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
896 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
897 if (conn->idleDeadTime) {
898 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
900 if (conn->hardDeadTime) {
901 if (conn->idleDeadTime) {
902 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
904 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
910 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
912 /* The idea is to set the dead time to a value that allows several
913 * keepalives to be dropped without timing out the connection. */
914 conn->secondsUntilDead = seconds;
915 rxi_CheckConnTimeouts(conn);
916 conn->secondsUntilPing = conn->secondsUntilDead / 6;
920 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
922 conn->hardDeadTime = seconds;
923 rxi_CheckConnTimeouts(conn);
927 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
929 conn->idleDeadTime = seconds;
930 rxi_CheckConnTimeouts(conn);
933 int rxi_lowPeerRefCount = 0;
934 int rxi_lowConnRefCount = 0;
937 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
938 * NOTE: must not be called with rx_connHashTable_lock held.
941 rxi_CleanupConnection(struct rx_connection *conn)
943 /* Notify the service exporter, if requested, that this connection
944 * is being destroyed */
945 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
946 (*conn->service->destroyConnProc) (conn);
948 /* Notify the security module that this connection is being destroyed */
949 RXS_DestroyConnection(conn->securityObject, conn);
951 /* If this is the last connection using the rx_peer struct, set its
952 * idle time to now. rxi_ReapConnections will reap it if it's still
953 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
955 MUTEX_ENTER(&rx_peerHashTable_lock);
956 if (conn->peer->refCount < 2) {
957 conn->peer->idleWhen = clock_Sec();
958 if (conn->peer->refCount < 1) {
959 conn->peer->refCount = 1;
960 if (rx_stats_active) {
961 MUTEX_ENTER(&rx_stats_mutex);
962 rxi_lowPeerRefCount++;
963 MUTEX_EXIT(&rx_stats_mutex);
967 conn->peer->refCount--;
968 MUTEX_EXIT(&rx_peerHashTable_lock);
972 if (conn->type == RX_SERVER_CONNECTION)
973 rx_atomic_dec(&rx_stats.nServerConns);
975 rx_atomic_dec(&rx_stats.nClientConns);
978 if (conn->specific) {
980 for (i = 0; i < conn->nSpecific; i++) {
981 if (conn->specific[i] && rxi_keyCreate_destructor[i])
982 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
983 conn->specific[i] = NULL;
985 free(conn->specific);
987 conn->specific = NULL;
991 MUTEX_DESTROY(&conn->conn_call_lock);
992 MUTEX_DESTROY(&conn->conn_data_lock);
993 CV_DESTROY(&conn->conn_call_cv);
995 rxi_FreeConnection(conn);
998 /* Destroy the specified connection */
1000 rxi_DestroyConnection(struct rx_connection *conn)
1002 MUTEX_ENTER(&rx_connHashTable_lock);
1003 rxi_DestroyConnectionNoLock(conn);
1004 /* conn should be at the head of the cleanup list */
1005 if (conn == rx_connCleanup_list) {
1006 rx_connCleanup_list = rx_connCleanup_list->next;
1007 MUTEX_EXIT(&rx_connHashTable_lock);
1008 rxi_CleanupConnection(conn);
1010 #ifdef RX_ENABLE_LOCKS
1012 MUTEX_EXIT(&rx_connHashTable_lock);
1014 #endif /* RX_ENABLE_LOCKS */
1018 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1020 struct rx_connection **conn_ptr;
1022 struct rx_packet *packet;
1029 MUTEX_ENTER(&conn->conn_data_lock);
1030 MUTEX_ENTER(&rx_refcnt_mutex);
1031 if (conn->refCount > 0)
1034 if (rx_stats_active) {
1035 MUTEX_ENTER(&rx_stats_mutex);
1036 rxi_lowConnRefCount++;
1037 MUTEX_EXIT(&rx_stats_mutex);
1041 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1042 /* Busy; wait till the last guy before proceeding */
1043 MUTEX_EXIT(&rx_refcnt_mutex);
1044 MUTEX_EXIT(&conn->conn_data_lock);
1049 /* If the client previously called rx_NewCall, but it is still
1050 * waiting, treat this as a running call, and wait to destroy the
1051 * connection later when the call completes. */
1052 if ((conn->type == RX_CLIENT_CONNECTION)
1053 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1054 conn->flags |= RX_CONN_DESTROY_ME;
1055 MUTEX_EXIT(&conn->conn_data_lock);
1059 MUTEX_EXIT(&rx_refcnt_mutex);
1060 MUTEX_EXIT(&conn->conn_data_lock);
1062 /* Check for extant references to this connection */
1063 for (i = 0; i < RX_MAXCALLS; i++) {
1064 struct rx_call *call = conn->call[i];
1067 if (conn->type == RX_CLIENT_CONNECTION) {
1068 MUTEX_ENTER(&call->lock);
1069 if (call->delayedAckEvent) {
1070 /* Push the final acknowledgment out now--there
1071 * won't be a subsequent call to acknowledge the
1072 * last reply packets */
1073 rxevent_Cancel(call->delayedAckEvent, call,
1074 RX_CALL_REFCOUNT_DELAY);
1075 if (call->state == RX_STATE_PRECALL
1076 || call->state == RX_STATE_ACTIVE) {
1077 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1079 rxi_AckAll(NULL, call, 0);
1082 MUTEX_EXIT(&call->lock);
1086 #ifdef RX_ENABLE_LOCKS
1088 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1089 MUTEX_EXIT(&conn->conn_data_lock);
1091 /* Someone is accessing a packet right now. */
1095 #endif /* RX_ENABLE_LOCKS */
1098 /* Don't destroy the connection if there are any call
1099 * structures still in use */
1100 MUTEX_ENTER(&conn->conn_data_lock);
1101 conn->flags |= RX_CONN_DESTROY_ME;
1102 MUTEX_EXIT(&conn->conn_data_lock);
1107 if (conn->natKeepAliveEvent) {
1108 rxi_NatKeepAliveOff(conn);
1111 if (conn->delayedAbortEvent) {
1112 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1113 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1115 MUTEX_ENTER(&conn->conn_data_lock);
1116 rxi_SendConnectionAbort(conn, packet, 0, 1);
1117 MUTEX_EXIT(&conn->conn_data_lock);
1118 rxi_FreePacket(packet);
1122 /* Remove from connection hash table before proceeding */
1124 &rx_connHashTable[CONN_HASH
1125 (peer->host, peer->port, conn->cid, conn->epoch,
1127 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1128 if (*conn_ptr == conn) {
1129 *conn_ptr = conn->next;
1133 /* if the conn that we are destroying was the last connection, then we
1134 * clear rxLastConn as well */
1135 if (rxLastConn == conn)
1138 /* Make sure the connection is completely reset before deleting it. */
1139 /* get rid of pending events that could zap us later */
1140 if (conn->challengeEvent)
1141 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1142 if (conn->checkReachEvent)
1143 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1144 if (conn->natKeepAliveEvent)
1145 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1147 /* Add the connection to the list of destroyed connections that
1148 * need to be cleaned up. This is necessary to avoid deadlocks
1149 * in the routines we call to inform others that this connection is
1150 * being destroyed. */
1151 conn->next = rx_connCleanup_list;
1152 rx_connCleanup_list = conn;
1155 /* Externally available version */
1157 rx_DestroyConnection(struct rx_connection *conn)
1162 rxi_DestroyConnection(conn);
1167 rx_GetConnection(struct rx_connection *conn)
1172 MUTEX_ENTER(&rx_refcnt_mutex);
1174 MUTEX_EXIT(&rx_refcnt_mutex);
1178 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1179 /* Wait for the transmit queue to no longer be busy.
1180 * requires the call->lock to be held */
1182 rxi_WaitforTQBusy(struct rx_call *call) {
1183 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1184 call->flags |= RX_CALL_TQ_WAIT;
1186 #ifdef RX_ENABLE_LOCKS
1187 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1188 CV_WAIT(&call->cv_tq, &call->lock);
1189 #else /* RX_ENABLE_LOCKS */
1190 osi_rxSleep(&call->tq);
1191 #endif /* RX_ENABLE_LOCKS */
1193 if (call->tqWaiters == 0) {
1194 call->flags &= ~RX_CALL_TQ_WAIT;
1201 rxi_WakeUpTransmitQueue(struct rx_call *call)
1203 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1204 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1205 call, call->tqWaiters, call->flags));
1206 #ifdef RX_ENABLE_LOCKS
1207 osirx_AssertMine(&call->lock, "rxi_Start start");
1208 CV_BROADCAST(&call->cv_tq);
1209 #else /* RX_ENABLE_LOCKS */
1210 osi_rxWakeup(&call->tq);
1211 #endif /* RX_ENABLE_LOCKS */
1215 /* Start a new rx remote procedure call, on the specified connection.
1216 * If wait is set to 1, wait for a free call channel; otherwise return
1217 * 0. Maxtime gives the maximum number of seconds this call may take,
1218 * after rx_NewCall returns. After this time interval, a call to any
1219 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1220 * For fine grain locking, we hold the conn_call_lock in order to
1221 * to ensure that we don't get signalle after we found a call in an active
1222 * state and before we go to sleep.
1225 rx_NewCall(struct rx_connection *conn)
1227 int i, wait, ignoreBusy = 1;
1228 struct rx_call *call;
1229 struct clock queueTime;
1230 afs_uint32 leastBusy = 0;
1234 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1237 clock_GetTime(&queueTime);
1239 * Check if there are others waiting for a new call.
1240 * If so, let them go first to avoid starving them.
1241 * This is a fairly simple scheme, and might not be
1242 * a complete solution for large numbers of waiters.
1244 * makeCallWaiters keeps track of the number of
1245 * threads waiting to make calls and the
1246 * RX_CONN_MAKECALL_WAITING flag bit is used to
1247 * indicate that there are indeed calls waiting.
1248 * The flag is set when the waiter is incremented.
1249 * It is only cleared when makeCallWaiters is 0.
1250 * This prevents us from accidently destroying the
1251 * connection while it is potentially about to be used.
1253 MUTEX_ENTER(&conn->conn_call_lock);
1254 MUTEX_ENTER(&conn->conn_data_lock);
1255 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1256 conn->flags |= RX_CONN_MAKECALL_WAITING;
1257 conn->makeCallWaiters++;
1258 MUTEX_EXIT(&conn->conn_data_lock);
1260 #ifdef RX_ENABLE_LOCKS
1261 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1265 MUTEX_ENTER(&conn->conn_data_lock);
1266 conn->makeCallWaiters--;
1267 if (conn->makeCallWaiters == 0)
1268 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1271 /* We are now the active thread in rx_NewCall */
1272 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1273 MUTEX_EXIT(&conn->conn_data_lock);
1278 for (i = 0; i < RX_MAXCALLS; i++) {
1279 call = conn->call[i];
1281 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1282 /* we're not ignoring busy call slots; only look at the
1283 * call slot that is the "least" busy */
1287 if (call->state == RX_STATE_DALLY) {
1288 MUTEX_ENTER(&call->lock);
1289 if (call->state == RX_STATE_DALLY) {
1290 if (ignoreBusy && conn->lastBusy[i]) {
1291 /* if we're ignoring busy call slots, skip any ones that
1292 * have lastBusy set */
1293 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1294 leastBusy = conn->lastBusy[i];
1296 MUTEX_EXIT(&call->lock);
1301 * We are setting the state to RX_STATE_RESET to
1302 * ensure that no one else will attempt to use this
1303 * call once we drop the conn->conn_call_lock and
1304 * call->lock. We must drop the conn->conn_call_lock
1305 * before calling rxi_ResetCall because the process
1306 * of clearing the transmit queue can block for an
1307 * extended period of time. If we block while holding
1308 * the conn->conn_call_lock, then all rx_EndCall
1309 * processing will block as well. This has a detrimental
1310 * effect on overall system performance.
1312 call->state = RX_STATE_RESET;
1313 MUTEX_EXIT(&conn->conn_call_lock);
1314 MUTEX_ENTER(&rx_refcnt_mutex);
1315 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1316 MUTEX_EXIT(&rx_refcnt_mutex);
1317 rxi_ResetCall(call, 0);
1318 (*call->callNumber)++;
1319 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1323 * If we failed to be able to safely obtain the
1324 * conn->conn_call_lock we will have to drop the
1325 * call->lock to avoid a deadlock. When the call->lock
1326 * is released the state of the call can change. If it
1327 * is no longer RX_STATE_RESET then some other thread is
1330 MUTEX_EXIT(&call->lock);
1331 MUTEX_ENTER(&conn->conn_call_lock);
1332 MUTEX_ENTER(&call->lock);
1334 if (call->state == RX_STATE_RESET)
1338 * If we get here it means that after dropping
1339 * the conn->conn_call_lock and call->lock that
1340 * the call is no longer ours. If we can't find
1341 * a free call in the remaining slots we should
1342 * not go immediately to RX_CONN_MAKECALL_WAITING
1343 * because by dropping the conn->conn_call_lock
1344 * we have given up synchronization with rx_EndCall.
1345 * Instead, cycle through one more time to see if
1346 * we can find a call that can call our own.
1348 MUTEX_ENTER(&rx_refcnt_mutex);
1349 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1350 MUTEX_EXIT(&rx_refcnt_mutex);
1353 MUTEX_EXIT(&call->lock);
1356 if (ignoreBusy && conn->lastBusy[i]) {
1357 /* if we're ignoring busy call slots, skip any ones that
1358 * have lastBusy set */
1359 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1360 leastBusy = conn->lastBusy[i];
1365 /* rxi_NewCall returns with mutex locked */
1366 call = rxi_NewCall(conn, i);
1367 MUTEX_ENTER(&rx_refcnt_mutex);
1368 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1369 MUTEX_EXIT(&rx_refcnt_mutex);
1373 if (i < RX_MAXCALLS) {
1374 conn->lastBusy[i] = 0;
1379 if (leastBusy && ignoreBusy) {
1380 /* we didn't find a useable call slot, but we did see at least one
1381 * 'busy' slot; look again and only use a slot with the 'least
1387 MUTEX_ENTER(&conn->conn_data_lock);
1388 conn->flags |= RX_CONN_MAKECALL_WAITING;
1389 conn->makeCallWaiters++;
1390 MUTEX_EXIT(&conn->conn_data_lock);
1392 #ifdef RX_ENABLE_LOCKS
1393 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1397 MUTEX_ENTER(&conn->conn_data_lock);
1398 conn->makeCallWaiters--;
1399 if (conn->makeCallWaiters == 0)
1400 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1401 MUTEX_EXIT(&conn->conn_data_lock);
1403 /* Client is initially in send mode */
1404 call->state = RX_STATE_ACTIVE;
1405 call->error = conn->error;
1407 call->mode = RX_MODE_ERROR;
1409 call->mode = RX_MODE_SENDING;
1411 /* remember start time for call in case we have hard dead time limit */
1412 call->queueTime = queueTime;
1413 clock_GetTime(&call->startTime);
1414 hzero(call->bytesSent);
1415 hzero(call->bytesRcvd);
1417 /* Turn on busy protocol. */
1418 rxi_KeepAliveOn(call);
1420 /* Attempt MTU discovery */
1421 rxi_GrowMTUOn(call);
1424 * We are no longer the active thread in rx_NewCall
1426 MUTEX_ENTER(&conn->conn_data_lock);
1427 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1428 MUTEX_EXIT(&conn->conn_data_lock);
1431 * Wake up anyone else who might be giving us a chance to
1432 * run (see code above that avoids resource starvation).
1434 #ifdef RX_ENABLE_LOCKS
1435 CV_BROADCAST(&conn->conn_call_cv);
1439 MUTEX_EXIT(&conn->conn_call_lock);
1441 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1442 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1443 osi_Panic("rx_NewCall call about to be used without an empty tq");
1445 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1447 MUTEX_EXIT(&call->lock);
1450 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1455 rxi_HasActiveCalls(struct rx_connection *aconn)
1458 struct rx_call *tcall;
1462 for (i = 0; i < RX_MAXCALLS; i++) {
1463 if ((tcall = aconn->call[i])) {
1464 if ((tcall->state == RX_STATE_ACTIVE)
1465 || (tcall->state == RX_STATE_PRECALL)) {
1476 rxi_GetCallNumberVector(struct rx_connection *aconn,
1477 afs_int32 * aint32s)
1480 struct rx_call *tcall;
1484 for (i = 0; i < RX_MAXCALLS; i++) {
1485 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1486 aint32s[i] = aconn->callNumber[i] + 1;
1488 aint32s[i] = aconn->callNumber[i];
1495 rxi_SetCallNumberVector(struct rx_connection *aconn,
1496 afs_int32 * aint32s)
1499 struct rx_call *tcall;
1503 for (i = 0; i < RX_MAXCALLS; i++) {
1504 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1505 aconn->callNumber[i] = aint32s[i] - 1;
1507 aconn->callNumber[i] = aint32s[i];
1513 /* Advertise a new service. A service is named locally by a UDP port
1514 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1517 char *serviceName; Name for identification purposes (e.g. the
1518 service name might be used for probing for
1521 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1522 char *serviceName, struct rx_securityClass **securityObjects,
1523 int nSecurityObjects,
1524 afs_int32(*serviceProc) (struct rx_call * acall))
1526 osi_socket socket = OSI_NULLSOCKET;
1527 struct rx_service *tservice;
1533 if (serviceId == 0) {
1535 "rx_NewService: service id for service %s is not non-zero.\n",
1542 "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",
1550 tservice = rxi_AllocService();
1553 #ifdef RX_ENABLE_LOCKS
1554 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1557 for (i = 0; i < RX_MAX_SERVICES; i++) {
1558 struct rx_service *service = rx_services[i];
1560 if (port == service->servicePort && host == service->serviceHost) {
1561 if (service->serviceId == serviceId) {
1562 /* The identical service has already been
1563 * installed; if the caller was intending to
1564 * change the security classes used by this
1565 * service, he/she loses. */
1567 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1568 serviceName, serviceId, service->serviceName);
1570 rxi_FreeService(tservice);
1573 /* Different service, same port: re-use the socket
1574 * which is bound to the same port */
1575 socket = service->socket;
1578 if (socket == OSI_NULLSOCKET) {
1579 /* If we don't already have a socket (from another
1580 * service on same port) get a new one */
1581 socket = rxi_GetHostUDPSocket(host, port);
1582 if (socket == OSI_NULLSOCKET) {
1584 rxi_FreeService(tservice);
1589 service->socket = socket;
1590 service->serviceHost = host;
1591 service->servicePort = port;
1592 service->serviceId = serviceId;
1593 service->serviceName = serviceName;
1594 service->nSecurityObjects = nSecurityObjects;
1595 service->securityObjects = securityObjects;
1596 service->minProcs = 0;
1597 service->maxProcs = 1;
1598 service->idleDeadTime = 60;
1599 service->idleDeadErr = 0;
1600 service->connDeadTime = rx_connDeadTime;
1601 service->executeRequestProc = serviceProc;
1602 service->checkReach = 0;
1603 service->nSpecific = 0;
1604 service->specific = NULL;
1605 rx_services[i] = service; /* not visible until now */
1611 rxi_FreeService(tservice);
1612 (osi_Msg "rx_NewService: cannot support > %d services\n",
1617 /* Set configuration options for all of a service's security objects */
1620 rx_SetSecurityConfiguration(struct rx_service *service,
1621 rx_securityConfigVariables type,
1625 for (i = 0; i<service->nSecurityObjects; i++) {
1626 if (service->securityObjects[i]) {
1627 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1635 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1636 struct rx_securityClass **securityObjects, int nSecurityObjects,
1637 afs_int32(*serviceProc) (struct rx_call * acall))
1639 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1642 /* Generic request processing loop. This routine should be called
1643 * by the implementation dependent rx_ServerProc. If socketp is
1644 * non-null, it will be set to the file descriptor that this thread
1645 * is now listening on. If socketp is null, this routine will never
1648 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1650 struct rx_call *call;
1652 struct rx_service *tservice = NULL;
1659 call = rx_GetCall(threadID, tservice, socketp);
1660 if (socketp && *socketp != OSI_NULLSOCKET) {
1661 /* We are now a listener thread */
1666 /* if server is restarting( typically smooth shutdown) then do not
1667 * allow any new calls.
1670 if (rx_tranquil && (call != NULL)) {
1674 MUTEX_ENTER(&call->lock);
1676 rxi_CallError(call, RX_RESTARTING);
1677 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1679 MUTEX_EXIT(&call->lock);
1683 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1684 #ifdef RX_ENABLE_LOCKS
1686 #endif /* RX_ENABLE_LOCKS */
1687 afs_termState = AFSOP_STOP_AFS;
1688 afs_osi_Wakeup(&afs_termState);
1689 #ifdef RX_ENABLE_LOCKS
1691 #endif /* RX_ENABLE_LOCKS */
1696 tservice = call->conn->service;
1698 if (tservice->beforeProc)
1699 (*tservice->beforeProc) (call);
1701 code = tservice->executeRequestProc(call);
1703 if (tservice->afterProc)
1704 (*tservice->afterProc) (call, code);
1706 rx_EndCall(call, code);
1707 if (rx_stats_active) {
1708 MUTEX_ENTER(&rx_stats_mutex);
1710 MUTEX_EXIT(&rx_stats_mutex);
1717 rx_WakeupServerProcs(void)
1719 struct rx_serverQueueEntry *np, *tqp;
1723 MUTEX_ENTER(&rx_serverPool_lock);
1725 #ifdef RX_ENABLE_LOCKS
1726 if (rx_waitForPacket)
1727 CV_BROADCAST(&rx_waitForPacket->cv);
1728 #else /* RX_ENABLE_LOCKS */
1729 if (rx_waitForPacket)
1730 osi_rxWakeup(rx_waitForPacket);
1731 #endif /* RX_ENABLE_LOCKS */
1732 MUTEX_ENTER(&freeSQEList_lock);
1733 for (np = rx_FreeSQEList; np; np = tqp) {
1734 tqp = *(struct rx_serverQueueEntry **)np;
1735 #ifdef RX_ENABLE_LOCKS
1736 CV_BROADCAST(&np->cv);
1737 #else /* RX_ENABLE_LOCKS */
1739 #endif /* RX_ENABLE_LOCKS */
1741 MUTEX_EXIT(&freeSQEList_lock);
1742 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1743 #ifdef RX_ENABLE_LOCKS
1744 CV_BROADCAST(&np->cv);
1745 #else /* RX_ENABLE_LOCKS */
1747 #endif /* RX_ENABLE_LOCKS */
1749 MUTEX_EXIT(&rx_serverPool_lock);
1754 * One thing that seems to happen is that all the server threads get
1755 * tied up on some empty or slow call, and then a whole bunch of calls
1756 * arrive at once, using up the packet pool, so now there are more
1757 * empty calls. The most critical resources here are server threads
1758 * and the free packet pool. The "doreclaim" code seems to help in
1759 * general. I think that eventually we arrive in this state: there
1760 * are lots of pending calls which do have all their packets present,
1761 * so they won't be reclaimed, are multi-packet calls, so they won't
1762 * be scheduled until later, and thus are tying up most of the free
1763 * packet pool for a very long time.
1765 * 1. schedule multi-packet calls if all the packets are present.
1766 * Probably CPU-bound operation, useful to return packets to pool.
1767 * Do what if there is a full window, but the last packet isn't here?
1768 * 3. preserve one thread which *only* runs "best" calls, otherwise
1769 * it sleeps and waits for that type of call.
1770 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1771 * the current dataquota business is badly broken. The quota isn't adjusted
1772 * to reflect how many packets are presently queued for a running call.
1773 * So, when we schedule a queued call with a full window of packets queued
1774 * up for it, that *should* free up a window full of packets for other 2d-class
1775 * calls to be able to use from the packet pool. But it doesn't.
1777 * NB. Most of the time, this code doesn't run -- since idle server threads
1778 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1779 * as a new call arrives.
1781 /* Sleep until a call arrives. Returns a pointer to the call, ready
1782 * for an rx_Read. */
1783 #ifdef RX_ENABLE_LOCKS
1785 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1787 struct rx_serverQueueEntry *sq;
1788 struct rx_call *call = (struct rx_call *)0;
1789 struct rx_service *service = NULL;
1791 MUTEX_ENTER(&freeSQEList_lock);
1793 if ((sq = rx_FreeSQEList)) {
1794 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1795 MUTEX_EXIT(&freeSQEList_lock);
1796 } else { /* otherwise allocate a new one and return that */
1797 MUTEX_EXIT(&freeSQEList_lock);
1798 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1799 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1800 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1803 MUTEX_ENTER(&rx_serverPool_lock);
1804 if (cur_service != NULL) {
1805 ReturnToServerPool(cur_service);
1808 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1809 struct rx_call *tcall, *ncall, *choice2 = NULL;
1811 /* Scan for eligible incoming calls. A call is not eligible
1812 * if the maximum number of calls for its service type are
1813 * already executing */
1814 /* One thread will process calls FCFS (to prevent starvation),
1815 * while the other threads may run ahead looking for calls which
1816 * have all their input data available immediately. This helps
1817 * keep threads from blocking, waiting for data from the client. */
1818 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1819 service = tcall->conn->service;
1820 if (!QuotaOK(service)) {
1823 MUTEX_ENTER(&rx_pthread_mutex);
1824 if (tno == rxi_fcfs_thread_num
1825 || !tcall->queue_item_header.next) {
1826 MUTEX_EXIT(&rx_pthread_mutex);
1827 /* If we're the fcfs thread , then we'll just use
1828 * this call. If we haven't been able to find an optimal
1829 * choice, and we're at the end of the list, then use a
1830 * 2d choice if one has been identified. Otherwise... */
1831 call = (choice2 ? choice2 : tcall);
1832 service = call->conn->service;
1834 MUTEX_EXIT(&rx_pthread_mutex);
1835 if (!queue_IsEmpty(&tcall->rq)) {
1836 struct rx_packet *rp;
1837 rp = queue_First(&tcall->rq, rx_packet);
1838 if (rp->header.seq == 1) {
1840 || (rp->header.flags & RX_LAST_PACKET)) {
1842 } else if (rxi_2dchoice && !choice2
1843 && !(tcall->flags & RX_CALL_CLEARED)
1844 && (tcall->rprev > rxi_HardAckRate)) {
1854 ReturnToServerPool(service);
1861 MUTEX_EXIT(&rx_serverPool_lock);
1862 MUTEX_ENTER(&call->lock);
1864 if (call->flags & RX_CALL_WAIT_PROC) {
1865 call->flags &= ~RX_CALL_WAIT_PROC;
1866 rx_atomic_dec(&rx_nWaiting);
1869 if (call->state != RX_STATE_PRECALL || call->error) {
1870 MUTEX_EXIT(&call->lock);
1871 MUTEX_ENTER(&rx_serverPool_lock);
1872 ReturnToServerPool(service);
1877 if (queue_IsEmpty(&call->rq)
1878 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1879 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1881 CLEAR_CALL_QUEUE_LOCK(call);
1884 /* If there are no eligible incoming calls, add this process
1885 * to the idle server queue, to wait for one */
1889 *socketp = OSI_NULLSOCKET;
1891 sq->socketp = socketp;
1892 queue_Append(&rx_idleServerQueue, sq);
1893 #ifndef AFS_AIX41_ENV
1894 rx_waitForPacket = sq;
1896 rx_waitingForPacket = sq;
1897 #endif /* AFS_AIX41_ENV */
1899 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1901 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1902 MUTEX_EXIT(&rx_serverPool_lock);
1903 return (struct rx_call *)0;
1906 } while (!(call = sq->newcall)
1907 && !(socketp && *socketp != OSI_NULLSOCKET));
1908 MUTEX_EXIT(&rx_serverPool_lock);
1910 MUTEX_ENTER(&call->lock);
1916 MUTEX_ENTER(&freeSQEList_lock);
1917 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1918 rx_FreeSQEList = sq;
1919 MUTEX_EXIT(&freeSQEList_lock);
1922 clock_GetTime(&call->startTime);
1923 call->state = RX_STATE_ACTIVE;
1924 call->mode = RX_MODE_RECEIVING;
1925 #ifdef RX_KERNEL_TRACE
1926 if (ICL_SETACTIVE(afs_iclSetp)) {
1927 int glockOwner = ISAFS_GLOCK();
1930 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1931 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1938 rxi_calltrace(RX_CALL_START, call);
1939 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1940 call->conn->service->servicePort, call->conn->service->serviceId,
1943 MUTEX_EXIT(&call->lock);
1944 MUTEX_ENTER(&rx_refcnt_mutex);
1945 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1946 MUTEX_EXIT(&rx_refcnt_mutex);
1948 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1953 #else /* RX_ENABLE_LOCKS */
1955 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1957 struct rx_serverQueueEntry *sq;
1958 struct rx_call *call = (struct rx_call *)0, *choice2;
1959 struct rx_service *service = NULL;
1963 MUTEX_ENTER(&freeSQEList_lock);
1965 if ((sq = rx_FreeSQEList)) {
1966 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1967 MUTEX_EXIT(&freeSQEList_lock);
1968 } else { /* otherwise allocate a new one and return that */
1969 MUTEX_EXIT(&freeSQEList_lock);
1970 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1971 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1972 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1974 MUTEX_ENTER(&sq->lock);
1976 if (cur_service != NULL) {
1977 cur_service->nRequestsRunning--;
1978 MUTEX_ENTER(&rx_quota_mutex);
1979 if (cur_service->nRequestsRunning < cur_service->minProcs)
1982 MUTEX_EXIT(&rx_quota_mutex);
1984 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1985 struct rx_call *tcall, *ncall;
1986 /* Scan for eligible incoming calls. A call is not eligible
1987 * if the maximum number of calls for its service type are
1988 * already executing */
1989 /* One thread will process calls FCFS (to prevent starvation),
1990 * while the other threads may run ahead looking for calls which
1991 * have all their input data available immediately. This helps
1992 * keep threads from blocking, waiting for data from the client. */
1993 choice2 = (struct rx_call *)0;
1994 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1995 service = tcall->conn->service;
1996 if (QuotaOK(service)) {
1997 MUTEX_ENTER(&rx_pthread_mutex);
1998 if (tno == rxi_fcfs_thread_num
1999 || !tcall->queue_item_header.next) {
2000 MUTEX_EXIT(&rx_pthread_mutex);
2001 /* If we're the fcfs thread, then we'll just use
2002 * this call. If we haven't been able to find an optimal
2003 * choice, and we're at the end of the list, then use a
2004 * 2d choice if one has been identified. Otherwise... */
2005 call = (choice2 ? choice2 : tcall);
2006 service = call->conn->service;
2008 MUTEX_EXIT(&rx_pthread_mutex);
2009 if (!queue_IsEmpty(&tcall->rq)) {
2010 struct rx_packet *rp;
2011 rp = queue_First(&tcall->rq, rx_packet);
2012 if (rp->header.seq == 1
2014 || (rp->header.flags & RX_LAST_PACKET))) {
2016 } else if (rxi_2dchoice && !choice2
2017 && !(tcall->flags & RX_CALL_CLEARED)
2018 && (tcall->rprev > rxi_HardAckRate)) {
2032 /* we can't schedule a call if there's no data!!! */
2033 /* send an ack if there's no data, if we're missing the
2034 * first packet, or we're missing something between first
2035 * and last -- there's a "hole" in the incoming data. */
2036 if (queue_IsEmpty(&call->rq)
2037 || queue_First(&call->rq, rx_packet)->header.seq != 1
2038 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2039 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2041 call->flags &= (~RX_CALL_WAIT_PROC);
2042 service->nRequestsRunning++;
2043 /* just started call in minProcs pool, need fewer to maintain
2045 MUTEX_ENTER(&rx_quota_mutex);
2046 if (service->nRequestsRunning <= service->minProcs)
2049 MUTEX_EXIT(&rx_quota_mutex);
2050 rx_atomic_dec(&rx_nWaiting);
2051 /* MUTEX_EXIT(&call->lock); */
2053 /* If there are no eligible incoming calls, add this process
2054 * to the idle server queue, to wait for one */
2057 *socketp = OSI_NULLSOCKET;
2059 sq->socketp = socketp;
2060 queue_Append(&rx_idleServerQueue, sq);
2064 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2066 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2067 return (struct rx_call *)0;
2070 } while (!(call = sq->newcall)
2071 && !(socketp && *socketp != OSI_NULLSOCKET));
2073 MUTEX_EXIT(&sq->lock);
2075 MUTEX_ENTER(&freeSQEList_lock);
2076 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2077 rx_FreeSQEList = sq;
2078 MUTEX_EXIT(&freeSQEList_lock);
2081 clock_GetTime(&call->startTime);
2082 call->state = RX_STATE_ACTIVE;
2083 call->mode = RX_MODE_RECEIVING;
2084 #ifdef RX_KERNEL_TRACE
2085 if (ICL_SETACTIVE(afs_iclSetp)) {
2086 int glockOwner = ISAFS_GLOCK();
2089 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2090 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2097 rxi_calltrace(RX_CALL_START, call);
2098 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2099 call->conn->service->servicePort, call->conn->service->serviceId,
2102 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2109 #endif /* RX_ENABLE_LOCKS */
2113 /* Establish a procedure to be called when a packet arrives for a
2114 * call. This routine will be called at most once after each call,
2115 * and will also be called if there is an error condition on the or
2116 * the call is complete. Used by multi rx to build a selection
2117 * function which determines which of several calls is likely to be a
2118 * good one to read from.
2119 * NOTE: the way this is currently implemented it is probably only a
2120 * good idea to (1) use it immediately after a newcall (clients only)
2121 * and (2) only use it once. Other uses currently void your warranty
2124 rx_SetArrivalProc(struct rx_call *call,
2125 void (*proc) (struct rx_call * call,
2128 void * handle, int arg)
2130 call->arrivalProc = proc;
2131 call->arrivalProcHandle = handle;
2132 call->arrivalProcArg = arg;
2135 /* Call is finished (possibly prematurely). Return rc to the peer, if
2136 * appropriate, and return the final error code from the conversation
2140 rx_EndCall(struct rx_call *call, afs_int32 rc)
2142 struct rx_connection *conn = call->conn;
2146 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2147 call, rc, call->error, call->abortCode));
2150 MUTEX_ENTER(&call->lock);
2152 if (rc == 0 && call->error == 0) {
2153 call->abortCode = 0;
2154 call->abortCount = 0;
2157 call->arrivalProc = (void (*)())0;
2158 if (rc && call->error == 0) {
2159 rxi_CallError(call, rc);
2160 call->mode = RX_MODE_ERROR;
2161 /* Send an abort message to the peer if this error code has
2162 * only just been set. If it was set previously, assume the
2163 * peer has already been sent the error code or will request it
2165 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2167 if (conn->type == RX_SERVER_CONNECTION) {
2168 /* Make sure reply or at least dummy reply is sent */
2169 if (call->mode == RX_MODE_RECEIVING) {
2170 MUTEX_EXIT(&call->lock);
2171 rxi_WriteProc(call, 0, 0);
2172 MUTEX_ENTER(&call->lock);
2174 if (call->mode == RX_MODE_SENDING) {
2175 MUTEX_EXIT(&call->lock);
2176 rxi_FlushWrite(call);
2177 MUTEX_ENTER(&call->lock);
2179 rxi_calltrace(RX_CALL_END, call);
2180 /* Call goes to hold state until reply packets are acknowledged */
2181 if (call->tfirst + call->nSoftAcked < call->tnext) {
2182 call->state = RX_STATE_HOLD;
2184 call->state = RX_STATE_DALLY;
2185 rxi_ClearTransmitQueue(call, 0);
2186 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2187 rxevent_Cancel(call->keepAliveEvent, call,
2188 RX_CALL_REFCOUNT_ALIVE);
2190 } else { /* Client connection */
2192 /* Make sure server receives input packets, in the case where
2193 * no reply arguments are expected */
2194 if ((call->mode == RX_MODE_SENDING)
2195 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2196 MUTEX_EXIT(&call->lock);
2197 (void)rxi_ReadProc(call, &dummy, 1);
2198 MUTEX_ENTER(&call->lock);
2201 /* If we had an outstanding delayed ack, be nice to the server
2202 * and force-send it now.
2204 if (call->delayedAckEvent) {
2205 rxevent_Cancel(call->delayedAckEvent, call,
2206 RX_CALL_REFCOUNT_DELAY);
2207 call->delayedAckEvent = NULL;
2208 rxi_SendDelayedAck(NULL, call, NULL);
2211 /* We need to release the call lock since it's lower than the
2212 * conn_call_lock and we don't want to hold the conn_call_lock
2213 * over the rx_ReadProc call. The conn_call_lock needs to be held
2214 * here for the case where rx_NewCall is perusing the calls on
2215 * the connection structure. We don't want to signal until
2216 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2217 * have checked this call, found it active and by the time it
2218 * goes to sleep, will have missed the signal.
2220 MUTEX_EXIT(&call->lock);
2221 MUTEX_ENTER(&conn->conn_call_lock);
2222 MUTEX_ENTER(&call->lock);
2224 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2225 conn->lastBusy[call->channel] = 0;
2228 MUTEX_ENTER(&conn->conn_data_lock);
2229 conn->flags |= RX_CONN_BUSY;
2230 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2231 MUTEX_EXIT(&conn->conn_data_lock);
2232 #ifdef RX_ENABLE_LOCKS
2233 CV_BROADCAST(&conn->conn_call_cv);
2238 #ifdef RX_ENABLE_LOCKS
2240 MUTEX_EXIT(&conn->conn_data_lock);
2242 #endif /* RX_ENABLE_LOCKS */
2243 call->state = RX_STATE_DALLY;
2245 error = call->error;
2247 /* currentPacket, nLeft, and NFree must be zeroed here, because
2248 * ResetCall cannot: ResetCall may be called at splnet(), in the
2249 * kernel version, and may interrupt the macros rx_Read or
2250 * rx_Write, which run at normal priority for efficiency. */
2251 if (call->currentPacket) {
2252 #ifdef RX_TRACK_PACKETS
2253 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2255 rxi_FreePacket(call->currentPacket);
2256 call->currentPacket = (struct rx_packet *)0;
2259 call->nLeft = call->nFree = call->curlen = 0;
2261 /* Free any packets from the last call to ReadvProc/WritevProc */
2262 #ifdef RXDEBUG_PACKET
2264 #endif /* RXDEBUG_PACKET */
2265 rxi_FreePackets(0, &call->iovq);
2266 MUTEX_EXIT(&call->lock);
2268 MUTEX_ENTER(&rx_refcnt_mutex);
2269 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2270 MUTEX_EXIT(&rx_refcnt_mutex);
2271 if (conn->type == RX_CLIENT_CONNECTION) {
2272 MUTEX_ENTER(&conn->conn_data_lock);
2273 conn->flags &= ~RX_CONN_BUSY;
2274 MUTEX_EXIT(&conn->conn_data_lock);
2275 MUTEX_EXIT(&conn->conn_call_lock);
2279 * Map errors to the local host's errno.h format.
2281 error = ntoh_syserr_conv(error);
2285 #if !defined(KERNEL)
2287 /* Call this routine when shutting down a server or client (especially
2288 * clients). This will allow Rx to gracefully garbage collect server
2289 * connections, and reduce the number of retries that a server might
2290 * make to a dead client.
2291 * This is not quite right, since some calls may still be ongoing and
2292 * we can't lock them to destroy them. */
2296 struct rx_connection **conn_ptr, **conn_end;
2300 if (rxinit_status == 1) {
2302 return; /* Already shutdown. */
2304 rxi_DeleteCachedConnections();
2305 if (rx_connHashTable) {
2306 MUTEX_ENTER(&rx_connHashTable_lock);
2307 for (conn_ptr = &rx_connHashTable[0], conn_end =
2308 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2310 struct rx_connection *conn, *next;
2311 for (conn = *conn_ptr; conn; conn = next) {
2313 if (conn->type == RX_CLIENT_CONNECTION) {
2314 MUTEX_ENTER(&rx_refcnt_mutex);
2316 MUTEX_EXIT(&rx_refcnt_mutex);
2317 #ifdef RX_ENABLE_LOCKS
2318 rxi_DestroyConnectionNoLock(conn);
2319 #else /* RX_ENABLE_LOCKS */
2320 rxi_DestroyConnection(conn);
2321 #endif /* RX_ENABLE_LOCKS */
2325 #ifdef RX_ENABLE_LOCKS
2326 while (rx_connCleanup_list) {
2327 struct rx_connection *conn;
2328 conn = rx_connCleanup_list;
2329 rx_connCleanup_list = rx_connCleanup_list->next;
2330 MUTEX_EXIT(&rx_connHashTable_lock);
2331 rxi_CleanupConnection(conn);
2332 MUTEX_ENTER(&rx_connHashTable_lock);
2334 MUTEX_EXIT(&rx_connHashTable_lock);
2335 #endif /* RX_ENABLE_LOCKS */
2340 afs_winsockCleanup();
2348 /* if we wakeup packet waiter too often, can get in loop with two
2349 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2351 rxi_PacketsUnWait(void)
2353 if (!rx_waitingForPackets) {
2357 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2358 return; /* still over quota */
2361 rx_waitingForPackets = 0;
2362 #ifdef RX_ENABLE_LOCKS
2363 CV_BROADCAST(&rx_waitingForPackets_cv);
2365 osi_rxWakeup(&rx_waitingForPackets);
2371 /* ------------------Internal interfaces------------------------- */
2373 /* Return this process's service structure for the
2374 * specified socket and service */
2375 static struct rx_service *
2376 rxi_FindService(osi_socket socket, u_short serviceId)
2378 struct rx_service **sp;
2379 for (sp = &rx_services[0]; *sp; sp++) {
2380 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2386 #ifdef RXDEBUG_PACKET
2387 #ifdef KDUMP_RX_LOCK
2388 static struct rx_call_rx_lock *rx_allCallsp = 0;
2390 static struct rx_call *rx_allCallsp = 0;
2392 #endif /* RXDEBUG_PACKET */
2394 /* Allocate a call structure, for the indicated channel of the
2395 * supplied connection. The mode and state of the call must be set by
2396 * the caller. Returns the call with mutex locked. */
2397 static struct rx_call *
2398 rxi_NewCall(struct rx_connection *conn, int channel)
2400 struct rx_call *call;
2401 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2402 struct rx_call *cp; /* Call pointer temp */
2403 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2404 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2406 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2408 /* Grab an existing call structure, or allocate a new one.
2409 * Existing call structures are assumed to have been left reset by
2411 MUTEX_ENTER(&rx_freeCallQueue_lock);
2413 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2415 * EXCEPT that the TQ might not yet be cleared out.
2416 * Skip over those with in-use TQs.
2419 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2420 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2426 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2427 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2428 call = queue_First(&rx_freeCallQueue, rx_call);
2429 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2431 if (rx_stats_active)
2432 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2433 MUTEX_EXIT(&rx_freeCallQueue_lock);
2434 MUTEX_ENTER(&call->lock);
2435 CLEAR_CALL_QUEUE_LOCK(call);
2436 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2437 /* Now, if TQ wasn't cleared earlier, do it now. */
2438 rxi_WaitforTQBusy(call);
2439 if (call->flags & RX_CALL_TQ_CLEARME) {
2440 rxi_ClearTransmitQueue(call, 1);
2441 /*queue_Init(&call->tq);*/
2443 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2444 /* Bind the call to its connection structure */
2446 rxi_ResetCall(call, 1);
2449 call = rxi_Alloc(sizeof(struct rx_call));
2450 #ifdef RXDEBUG_PACKET
2451 call->allNextp = rx_allCallsp;
2452 rx_allCallsp = call;
2454 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2455 #else /* RXDEBUG_PACKET */
2456 rx_atomic_inc(&rx_stats.nCallStructs);
2457 #endif /* RXDEBUG_PACKET */
2459 MUTEX_EXIT(&rx_freeCallQueue_lock);
2460 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2461 MUTEX_ENTER(&call->lock);
2462 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2463 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2464 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2466 /* Initialize once-only items */
2467 queue_Init(&call->tq);
2468 queue_Init(&call->rq);
2469 queue_Init(&call->iovq);
2470 #ifdef RXDEBUG_PACKET
2471 call->rqc = call->tqc = call->iovqc = 0;
2472 #endif /* RXDEBUG_PACKET */
2473 /* Bind the call to its connection structure (prereq for reset) */
2475 rxi_ResetCall(call, 1);
2477 call->channel = channel;
2478 call->callNumber = &conn->callNumber[channel];
2479 call->rwind = conn->rwind[channel];
2480 call->twind = conn->twind[channel];
2481 /* Note that the next expected call number is retained (in
2482 * conn->callNumber[i]), even if we reallocate the call structure
2484 conn->call[channel] = call;
2485 /* if the channel's never been used (== 0), we should start at 1, otherwise
2486 * the call number is valid from the last time this channel was used */
2487 if (*call->callNumber == 0)
2488 *call->callNumber = 1;
2493 /* A call has been inactive long enough that so we can throw away
2494 * state, including the call structure, which is placed on the call
2497 * call->lock amd rx_refcnt_mutex are held upon entry.
2498 * haveCTLock is set when called from rxi_ReapConnections.
2501 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2503 int channel = call->channel;
2504 struct rx_connection *conn = call->conn;
2507 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2508 (*call->callNumber)++;
2510 * We are setting the state to RX_STATE_RESET to
2511 * ensure that no one else will attempt to use this
2512 * call once we drop the refcnt lock. We must drop
2513 * the refcnt lock before calling rxi_ResetCall
2514 * because it cannot be held across acquiring the
2515 * freepktQ lock. NewCall does the same.
2517 call->state = RX_STATE_RESET;
2518 MUTEX_EXIT(&rx_refcnt_mutex);
2519 rxi_ResetCall(call, 0);
2520 call->conn->call[channel] = (struct rx_call *)0;
2522 MUTEX_ENTER(&rx_freeCallQueue_lock);
2523 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2524 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2525 /* A call may be free even though its transmit queue is still in use.
2526 * Since we search the call list from head to tail, put busy calls at
2527 * the head of the list, and idle calls at the tail.
2529 if (call->flags & RX_CALL_TQ_BUSY)
2530 queue_Prepend(&rx_freeCallQueue, call);
2532 queue_Append(&rx_freeCallQueue, call);
2533 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2534 queue_Append(&rx_freeCallQueue, call);
2535 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2536 if (rx_stats_active)
2537 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2538 MUTEX_EXIT(&rx_freeCallQueue_lock);
2540 /* Destroy the connection if it was previously slated for
2541 * destruction, i.e. the Rx client code previously called
2542 * rx_DestroyConnection (client connections), or
2543 * rxi_ReapConnections called the same routine (server
2544 * connections). Only do this, however, if there are no
2545 * outstanding calls. Note that for fine grain locking, there appears
2546 * to be a deadlock in that rxi_FreeCall has a call locked and
2547 * DestroyConnectionNoLock locks each call in the conn. But note a
2548 * few lines up where we have removed this call from the conn.
2549 * If someone else destroys a connection, they either have no
2550 * call lock held or are going through this section of code.
2552 MUTEX_ENTER(&conn->conn_data_lock);
2553 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2554 MUTEX_ENTER(&rx_refcnt_mutex);
2556 MUTEX_EXIT(&rx_refcnt_mutex);
2557 MUTEX_EXIT(&conn->conn_data_lock);
2558 #ifdef RX_ENABLE_LOCKS
2560 rxi_DestroyConnectionNoLock(conn);
2562 rxi_DestroyConnection(conn);
2563 #else /* RX_ENABLE_LOCKS */
2564 rxi_DestroyConnection(conn);
2565 #endif /* RX_ENABLE_LOCKS */
2567 MUTEX_EXIT(&conn->conn_data_lock);
2569 MUTEX_ENTER(&rx_refcnt_mutex);
2572 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2573 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2576 rxi_Alloc(size_t size)
2580 if (rx_stats_active) {
2581 rx_atomic_add(&rxi_Allocsize, (int) size);
2582 rx_atomic_inc(&rxi_Alloccnt);
2586 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2587 afs_osi_Alloc_NoSleep(size);
2592 osi_Panic("rxi_Alloc error");
2598 rxi_Free(void *addr, size_t size)
2600 if (rx_stats_active) {
2601 rx_atomic_sub(&rxi_Allocsize, (int) size);
2602 rx_atomic_dec(&rxi_Alloccnt);
2604 osi_Free(addr, size);
2608 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2610 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2611 struct rx_peer *next = NULL;
2615 MUTEX_ENTER(&rx_peerHashTable_lock);
2617 peer_ptr = &rx_peerHashTable[0];
2618 peer_end = &rx_peerHashTable[rx_hashTableSize];
2621 for ( ; peer_ptr < peer_end; peer_ptr++) {
2624 for ( ; peer; peer = next) {
2626 if (host == peer->host)
2631 hashIndex = PEER_HASH(host, port);
2632 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2633 if ((peer->host == host) && (peer->port == port))
2638 MUTEX_ENTER(&rx_peerHashTable_lock);
2643 MUTEX_EXIT(&rx_peerHashTable_lock);
2645 MUTEX_ENTER(&peer->peer_lock);
2646 /* We don't handle dropping below min, so don't */
2647 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2648 peer->ifMTU=MIN(mtu, peer->ifMTU);
2649 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2650 /* if we tweaked this down, need to tune our peer MTU too */
2651 peer->MTU = MIN(peer->MTU, peer->natMTU);
2652 /* if we discovered a sub-1500 mtu, degrade */
2653 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2654 peer->maxDgramPackets = 1;
2655 /* We no longer have valid peer packet information */
2656 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2657 peer->maxPacketSize = 0;
2658 MUTEX_EXIT(&peer->peer_lock);
2660 MUTEX_ENTER(&rx_peerHashTable_lock);
2662 if (host && !port) {
2664 /* pick up where we left off */
2668 MUTEX_EXIT(&rx_peerHashTable_lock);
2671 /* Find the peer process represented by the supplied (host,port)
2672 * combination. If there is no appropriate active peer structure, a
2673 * new one will be allocated and initialized
2674 * The origPeer, if set, is a pointer to a peer structure on which the
2675 * refcount will be be decremented. This is used to replace the peer
2676 * structure hanging off a connection structure */
2678 rxi_FindPeer(afs_uint32 host, u_short port,
2679 struct rx_peer *origPeer, int create)
2683 hashIndex = PEER_HASH(host, port);
2684 MUTEX_ENTER(&rx_peerHashTable_lock);
2685 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2686 if ((pp->host == host) && (pp->port == port))
2691 pp = rxi_AllocPeer(); /* This bzero's *pp */
2692 pp->host = host; /* set here or in InitPeerParams is zero */
2694 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2695 queue_Init(&pp->congestionQueue);
2696 queue_Init(&pp->rpcStats);
2697 pp->next = rx_peerHashTable[hashIndex];
2698 rx_peerHashTable[hashIndex] = pp;
2699 rxi_InitPeerParams(pp);
2700 if (rx_stats_active)
2701 rx_atomic_inc(&rx_stats.nPeerStructs);
2708 origPeer->refCount--;
2709 MUTEX_EXIT(&rx_peerHashTable_lock);
2714 /* Find the connection at (host, port) started at epoch, and with the
2715 * given connection id. Creates the server connection if necessary.
2716 * The type specifies whether a client connection or a server
2717 * connection is desired. In both cases, (host, port) specify the
2718 * peer's (host, pair) pair. Client connections are not made
2719 * automatically by this routine. The parameter socket gives the
2720 * socket descriptor on which the packet was received. This is used,
2721 * in the case of server connections, to check that *new* connections
2722 * come via a valid (port, serviceId). Finally, the securityIndex
2723 * parameter must match the existing index for the connection. If a
2724 * server connection is created, it will be created using the supplied
2725 * index, if the index is valid for this service */
2726 struct rx_connection *
2727 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2728 u_short port, u_short serviceId, afs_uint32 cid,
2729 afs_uint32 epoch, int type, u_int securityIndex)
2731 int hashindex, flag, i;
2732 struct rx_connection *conn;
2733 hashindex = CONN_HASH(host, port, cid, epoch, type);
2734 MUTEX_ENTER(&rx_connHashTable_lock);
2735 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2736 rx_connHashTable[hashindex],
2739 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2740 && (epoch == conn->epoch)) {
2741 struct rx_peer *pp = conn->peer;
2742 if (securityIndex != conn->securityIndex) {
2743 /* this isn't supposed to happen, but someone could forge a packet
2744 * like this, and there seems to be some CM bug that makes this
2745 * happen from time to time -- in which case, the fileserver
2747 MUTEX_EXIT(&rx_connHashTable_lock);
2748 return (struct rx_connection *)0;
2750 if (pp->host == host && pp->port == port)
2752 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2754 /* So what happens when it's a callback connection? */
2755 if ( /*type == RX_CLIENT_CONNECTION && */
2756 (conn->epoch & 0x80000000))
2760 /* the connection rxLastConn that was used the last time is not the
2761 ** one we are looking for now. Hence, start searching in the hash */
2763 conn = rx_connHashTable[hashindex];
2768 struct rx_service *service;
2769 if (type == RX_CLIENT_CONNECTION) {
2770 MUTEX_EXIT(&rx_connHashTable_lock);
2771 return (struct rx_connection *)0;
2773 service = rxi_FindService(socket, serviceId);
2774 if (!service || (securityIndex >= service->nSecurityObjects)
2775 || (service->securityObjects[securityIndex] == 0)) {
2776 MUTEX_EXIT(&rx_connHashTable_lock);
2777 return (struct rx_connection *)0;
2779 conn = rxi_AllocConnection(); /* This bzero's the connection */
2780 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2781 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2782 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2783 conn->next = rx_connHashTable[hashindex];
2784 rx_connHashTable[hashindex] = conn;
2785 conn->peer = rxi_FindPeer(host, port, 0, 1);
2786 conn->type = RX_SERVER_CONNECTION;
2787 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2788 conn->epoch = epoch;
2789 conn->cid = cid & RX_CIDMASK;
2790 /* conn->serial = conn->lastSerial = 0; */
2791 /* conn->timeout = 0; */
2792 conn->ackRate = RX_FAST_ACK_RATE;
2793 conn->service = service;
2794 conn->serviceId = serviceId;
2795 conn->securityIndex = securityIndex;
2796 conn->securityObject = service->securityObjects[securityIndex];
2797 conn->nSpecific = 0;
2798 conn->specific = NULL;
2799 rx_SetConnDeadTime(conn, service->connDeadTime);
2800 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2801 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2802 for (i = 0; i < RX_MAXCALLS; i++) {
2803 conn->twind[i] = rx_initSendWindow;
2804 conn->rwind[i] = rx_initReceiveWindow;
2806 /* Notify security object of the new connection */
2807 RXS_NewConnection(conn->securityObject, conn);
2808 /* XXXX Connection timeout? */
2809 if (service->newConnProc)
2810 (*service->newConnProc) (conn);
2811 if (rx_stats_active)
2812 rx_atomic_inc(&rx_stats.nServerConns);
2815 MUTEX_ENTER(&rx_refcnt_mutex);
2817 MUTEX_EXIT(&rx_refcnt_mutex);
2819 rxLastConn = conn; /* store this connection as the last conn used */
2820 MUTEX_EXIT(&rx_connHashTable_lock);
2825 * Timeout a call on a busy call channel if appropriate.
2827 * @param[in] call The busy call.
2829 * @pre 'call' is marked as busy (namely,
2830 * call->conn->lastBusy[call->channel] != 0)
2832 * @pre call->lock is held
2833 * @pre rxi_busyChannelError is nonzero
2835 * @note call->lock is dropped and reacquired
2838 rxi_CheckBusy(struct rx_call *call)
2840 struct rx_connection *conn = call->conn;
2841 int channel = call->channel;
2842 int freechannel = 0;
2844 afs_uint32 callNumber = *call->callNumber;
2846 MUTEX_EXIT(&call->lock);
2848 MUTEX_ENTER(&conn->conn_call_lock);
2850 /* Are there any other call slots on this conn that we should try? Look for
2851 * slots that are empty and are either non-busy, or were marked as busy
2852 * longer than conn->secondsUntilDead seconds before this call started. */
2854 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
2856 /* only look at channels that aren't us */
2860 if (conn->lastBusy[i]) {
2861 /* if this channel looked busy too recently, don't look at it */
2862 if (conn->lastBusy[i] >= call->startTime.sec) {
2865 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
2870 if (conn->call[i]) {
2871 struct rx_call *tcall = conn->call[i];
2872 MUTEX_ENTER(&tcall->lock);
2873 if (tcall->state == RX_STATE_DALLY) {
2876 MUTEX_EXIT(&tcall->lock);
2882 MUTEX_EXIT(&conn->conn_call_lock);
2884 MUTEX_ENTER(&call->lock);
2886 /* Since the call->lock and conn->conn_call_lock have been released it is
2887 * possible that (1) the call may no longer be busy and/or (2) the call may
2888 * have been reused by another waiting thread. Therefore, we must confirm
2889 * that the call state has not changed when deciding whether or not to
2890 * force this application thread to retry by forcing a Timeout error. */
2892 if (freechannel && *call->callNumber == callNumber &&
2893 (call->flags & RX_CALL_PEER_BUSY)) {
2894 /* Since 'freechannel' is set, there exists another channel in this
2895 * rx_conn that the application thread might be able to use. We know
2896 * that we have the correct call since callNumber is unchanged, and we
2897 * know that the call is still busy. So, set the call error state to
2898 * rxi_busyChannelError so the application can retry the request,
2899 * presumably on a less-busy call channel. */
2901 rxi_CallError(call, rxi_busyChannelError);
2905 /* There are two packet tracing routines available for testing and monitoring
2906 * Rx. One is called just after every packet is received and the other is
2907 * called just before every packet is sent. Received packets, have had their
2908 * headers decoded, and packets to be sent have not yet had their headers
2909 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2910 * containing the network address. Both can be modified. The return value, if
2911 * non-zero, indicates that the packet should be dropped. */
2913 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2914 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2916 /* A packet has been received off the interface. Np is the packet, socket is
2917 * the socket number it was received from (useful in determining which service
2918 * this packet corresponds to), and (host, port) reflect the host,port of the
2919 * sender. This call returns the packet to the caller if it is finished with
2920 * it, rather than de-allocating it, just as a small performance hack */
2923 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2924 afs_uint32 host, u_short port, int *tnop,
2925 struct rx_call **newcallp)
2927 struct rx_call *call;
2928 struct rx_connection *conn;
2930 afs_uint32 currentCallNumber;
2936 struct rx_packet *tnp;
2939 /* We don't print out the packet until now because (1) the time may not be
2940 * accurate enough until now in the lwp implementation (rx_Listener only gets
2941 * the time after the packet is read) and (2) from a protocol point of view,
2942 * this is the first time the packet has been seen */
2943 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2944 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2945 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2946 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2947 np->header.epoch, np->header.cid, np->header.callNumber,
2948 np->header.seq, np->header.flags, np));
2951 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2952 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2955 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2956 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2959 /* If an input tracer function is defined, call it with the packet and
2960 * network address. Note this function may modify its arguments. */
2961 if (rx_justReceived) {
2962 struct sockaddr_in addr;
2964 addr.sin_family = AF_INET;
2965 addr.sin_port = port;
2966 addr.sin_addr.s_addr = host;
2967 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2968 addr.sin_len = sizeof(addr);
2969 #endif /* AFS_OSF_ENV */
2970 drop = (*rx_justReceived) (np, &addr);
2971 /* drop packet if return value is non-zero */
2974 port = addr.sin_port; /* in case fcn changed addr */
2975 host = addr.sin_addr.s_addr;
2979 /* If packet was not sent by the client, then *we* must be the client */
2980 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2981 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2983 /* Find the connection (or fabricate one, if we're the server & if
2984 * necessary) associated with this packet */
2986 rxi_FindConnection(socket, host, port, np->header.serviceId,
2987 np->header.cid, np->header.epoch, type,
2988 np->header.securityIndex);
2991 /* If no connection found or fabricated, just ignore the packet.
2992 * (An argument could be made for sending an abort packet for
2997 MUTEX_ENTER(&conn->conn_data_lock);
2998 if (conn->maxSerial < np->header.serial)
2999 conn->maxSerial = np->header.serial;
3000 MUTEX_EXIT(&conn->conn_data_lock);
3002 /* If the connection is in an error state, send an abort packet and ignore
3003 * the incoming packet */
3005 /* Don't respond to an abort packet--we don't want loops! */
3006 MUTEX_ENTER(&conn->conn_data_lock);
3007 if (np->header.type != RX_PACKET_TYPE_ABORT)
3008 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3009 MUTEX_ENTER(&rx_refcnt_mutex);
3011 MUTEX_EXIT(&rx_refcnt_mutex);
3012 MUTEX_EXIT(&conn->conn_data_lock);
3016 /* Check for connection-only requests (i.e. not call specific). */
3017 if (np->header.callNumber == 0) {
3018 switch (np->header.type) {
3019 case RX_PACKET_TYPE_ABORT: {
3020 /* What if the supplied error is zero? */
3021 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3022 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3023 rxi_ConnectionError(conn, errcode);
3024 MUTEX_ENTER(&rx_refcnt_mutex);
3026 MUTEX_EXIT(&rx_refcnt_mutex);
3029 case RX_PACKET_TYPE_CHALLENGE:
3030 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3031 MUTEX_ENTER(&rx_refcnt_mutex);
3033 MUTEX_EXIT(&rx_refcnt_mutex);
3035 case RX_PACKET_TYPE_RESPONSE:
3036 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3037 MUTEX_ENTER(&rx_refcnt_mutex);
3039 MUTEX_EXIT(&rx_refcnt_mutex);
3041 case RX_PACKET_TYPE_PARAMS:
3042 case RX_PACKET_TYPE_PARAMS + 1:
3043 case RX_PACKET_TYPE_PARAMS + 2:
3044 /* ignore these packet types for now */
3045 MUTEX_ENTER(&rx_refcnt_mutex);
3047 MUTEX_EXIT(&rx_refcnt_mutex);
3052 /* Should not reach here, unless the peer is broken: send an
3054 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3055 MUTEX_ENTER(&conn->conn_data_lock);
3056 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3057 MUTEX_ENTER(&rx_refcnt_mutex);
3059 MUTEX_EXIT(&rx_refcnt_mutex);
3060 MUTEX_EXIT(&conn->conn_data_lock);
3065 channel = np->header.cid & RX_CHANNELMASK;
3066 call = conn->call[channel];
3067 #ifdef RX_ENABLE_LOCKS
3069 MUTEX_ENTER(&call->lock);
3070 /* Test to see if call struct is still attached to conn. */
3071 if (call != conn->call[channel]) {
3073 MUTEX_EXIT(&call->lock);
3074 if (type == RX_SERVER_CONNECTION) {
3075 call = conn->call[channel];
3076 /* If we started with no call attached and there is one now,
3077 * another thread is also running this routine and has gotten
3078 * the connection channel. We should drop this packet in the tests
3079 * below. If there was a call on this connection and it's now
3080 * gone, then we'll be making a new call below.
3081 * If there was previously a call and it's now different then
3082 * the old call was freed and another thread running this routine
3083 * has created a call on this channel. One of these two threads
3084 * has a packet for the old call and the code below handles those
3088 MUTEX_ENTER(&call->lock);
3090 /* This packet can't be for this call. If the new call address is
3091 * 0 then no call is running on this channel. If there is a call
3092 * then, since this is a client connection we're getting data for
3093 * it must be for the previous call.
3095 if (rx_stats_active)
3096 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3097 MUTEX_ENTER(&rx_refcnt_mutex);
3099 MUTEX_EXIT(&rx_refcnt_mutex);
3104 currentCallNumber = conn->callNumber[channel];
3106 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3107 if (np->header.callNumber < currentCallNumber) {
3108 if (rx_stats_active)
3109 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3110 #ifdef RX_ENABLE_LOCKS
3112 MUTEX_EXIT(&call->lock);
3114 MUTEX_ENTER(&rx_refcnt_mutex);
3116 MUTEX_EXIT(&rx_refcnt_mutex);
3120 MUTEX_ENTER(&conn->conn_call_lock);
3121 call = rxi_NewCall(conn, channel);
3122 MUTEX_EXIT(&conn->conn_call_lock);
3123 *call->callNumber = np->header.callNumber;
3125 if (np->header.callNumber == 0)
3126 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",
3127 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3128 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3129 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
3131 call->state = RX_STATE_PRECALL;
3132 clock_GetTime(&call->queueTime);
3133 hzero(call->bytesSent);
3134 hzero(call->bytesRcvd);
3136 * If the number of queued calls exceeds the overload
3137 * threshold then abort this call.
3139 if ((rx_BusyThreshold > 0) &&
3140 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3141 struct rx_packet *tp;
3143 rxi_CallError(call, rx_BusyError);
3144 tp = rxi_SendCallAbort(call, np, 1, 0);
3145 MUTEX_EXIT(&call->lock);
3146 MUTEX_ENTER(&rx_refcnt_mutex);
3148 MUTEX_EXIT(&rx_refcnt_mutex);
3149 if (rx_stats_active)
3150 rx_atomic_inc(&rx_stats.nBusies);
3153 rxi_KeepAliveOn(call);
3154 } else if (np->header.callNumber != currentCallNumber) {
3155 /* Wait until the transmit queue is idle before deciding
3156 * whether to reset the current call. Chances are that the
3157 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3160 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3161 if (call->state == RX_STATE_ACTIVE) {
3162 rxi_WaitforTQBusy(call);
3164 * If we entered error state while waiting,
3165 * must call rxi_CallError to permit rxi_ResetCall
3166 * to processed when the tqWaiter count hits zero.
3169 rxi_CallError(call, call->error);
3170 MUTEX_EXIT(&call->lock);
3171 MUTEX_ENTER(&rx_refcnt_mutex);
3173 MUTEX_EXIT(&rx_refcnt_mutex);
3177 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3178 /* If the new call cannot be taken right now send a busy and set
3179 * the error condition in this call, so that it terminates as
3180 * quickly as possible */
3181 if (call->state == RX_STATE_ACTIVE) {
3182 struct rx_packet *tp;
3184 rxi_CallError(call, RX_CALL_DEAD);
3185 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3187 MUTEX_EXIT(&call->lock);
3188 MUTEX_ENTER(&rx_refcnt_mutex);
3190 MUTEX_EXIT(&rx_refcnt_mutex);
3193 rxi_ResetCall(call, 0);
3194 *call->callNumber = np->header.callNumber;
3196 if (np->header.callNumber == 0)
3197 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",
3198 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3199 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3200 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3202 call->state = RX_STATE_PRECALL;
3203 clock_GetTime(&call->queueTime);
3204 hzero(call->bytesSent);
3205 hzero(call->bytesRcvd);
3207 * If the number of queued calls exceeds the overload
3208 * threshold then abort this call.
3210 if ((rx_BusyThreshold > 0) &&
3211 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3212 struct rx_packet *tp;
3214 rxi_CallError(call, rx_BusyError);
3215 tp = rxi_SendCallAbort(call, np, 1, 0);
3216 MUTEX_EXIT(&call->lock);
3217 MUTEX_ENTER(&rx_refcnt_mutex);
3219 MUTEX_EXIT(&rx_refcnt_mutex);
3220 if (rx_stats_active)
3221 rx_atomic_inc(&rx_stats.nBusies);
3224 rxi_KeepAliveOn(call);
3226 /* Continuing call; do nothing here. */
3228 } else { /* we're the client */
3229 /* Ignore all incoming acknowledgements for calls in DALLY state */
3230 if (call && (call->state == RX_STATE_DALLY)
3231 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3232 if (rx_stats_active)
3233 rx_atomic_inc(&rx_stats.ignorePacketDally);
3234 #ifdef RX_ENABLE_LOCKS
3236 MUTEX_EXIT(&call->lock);
3239 MUTEX_ENTER(&rx_refcnt_mutex);
3241 MUTEX_EXIT(&rx_refcnt_mutex);
3245 /* Ignore anything that's not relevant to the current call. If there
3246 * isn't a current call, then no packet is relevant. */
3247 if (!call || (np->header.callNumber != currentCallNumber)) {
3248 if (rx_stats_active)
3249 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3250 #ifdef RX_ENABLE_LOCKS
3252 MUTEX_EXIT(&call->lock);
3255 MUTEX_ENTER(&rx_refcnt_mutex);
3257 MUTEX_EXIT(&rx_refcnt_mutex);
3260 /* If the service security object index stamped in the packet does not
3261 * match the connection's security index, ignore the packet */
3262 if (np->header.securityIndex != conn->securityIndex) {
3263 #ifdef RX_ENABLE_LOCKS
3264 MUTEX_EXIT(&call->lock);
3266 MUTEX_ENTER(&rx_refcnt_mutex);
3268 MUTEX_EXIT(&rx_refcnt_mutex);
3272 /* If we're receiving the response, then all transmit packets are
3273 * implicitly acknowledged. Get rid of them. */
3274 if (np->header.type == RX_PACKET_TYPE_DATA) {
3275 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3276 /* XXX Hack. Because we must release the global rx lock when
3277 * sending packets (osi_NetSend) we drop all acks while we're
3278 * traversing the tq in rxi_Start sending packets out because
3279 * packets may move to the freePacketQueue as result of being here!
3280 * So we drop these packets until we're safely out of the
3281 * traversing. Really ugly!
3282 * For fine grain RX locking, we set the acked field in the
3283 * packets and let rxi_Start remove them from the transmit queue.
3285 if (call->flags & RX_CALL_TQ_BUSY) {
3286 #ifdef RX_ENABLE_LOCKS
3287 rxi_SetAcksInTransmitQueue(call);
3289 MUTEX_ENTER(&rx_refcnt_mutex);
3291 MUTEX_EXIT(&rx_refcnt_mutex);
3292 return np; /* xmitting; drop packet */
3295 rxi_ClearTransmitQueue(call, 0);
3297 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3298 rxi_ClearTransmitQueue(call, 0);
3299 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3301 if (np->header.type == RX_PACKET_TYPE_ACK) {
3302 /* now check to see if this is an ack packet acknowledging that the
3303 * server actually *lost* some hard-acked data. If this happens we
3304 * ignore this packet, as it may indicate that the server restarted in
3305 * the middle of a call. It is also possible that this is an old ack
3306 * packet. We don't abort the connection in this case, because this
3307 * *might* just be an old ack packet. The right way to detect a server
3308 * restart in the midst of a call is to notice that the server epoch
3310 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3311 * XXX unacknowledged. I think that this is off-by-one, but
3312 * XXX I don't dare change it just yet, since it will
3313 * XXX interact badly with the server-restart detection
3314 * XXX code in receiveackpacket. */
3315 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3316 if (rx_stats_active)
3317 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3318 MUTEX_EXIT(&call->lock);
3319 MUTEX_ENTER(&rx_refcnt_mutex);
3321 MUTEX_EXIT(&rx_refcnt_mutex);
3325 } /* else not a data packet */
3328 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3329 /* Set remote user defined status from packet */
3330 call->remoteStatus = np->header.userStatus;
3332 /* Note the gap between the expected next packet and the actual
3333 * packet that arrived, when the new packet has a smaller serial number
3334 * than expected. Rioses frequently reorder packets all by themselves,
3335 * so this will be quite important with very large window sizes.
3336 * Skew is checked against 0 here to avoid any dependence on the type of
3337 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3339 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3340 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3341 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3343 MUTEX_ENTER(&conn->conn_data_lock);
3344 skew = conn->lastSerial - np->header.serial;
3345 conn->lastSerial = np->header.serial;
3346 MUTEX_EXIT(&conn->conn_data_lock);
3348 struct rx_peer *peer;
3350 if (skew > peer->inPacketSkew) {
3351 dpf(("*** In skew changed from %d to %d\n",
3352 peer->inPacketSkew, skew));
3353 peer->inPacketSkew = skew;
3357 /* Now do packet type-specific processing */
3358 switch (np->header.type) {
3359 case RX_PACKET_TYPE_DATA:
3360 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3363 case RX_PACKET_TYPE_ACK:
3364 /* Respond immediately to ack packets requesting acknowledgement
3366 if (np->header.flags & RX_REQUEST_ACK) {
3368 (void)rxi_SendCallAbort(call, 0, 1, 0);
3370 (void)rxi_SendAck(call, 0, np->header.serial,
3371 RX_ACK_PING_RESPONSE, 1);
3373 np = rxi_ReceiveAckPacket(call, np, 1);
3375 case RX_PACKET_TYPE_ABORT: {
3376 /* An abort packet: reset the call, passing the error up to the user. */
3377 /* What if error is zero? */
3378 /* What if the error is -1? the application will treat it as a timeout. */
3379 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3380 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3381 rxi_CallError(call, errdata);
3382 MUTEX_EXIT(&call->lock);
3383 MUTEX_ENTER(&rx_refcnt_mutex);
3385 MUTEX_EXIT(&rx_refcnt_mutex);
3386 return np; /* xmitting; drop packet */
3388 case RX_PACKET_TYPE_BUSY: {
3389 struct clock busyTime;
3391 clock_GetTime(&busyTime);
3393 MUTEX_EXIT(&call->lock);
3395 MUTEX_ENTER(&conn->conn_call_lock);
3396 MUTEX_ENTER(&call->lock);
3397 conn->lastBusy[call->channel] = busyTime.sec;
3398 call->flags |= RX_CALL_PEER_BUSY;
3399 MUTEX_EXIT(&call->lock);
3400 MUTEX_EXIT(&conn->conn_call_lock);
3402 MUTEX_ENTER(&rx_refcnt_mutex);
3404 MUTEX_EXIT(&rx_refcnt_mutex);
3408 case RX_PACKET_TYPE_ACKALL:
3409 /* All packets acknowledged, so we can drop all packets previously
3410 * readied for sending */
3411 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3412 /* XXX Hack. We because we can't release the global rx lock when
3413 * sending packets (osi_NetSend) we drop all ack pkts while we're
3414 * traversing the tq in rxi_Start sending packets out because
3415 * packets may move to the freePacketQueue as result of being
3416 * here! So we drop these packets until we're safely out of the
3417 * traversing. Really ugly!
3418 * For fine grain RX locking, we set the acked field in the packets
3419 * and let rxi_Start remove the packets from the transmit queue.
3421 if (call->flags & RX_CALL_TQ_BUSY) {
3422 #ifdef RX_ENABLE_LOCKS
3423 rxi_SetAcksInTransmitQueue(call);
3425 #else /* RX_ENABLE_LOCKS */
3426 MUTEX_EXIT(&call->lock);
3427 MUTEX_ENTER(&rx_refcnt_mutex);
3429 MUTEX_EXIT(&rx_refcnt_mutex);
3430 return np; /* xmitting; drop packet */
3431 #endif /* RX_ENABLE_LOCKS */
3433 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3434 rxi_ClearTransmitQueue(call, 0);
3437 /* Should not reach here, unless the peer is broken: send an abort
3439 rxi_CallError(call, RX_PROTOCOL_ERROR);
3440 np = rxi_SendCallAbort(call, np, 1, 0);
3443 /* Note when this last legitimate packet was received, for keep-alive
3444 * processing. Note, we delay getting the time until now in the hope that
3445 * the packet will be delivered to the user before any get time is required
3446 * (if not, then the time won't actually be re-evaluated here). */
3447 call->lastReceiveTime = clock_Sec();
3448 /* we've received a legit packet, so the channel is not busy */
3449 call->flags &= ~RX_CALL_PEER_BUSY;
3450 MUTEX_EXIT(&call->lock);
3451 MUTEX_ENTER(&rx_refcnt_mutex);
3453 MUTEX_EXIT(&rx_refcnt_mutex);
3457 /* return true if this is an "interesting" connection from the point of view
3458 of someone trying to debug the system */
3460 rxi_IsConnInteresting(struct rx_connection *aconn)
3463 struct rx_call *tcall;
3465 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3468 for (i = 0; i < RX_MAXCALLS; i++) {
3469 tcall = aconn->call[i];
3471 if ((tcall->state == RX_STATE_PRECALL)
3472 || (tcall->state == RX_STATE_ACTIVE))
3474 if ((tcall->mode == RX_MODE_SENDING)
3475 || (tcall->mode == RX_MODE_RECEIVING))
3483 /* if this is one of the last few packets AND it wouldn't be used by the
3484 receiving call to immediately satisfy a read request, then drop it on
3485 the floor, since accepting it might prevent a lock-holding thread from
3486 making progress in its reading. If a call has been cleared while in
3487 the precall state then ignore all subsequent packets until the call
3488 is assigned to a thread. */
3491 TooLow(struct rx_packet *ap, struct rx_call *acall)
3495 MUTEX_ENTER(&rx_quota_mutex);
3496 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3497 && (acall->state == RX_STATE_PRECALL))
3498 || ((rx_nFreePackets < rxi_dataQuota + 2)
3499 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3500 && (acall->flags & RX_CALL_READER_WAIT)))) {
3503 MUTEX_EXIT(&rx_quota_mutex);
3509 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3511 struct rx_connection *conn = arg1;
3512 struct rx_call *acall = arg2;
3513 struct rx_call *call = acall;
3514 struct clock when, now;
3517 MUTEX_ENTER(&conn->conn_data_lock);
3518 conn->checkReachEvent = NULL;
3519 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3521 MUTEX_ENTER(&rx_refcnt_mutex);
3523 MUTEX_EXIT(&rx_refcnt_mutex);
3525 MUTEX_EXIT(&conn->conn_data_lock);
3529 MUTEX_ENTER(&conn->conn_call_lock);
3530 MUTEX_ENTER(&conn->conn_data_lock);
3531 for (i = 0; i < RX_MAXCALLS; i++) {
3532 struct rx_call *tc = conn->call[i];
3533 if (tc && tc->state == RX_STATE_PRECALL) {
3539 /* Indicate that rxi_CheckReachEvent is no longer running by
3540 * clearing the flag. Must be atomic under conn_data_lock to
3541 * avoid a new call slipping by: rxi_CheckConnReach holds
3542 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3544 conn->flags &= ~RX_CONN_ATTACHWAIT;
3545 MUTEX_EXIT(&conn->conn_data_lock);
3546 MUTEX_EXIT(&conn->conn_call_lock);
3551 MUTEX_ENTER(&call->lock);
3552 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3554 MUTEX_EXIT(&call->lock);
3556 clock_GetTime(&now);
3558 when.sec += RX_CHECKREACH_TIMEOUT;
3559 MUTEX_ENTER(&conn->conn_data_lock);
3560 if (!conn->checkReachEvent) {
3561 MUTEX_ENTER(&rx_refcnt_mutex);
3563 MUTEX_EXIT(&rx_refcnt_mutex);
3564 conn->checkReachEvent =
3565 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3568 MUTEX_EXIT(&conn->conn_data_lock);
3574 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3576 struct rx_service *service = conn->service;
3577 struct rx_peer *peer = conn->peer;
3578 afs_uint32 now, lastReach;
3580 if (service->checkReach == 0)
3584 MUTEX_ENTER(&peer->peer_lock);
3585 lastReach = peer->lastReachTime;
3586 MUTEX_EXIT(&peer->peer_lock);
3587 if (now - lastReach < RX_CHECKREACH_TTL)
3590 MUTEX_ENTER(&conn->conn_data_lock);
3591 if (conn->flags & RX_CONN_ATTACHWAIT) {
3592 MUTEX_EXIT(&conn->conn_data_lock);
3595 conn->flags |= RX_CONN_ATTACHWAIT;
3596 MUTEX_EXIT(&conn->conn_data_lock);
3597 if (!conn->checkReachEvent)
3598 rxi_CheckReachEvent(NULL, conn, call);
3603 /* try to attach call, if authentication is complete */
3605 TryAttach(struct rx_call *acall, osi_socket socket,
3606 int *tnop, struct rx_call **newcallp,
3609 struct rx_connection *conn = acall->conn;
3611 if (conn->type == RX_SERVER_CONNECTION
3612 && acall->state == RX_STATE_PRECALL) {
3613 /* Don't attach until we have any req'd. authentication. */
3614 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3615 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3616 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3617 /* Note: this does not necessarily succeed; there
3618 * may not any proc available
3621 rxi_ChallengeOn(acall->conn);
3626 /* A data packet has been received off the interface. This packet is
3627 * appropriate to the call (the call is in the right state, etc.). This
3628 * routine can return a packet to the caller, for re-use */
3631 rxi_ReceiveDataPacket(struct rx_call *call,
3632 struct rx_packet *np, int istack,
3633 osi_socket socket, afs_uint32 host, u_short port,
3634 int *tnop, struct rx_call **newcallp)
3636 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3641 afs_uint32 serial=0, flags=0;
3643 struct rx_packet *tnp;
3644 struct clock when, now;
3645 if (rx_stats_active)
3646 rx_atomic_inc(&rx_stats.dataPacketsRead);
3649 /* If there are no packet buffers, drop this new packet, unless we can find
3650 * packet buffers from inactive calls */
3652 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3653 MUTEX_ENTER(&rx_freePktQ_lock);
3654 rxi_NeedMorePackets = TRUE;
3655 MUTEX_EXIT(&rx_freePktQ_lock);
3656 if (rx_stats_active)
3657 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3658 call->rprev = np->header.serial;
3659 rxi_calltrace(RX_TRACE_DROP, call);
3660 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3662 rxi_ClearReceiveQueue(call);
3663 clock_GetTime(&now);
3665 clock_Add(&when, &rx_softAckDelay);
3666 if (!call->delayedAckEvent
3667 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3668 rxevent_Cancel(call->delayedAckEvent, call,
3669 RX_CALL_REFCOUNT_DELAY);
3670 MUTEX_ENTER(&rx_refcnt_mutex);
3671 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3672 MUTEX_EXIT(&rx_refcnt_mutex);
3674 call->delayedAckEvent =
3675 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3677 /* we've damaged this call already, might as well do it in. */
3683 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3684 * packet is one of several packets transmitted as a single
3685 * datagram. Do not send any soft or hard acks until all packets
3686 * in a jumbogram have been processed. Send negative acks right away.
3688 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3689 /* tnp is non-null when there are more packets in the
3690 * current jumbo gram */
3697 seq = np->header.seq;
3698 serial = np->header.serial;
3699 flags = np->header.flags;
3701 /* If the call is in an error state, send an abort message */
3703 return rxi_SendCallAbort(call, np, istack, 0);
3705 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3706 * AFS 3.5 jumbogram. */
3707 if (flags & RX_JUMBO_PACKET) {
3708 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3713 if (np->header.spare != 0) {
3714 MUTEX_ENTER(&call->conn->conn_data_lock);
3715 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3716 MUTEX_EXIT(&call->conn->conn_data_lock);
3719 /* The usual case is that this is the expected next packet */
3720 if (seq == call->rnext) {
3722 /* Check to make sure it is not a duplicate of one already queued */
3723 if (queue_IsNotEmpty(&call->rq)
3724 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3725 if (rx_stats_active)
3726 rx_atomic_inc(&rx_stats.dupPacketsRead);
3727 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3728 rxevent_Cancel(call->delayedAckEvent, call,
3729 RX_CALL_REFCOUNT_DELAY);
3730 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3736 /* It's the next packet. Stick it on the receive queue
3737 * for this call. Set newPackets to make sure we wake
3738 * the reader once all packets have been processed */
3739 #ifdef RX_TRACK_PACKETS
3740 np->flags |= RX_PKTFLAG_RQ;
3742 queue_Prepend(&call->rq, np);
3743 #ifdef RXDEBUG_PACKET
3745 #endif /* RXDEBUG_PACKET */
3747 np = NULL; /* We can't use this anymore */
3750 /* If an ack is requested then set a flag to make sure we
3751 * send an acknowledgement for this packet */
3752 if (flags & RX_REQUEST_ACK) {
3753 ackNeeded = RX_ACK_REQUESTED;
3756 /* Keep track of whether we have received the last packet */
3757 if (flags & RX_LAST_PACKET) {
3758 call->flags |= RX_CALL_HAVE_LAST;
3762 /* Check whether we have all of the packets for this call */
3763 if (call->flags & RX_CALL_HAVE_LAST) {
3764 afs_uint32 tseq; /* temporary sequence number */
3765 struct rx_packet *tp; /* Temporary packet pointer */
3766 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3768 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3769 if (tseq != tp->header.seq)
3771 if (tp->header.flags & RX_LAST_PACKET) {
3772 call->flags |= RX_CALL_RECEIVE_DONE;
3779 /* Provide asynchronous notification for those who want it
3780 * (e.g. multi rx) */
3781 if (call->arrivalProc) {
3782 (*call->arrivalProc) (call, call->arrivalProcHandle,
3783 call->arrivalProcArg);
3784 call->arrivalProc = (void (*)())0;
3787 /* Update last packet received */
3790 /* If there is no server process serving this call, grab
3791 * one, if available. We only need to do this once. If a
3792 * server thread is available, this thread becomes a server
3793 * thread and the server thread becomes a listener thread. */
3795 TryAttach(call, socket, tnop, newcallp, 0);
3798 /* This is not the expected next packet. */
3800 /* Determine whether this is a new or old packet, and if it's
3801 * a new one, whether it fits into the current receive window.
3802 * Also figure out whether the packet was delivered in sequence.
3803 * We use the prev variable to determine whether the new packet
3804 * is the successor of its immediate predecessor in the
3805 * receive queue, and the missing flag to determine whether
3806 * any of this packets predecessors are missing. */
3808 afs_uint32 prev; /* "Previous packet" sequence number */
3809 struct rx_packet *tp; /* Temporary packet pointer */
3810 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3811 int missing; /* Are any predecessors missing? */
3813 /* If the new packet's sequence number has been sent to the
3814 * application already, then this is a duplicate */
3815 if (seq < call->rnext) {
3816 if (rx_stats_active)
3817 rx_atomic_inc(&rx_stats.dupPacketsRead);
3818 rxevent_Cancel(call->delayedAckEvent, call,
3819 RX_CALL_REFCOUNT_DELAY);
3820 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3826 /* If the sequence number is greater than what can be
3827 * accomodated by the current window, then send a negative
3828 * acknowledge and drop the packet */
3829 if ((call->rnext + call->rwind) <= seq) {
3830 rxevent_Cancel(call->delayedAckEvent, call,
3831 RX_CALL_REFCOUNT_DELAY);
3832 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3839 /* Look for the packet in the queue of old received packets */
3840 for (prev = call->rnext - 1, missing =
3841 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3842 /*Check for duplicate packet */
3843 if (seq == tp->header.seq) {
3844 if (rx_stats_active)
3845 rx_atomic_inc(&rx_stats.dupPacketsRead);
3846 rxevent_Cancel(call->delayedAckEvent, call,
3847 RX_CALL_REFCOUNT_DELAY);
3848 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3854 /* If we find a higher sequence packet, break out and
3855 * insert the new packet here. */
3856 if (seq < tp->header.seq)
3858 /* Check for missing packet */
3859 if (tp->header.seq != prev + 1) {
3863 prev = tp->header.seq;
3866 /* Keep track of whether we have received the last packet. */
3867 if (flags & RX_LAST_PACKET) {
3868 call->flags |= RX_CALL_HAVE_LAST;
3871 /* It's within the window: add it to the the receive queue.
3872 * tp is left by the previous loop either pointing at the
3873 * packet before which to insert the new packet, or at the
3874 * queue head if the queue is empty or the packet should be
3876 #ifdef RX_TRACK_PACKETS
3877 np->flags |= RX_PKTFLAG_RQ;
3879 #ifdef RXDEBUG_PACKET
3881 #endif /* RXDEBUG_PACKET */
3882 queue_InsertBefore(tp, np);
3886 /* Check whether we have all of the packets for this call */
3887 if ((call->flags & RX_CALL_HAVE_LAST)
3888 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3889 afs_uint32 tseq; /* temporary sequence number */
3892 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3893 if (tseq != tp->header.seq)
3895 if (tp->header.flags & RX_LAST_PACKET) {
3896 call->flags |= RX_CALL_RECEIVE_DONE;
3903 /* We need to send an ack of the packet is out of sequence,
3904 * or if an ack was requested by the peer. */
3905 if (seq != prev + 1 || missing) {
3906 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3907 } else if (flags & RX_REQUEST_ACK) {
3908 ackNeeded = RX_ACK_REQUESTED;
3911 /* Acknowledge the last packet for each call */
3912 if (flags & RX_LAST_PACKET) {
3923 * If the receiver is waiting for an iovec, fill the iovec
3924 * using the data from the receive queue */
3925 if (call->flags & RX_CALL_IOVEC_WAIT) {
3926 didHardAck = rxi_FillReadVec(call, serial);
3927 /* the call may have been aborted */
3936 /* Wakeup the reader if any */
3937 if ((call->flags & RX_CALL_READER_WAIT)
3938 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3939 || (call->iovNext >= call->iovMax)
3940 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3941 call->flags &= ~RX_CALL_READER_WAIT;
3942 #ifdef RX_ENABLE_LOCKS
3943 CV_BROADCAST(&call->cv_rq);
3945 osi_rxWakeup(&call->rq);
3951 * Send an ack when requested by the peer, or once every
3952 * rxi_SoftAckRate packets until the last packet has been
3953 * received. Always send a soft ack for the last packet in
3954 * the server's reply.
3956 * If we have received all of the packets for the call
3957 * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3958 * the peer can empty its packet queue and cancel all resend
3961 if (call->flags & RX_CALL_RECEIVE_DONE) {
3962 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3963 rxi_AckAll(NULL, call, 0);
3964 } else if (ackNeeded) {
3965 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3966 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3967 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3968 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3969 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3970 } else if (call->nSoftAcks) {
3971 clock_GetTime(&now);
3973 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3974 clock_Add(&when, &rx_lastAckDelay);
3976 clock_Add(&when, &rx_softAckDelay);
3978 if (!call->delayedAckEvent
3979 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3980 rxevent_Cancel(call->delayedAckEvent, call,
3981 RX_CALL_REFCOUNT_DELAY);
3982 MUTEX_ENTER(&rx_refcnt_mutex);
3983 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3984 MUTEX_EXIT(&rx_refcnt_mutex);
3985 call->delayedAckEvent =
3986 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3994 static void rxi_ComputeRate();
3998 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4000 struct rx_peer *peer = conn->peer;
4002 MUTEX_ENTER(&peer->peer_lock);
4003 peer->lastReachTime = clock_Sec();
4004 MUTEX_EXIT(&peer->peer_lock);
4006 MUTEX_ENTER(&conn->conn_data_lock);
4007 if (conn->flags & RX_CONN_ATTACHWAIT) {
4010 conn->flags &= ~RX_CONN_ATTACHWAIT;
4011 MUTEX_EXIT(&conn->conn_data_lock);
4013 for (i = 0; i < RX_MAXCALLS; i++) {
4014 struct rx_call *call = conn->call[i];
4017 MUTEX_ENTER(&call->lock);
4018 /* tnop can be null if newcallp is null */
4019 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4021 MUTEX_EXIT(&call->lock);
4025 MUTEX_EXIT(&conn->conn_data_lock);
4028 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4030 rx_ack_reason(int reason)
4033 case RX_ACK_REQUESTED:
4035 case RX_ACK_DUPLICATE:
4037 case RX_ACK_OUT_OF_SEQUENCE:
4039 case RX_ACK_EXCEEDS_WINDOW:
4041 case RX_ACK_NOSPACE:
4045 case RX_ACK_PING_RESPONSE:
4058 /* The real smarts of the whole thing. */
4060 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4063 struct rx_ackPacket *ap;
4065 struct rx_packet *tp;
4066 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4067 struct rx_connection *conn = call->conn;
4068 struct rx_peer *peer = conn->peer;
4069 struct clock now; /* Current time, for RTT calculations */
4073 /* because there are CM's that are bogus, sending weird values for this. */
4074 afs_uint32 skew = 0;
4079 int newAckCount = 0;
4080 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4081 int pktsize = 0; /* Set if we need to update the peer mtu */
4082 int conn_data_locked = 0;
4084 if (rx_stats_active)
4085 rx_atomic_inc(&rx_stats.ackPacketsRead);
4086 ap = (struct rx_ackPacket *)rx_DataOf(np);
4087 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4089 return np; /* truncated ack packet */
4091 /* depends on ack packet struct */
4092 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4093 first = ntohl(ap->firstPacket);
4094 prev = ntohl(ap->previousPacket);
4095 serial = ntohl(ap->serial);
4096 /* temporarily disabled -- needs to degrade over time
4097 * skew = ntohs(ap->maxSkew); */
4099 /* Ignore ack packets received out of order */
4100 if (first < call->tfirst ||
4101 (first == call->tfirst && prev < call->tprev)) {
4107 if (np->header.flags & RX_SLOW_START_OK) {
4108 call->flags |= RX_CALL_SLOW_START_OK;
4111 if (ap->reason == RX_ACK_PING_RESPONSE)
4112 rxi_UpdatePeerReach(conn, call);
4114 if (conn->lastPacketSizeSeq) {
4115 MUTEX_ENTER(&conn->conn_data_lock);
4116 conn_data_locked = 1;
4117 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4118 pktsize = conn->lastPacketSize;
4119 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4122 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4123 if (!conn_data_locked) {
4124 MUTEX_ENTER(&conn->conn_data_lock);
4125 conn_data_locked = 1;
4127 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4128 /* process mtu ping ack */
4129 pktsize = conn->lastPingSize;
4130 conn->lastPingSizeSer = conn->lastPingSize = 0;
4134 if (conn_data_locked) {
4135 MUTEX_EXIT(&conn->conn_data_lock);
4136 conn_data_locked = 0;
4140 if (rxdebug_active) {
4144 len = _snprintf(msg, sizeof(msg),
4145 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4146 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4147 ntohl(ap->serial), ntohl(ap->previousPacket),
4148 (unsigned int)np->header.seq, (unsigned int)skew,
4149 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4153 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4154 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4158 OutputDebugString(msg);
4160 #else /* AFS_NT40_ENV */
4163 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4164 ap->reason, ntohl(ap->previousPacket),
4165 (unsigned int)np->header.seq, (unsigned int)serial,
4166 (unsigned int)skew, ntohl(ap->firstPacket));
4169 for (offset = 0; offset < nAcks; offset++)
4170 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4175 #endif /* AFS_NT40_ENV */
4178 MUTEX_ENTER(&peer->peer_lock);
4181 * Start somewhere. Can't assume we can send what we can receive,
4182 * but we are clearly receiving.
4184 if (!peer->maxPacketSize)
4185 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4187 if (pktsize > peer->maxPacketSize) {
4188 peer->maxPacketSize = pktsize;
4189 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4190 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4191 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4192 rxi_ScheduleGrowMTUEvent(call, 1);
4197 /* Update the outgoing packet skew value to the latest value of
4198 * the peer's incoming packet skew value. The ack packet, of
4199 * course, could arrive out of order, but that won't affect things
4201 peer->outPacketSkew = skew;
4203 /* Check for packets that no longer need to be transmitted, and
4204 * discard them. This only applies to packets positively
4205 * acknowledged as having been sent to the peer's upper level.
4206 * All other packets must be retained. So only packets with
4207 * sequence numbers < ap->firstPacket are candidates. */
4209 clock_GetTime(&now);
4211 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4212 if (tp->header.seq >= first)
4214 call->tfirst = tp->header.seq + 1;
4216 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4219 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4223 rxi_ComputeRate(call->conn->peer, call, p, np, ap->reason);
4226 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4227 /* XXX Hack. Because we have to release the global rx lock when sending
4228 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4229 * in rxi_Start sending packets out because packets may move to the
4230 * freePacketQueue as result of being here! So we drop these packets until
4231 * we're safely out of the traversing. Really ugly!
4232 * To make it even uglier, if we're using fine grain locking, we can
4233 * set the ack bits in the packets and have rxi_Start remove the packets
4234 * when it's done transmitting.
4236 if (call->flags & RX_CALL_TQ_BUSY) {
4237 #ifdef RX_ENABLE_LOCKS
4238 tp->flags |= RX_PKTFLAG_ACKED;
4239 call->flags |= RX_CALL_TQ_SOME_ACKED;
4240 #else /* RX_ENABLE_LOCKS */
4242 #endif /* RX_ENABLE_LOCKS */
4244 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4247 #ifdef RX_TRACK_PACKETS
4248 tp->flags &= ~RX_PKTFLAG_TQ;
4250 #ifdef RXDEBUG_PACKET
4252 #endif /* RXDEBUG_PACKET */
4253 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4258 /* Give rate detector a chance to respond to ping requests */
4259 if (ap->reason == RX_ACK_PING_RESPONSE) {
4260 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4264 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4266 /* Now go through explicit acks/nacks and record the results in
4267 * the waiting packets. These are packets that can't be released
4268 * yet, even with a positive acknowledge. This positive
4269 * acknowledge only means the packet has been received by the
4270 * peer, not that it will be retained long enough to be sent to
4271 * the peer's upper level. In addition, reset the transmit timers
4272 * of any missing packets (those packets that must be missing
4273 * because this packet was out of sequence) */
4275 call->nSoftAcked = 0;
4276 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4278 /* Set the acknowledge flag per packet based on the
4279 * information in the ack packet. An acknowlegded packet can
4280 * be downgraded when the server has discarded a packet it
4281 * soacked previously, or when an ack packet is received
4282 * out of sequence. */
4283 if (tp->header.seq < first) {
4284 /* Implicit ack information */
4285 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4288 tp->flags |= RX_PKTFLAG_ACKED;
4289 } else if (tp->header.seq < first + nAcks) {
4290 /* Explicit ack information: set it in the packet appropriately */
4291 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4292 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4294 tp->flags |= RX_PKTFLAG_ACKED;
4296 rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4298 rxi_ComputeRate(call->conn->peer, call, tp, np,
4307 } else /* RX_ACK_TYPE_NACK */ {
4308 tp->flags &= ~RX_PKTFLAG_ACKED;
4312 if (tp->flags & RX_PKTFLAG_ACKED) {
4313 tp->flags &= ~RX_PKTFLAG_ACKED;
4319 * Following the suggestion of Phil Kern, we back off the peer's
4320 * timeout value for future packets until a successful response
4321 * is received for an initial transmission.
4323 if (missing && !peer->backedOff) {
4324 struct clock c = peer->timeout;
4325 struct clock max_to = {3, 0};
4327 clock_Add(&peer->timeout, &c);
4328 if (clock_Gt(&peer->timeout, &max_to))
4329 peer->timeout = max_to;
4330 peer->backedOff = 1;
4333 /* If packet isn't yet acked, and it has been transmitted at least
4334 * once, reset retransmit time using latest timeout
4335 * ie, this should readjust the retransmit timer for all outstanding
4336 * packets... So we don't just retransmit when we should know better*/
4338 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4339 tp->retryTime = tp->timeSent;
4340 clock_Add(&tp->retryTime, &peer->timeout);
4341 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4342 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4346 /* If the window has been extended by this acknowledge packet,
4347 * then wakeup a sender waiting in alloc for window space, or try
4348 * sending packets now, if he's been sitting on packets due to
4349 * lack of window space */
4350 if (call->tnext < (call->tfirst + call->twind)) {
4351 #ifdef RX_ENABLE_LOCKS
4352 CV_SIGNAL(&call->cv_twind);
4354 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4355 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4356 osi_rxWakeup(&call->twind);
4359 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4360 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4364 /* if the ack packet has a receivelen field hanging off it,
4365 * update our state */
4366 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4369 /* If the ack packet has a "recommended" size that is less than
4370 * what I am using now, reduce my size to match */
4371 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4372 (int)sizeof(afs_int32), &tSize);
4373 tSize = (afs_uint32) ntohl(tSize);
4374 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4376 /* Get the maximum packet size to send to this peer */
4377 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4379 tSize = (afs_uint32) ntohl(tSize);
4380 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4381 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4383 /* sanity check - peer might have restarted with different params.
4384 * If peer says "send less", dammit, send less... Peer should never
4385 * be unable to accept packets of the size that prior AFS versions would
4386 * send without asking. */
4387 if (peer->maxMTU != tSize) {
4388 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4390 peer->maxMTU = tSize;
4391 peer->MTU = MIN(tSize, peer->MTU);
4392 call->MTU = MIN(call->MTU, tSize);
4395 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4398 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4399 (int)sizeof(afs_int32), &tSize);
4400 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4401 if (tSize < call->twind) { /* smaller than our send */
4402 call->twind = tSize; /* window, we must send less... */
4403 call->ssthresh = MIN(call->twind, call->ssthresh);
4404 call->conn->twind[call->channel] = call->twind;
4407 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4408 * network MTU confused with the loopback MTU. Calculate the
4409 * maximum MTU here for use in the slow start code below.
4411 /* Did peer restart with older RX version? */
4412 if (peer->maxDgramPackets > 1) {
4413 peer->maxDgramPackets = 1;
4415 } else if (np->length >=
4416 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4419 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4420 sizeof(afs_int32), &tSize);
4421 tSize = (afs_uint32) ntohl(tSize);
4423 * As of AFS 3.5 we set the send window to match the receive window.
4425 if (tSize < call->twind) {
4426 call->twind = tSize;
4427 call->conn->twind[call->channel] = call->twind;
4428 call->ssthresh = MIN(call->twind, call->ssthresh);
4429 } else if (tSize > call->twind) {
4430 call->twind = tSize;
4431 call->conn->twind[call->channel] = call->twind;
4435 * As of AFS 3.5, a jumbogram is more than one fixed size
4436 * packet transmitted in a single UDP datagram. If the remote
4437 * MTU is smaller than our local MTU then never send a datagram
4438 * larger than the natural MTU.
4441 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4442 (int)sizeof(afs_int32), &tSize);
4443 maxDgramPackets = (afs_uint32) ntohl(tSize);
4444 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4446 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4447 if (maxDgramPackets > 1) {
4448 peer->maxDgramPackets = maxDgramPackets;
4449 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4451 peer->maxDgramPackets = 1;
4452 call->MTU = peer->natMTU;
4454 } else if (peer->maxDgramPackets > 1) {
4455 /* Restarted with lower version of RX */
4456 peer->maxDgramPackets = 1;
4458 } else if (peer->maxDgramPackets > 1
4459 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4460 /* Restarted with lower version of RX */
4461 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4462 peer->natMTU = OLD_MAX_PACKET_SIZE;
4463 peer->MTU = OLD_MAX_PACKET_SIZE;
4464 peer->maxDgramPackets = 1;
4465 peer->nDgramPackets = 1;
4467 call->MTU = OLD_MAX_PACKET_SIZE;
4472 * Calculate how many datagrams were successfully received after
4473 * the first missing packet and adjust the negative ack counter
4478 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4479 if (call->nNacks < nNacked) {
4480 call->nNacks = nNacked;
4483 call->nAcks += newAckCount;
4487 if (call->flags & RX_CALL_FAST_RECOVER) {
4489 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4491 call->flags &= ~RX_CALL_FAST_RECOVER;
4492 call->cwind = call->nextCwind;
4493 call->nextCwind = 0;
4496 call->nCwindAcks = 0;
4497 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4498 /* Three negative acks in a row trigger congestion recovery */
4499 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4500 MUTEX_EXIT(&peer->peer_lock);
4501 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4502 /* someone else is waiting to start recovery */
4505 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4506 rxi_WaitforTQBusy(call);
4507 MUTEX_ENTER(&peer->peer_lock);
4508 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4509 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4510 call->flags |= RX_CALL_FAST_RECOVER;
4511 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4513 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4514 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4515 call->nextCwind = call->ssthresh;
4518 peer->MTU = call->MTU;
4519 peer->cwind = call->nextCwind;
4520 peer->nDgramPackets = call->nDgramPackets;
4522 call->congestSeq = peer->congestSeq;
4523 /* Reset the resend times on the packets that were nacked
4524 * so we will retransmit as soon as the window permits*/
4525 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4527 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4528 clock_Zero(&tp->retryTime);
4530 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4535 /* If cwind is smaller than ssthresh, then increase
4536 * the window one packet for each ack we receive (exponential
4538 * If cwind is greater than or equal to ssthresh then increase
4539 * the congestion window by one packet for each cwind acks we
4540 * receive (linear growth). */
4541 if (call->cwind < call->ssthresh) {
4543 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4544 call->nCwindAcks = 0;
4546 call->nCwindAcks += newAckCount;
4547 if (call->nCwindAcks >= call->cwind) {
4548 call->nCwindAcks = 0;
4549 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4553 * If we have received several acknowledgements in a row then
4554 * it is time to increase the size of our datagrams
4556 if ((int)call->nAcks > rx_nDgramThreshold) {
4557 if (peer->maxDgramPackets > 1) {
4558 if (call->nDgramPackets < peer->maxDgramPackets) {
4559 call->nDgramPackets++;
4561 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4562 } else if (call->MTU < peer->maxMTU) {
4563 /* don't upgrade if we can't handle it */
4564 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4565 call->MTU = peer->ifMTU;
4567 call->MTU += peer->natMTU;
4568 call->MTU = MIN(call->MTU, peer->maxMTU);
4575 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4577 /* Servers need to hold the call until all response packets have
4578 * been acknowledged. Soft acks are good enough since clients
4579 * are not allowed to clear their receive queues. */
4580 if (call->state == RX_STATE_HOLD
4581 && call->tfirst + call->nSoftAcked >= call->tnext) {
4582 call->state = RX_STATE_DALLY;
4583 rxi_ClearTransmitQueue(call, 0);
4584 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4585 } else if (!queue_IsEmpty(&call->tq)) {
4586 rxi_Start(0, call, 0, istack);
4591 /* Received a response to a challenge packet */
4593 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4594 struct rx_packet *np, int istack)
4598 /* Ignore the packet if we're the client */
4599 if (conn->type == RX_CLIENT_CONNECTION)
4602 /* If already authenticated, ignore the packet (it's probably a retry) */
4603 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4606 /* Otherwise, have the security object evaluate the response packet */
4607 error = RXS_CheckResponse(conn->securityObject, conn, np);
4609 /* If the response is invalid, reset the connection, sending
4610 * an abort to the peer */
4614 rxi_ConnectionError(conn, error);
4615 MUTEX_ENTER(&conn->conn_data_lock);
4616 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4617 MUTEX_EXIT(&conn->conn_data_lock);
4620 /* If the response is valid, any calls waiting to attach
4621 * servers can now do so */
4624 for (i = 0; i < RX_MAXCALLS; i++) {
4625 struct rx_call *call = conn->call[i];
4627 MUTEX_ENTER(&call->lock);
4628 if (call->state == RX_STATE_PRECALL)
4629 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4630 /* tnop can be null if newcallp is null */
4631 MUTEX_EXIT(&call->lock);
4635 /* Update the peer reachability information, just in case
4636 * some calls went into attach-wait while we were waiting
4637 * for authentication..
4639 rxi_UpdatePeerReach(conn, NULL);
4644 /* A client has received an authentication challenge: the security
4645 * object is asked to cough up a respectable response packet to send
4646 * back to the server. The server is responsible for retrying the
4647 * challenge if it fails to get a response. */
4650 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4651 struct rx_packet *np, int istack)
4655 /* Ignore the challenge if we're the server */
4656 if (conn->type == RX_SERVER_CONNECTION)
4659 /* Ignore the challenge if the connection is otherwise idle; someone's
4660 * trying to use us as an oracle. */
4661 if (!rxi_HasActiveCalls(conn))
4664 /* Send the security object the challenge packet. It is expected to fill
4665 * in the response. */
4666 error = RXS_GetResponse(conn->securityObject, conn, np);
4668 /* If the security object is unable to return a valid response, reset the
4669 * connection and send an abort to the peer. Otherwise send the response
4670 * packet to the peer connection. */
4672 rxi_ConnectionError(conn, error);
4673 MUTEX_ENTER(&conn->conn_data_lock);
4674 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4675 MUTEX_EXIT(&conn->conn_data_lock);
4677 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4678 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4684 /* Find an available server process to service the current request in
4685 * the given call structure. If one isn't available, queue up this
4686 * call so it eventually gets one */
4688 rxi_AttachServerProc(struct rx_call *call,
4689 osi_socket socket, int *tnop,
4690 struct rx_call **newcallp)
4692 struct rx_serverQueueEntry *sq;
4693 struct rx_service *service = call->conn->service;
4696 /* May already be attached */
4697 if (call->state == RX_STATE_ACTIVE)
4700 MUTEX_ENTER(&rx_serverPool_lock);
4702 haveQuota = QuotaOK(service);
4703 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4704 /* If there are no processes available to service this call,
4705 * put the call on the incoming call queue (unless it's
4706 * already on the queue).
4708 #ifdef RX_ENABLE_LOCKS
4710 ReturnToServerPool(service);
4711 #endif /* RX_ENABLE_LOCKS */
4713 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4714 call->flags |= RX_CALL_WAIT_PROC;
4715 rx_atomic_inc(&rx_nWaiting);
4716 rx_atomic_inc(&rx_nWaited);
4717 rxi_calltrace(RX_CALL_ARRIVAL, call);
4718 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4719 queue_Append(&rx_incomingCallQueue, call);
4722 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4724 /* If hot threads are enabled, and both newcallp and sq->socketp
4725 * are non-null, then this thread will process the call, and the
4726 * idle server thread will start listening on this threads socket.
4729 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4732 *sq->socketp = socket;
4733 clock_GetTime(&call->startTime);
4734 MUTEX_ENTER(&rx_refcnt_mutex);
4735 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4736 MUTEX_EXIT(&rx_refcnt_mutex);
4740 if (call->flags & RX_CALL_WAIT_PROC) {
4741 /* Conservative: I don't think this should happen */
4742 call->flags &= ~RX_CALL_WAIT_PROC;
4743 if (queue_IsOnQueue(call)) {
4746 rx_atomic_dec(&rx_nWaiting);
4749 call->state = RX_STATE_ACTIVE;
4750 call->mode = RX_MODE_RECEIVING;
4751 #ifdef RX_KERNEL_TRACE
4753 int glockOwner = ISAFS_GLOCK();
4756 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4757 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4763 if (call->flags & RX_CALL_CLEARED) {
4764 /* send an ack now to start the packet flow up again */
4765 call->flags &= ~RX_CALL_CLEARED;
4766 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4768 #ifdef RX_ENABLE_LOCKS
4771 service->nRequestsRunning++;
4772 MUTEX_ENTER(&rx_quota_mutex);
4773 if (service->nRequestsRunning <= service->minProcs)
4776 MUTEX_EXIT(&rx_quota_mutex);
4780 MUTEX_EXIT(&rx_serverPool_lock);
4783 /* Delay the sending of an acknowledge event for a short while, while
4784 * a new call is being prepared (in the case of a client) or a reply
4785 * is being prepared (in the case of a server). Rather than sending
4786 * an ack packet, an ACKALL packet is sent. */
4788 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4790 #ifdef RX_ENABLE_LOCKS
4792 MUTEX_ENTER(&call->lock);
4793 call->delayedAckEvent = NULL;
4794 MUTEX_ENTER(&rx_refcnt_mutex);
4795 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4796 MUTEX_EXIT(&rx_refcnt_mutex);
4798 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4799 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4801 MUTEX_EXIT(&call->lock);
4802 #else /* RX_ENABLE_LOCKS */
4804 call->delayedAckEvent = NULL;
4805 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4806 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4807 #endif /* RX_ENABLE_LOCKS */
4811 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4813 struct rx_call *call = arg1;
4814 #ifdef RX_ENABLE_LOCKS
4816 MUTEX_ENTER(&call->lock);
4817 if (event == call->delayedAckEvent)
4818 call->delayedAckEvent = NULL;
4819 MUTEX_ENTER(&rx_refcnt_mutex);
4820 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4821 MUTEX_EXIT(&rx_refcnt_mutex);
4823 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4825 MUTEX_EXIT(&call->lock);
4826 #else /* RX_ENABLE_LOCKS */
4828 call->delayedAckEvent = NULL;
4829 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4830 #endif /* RX_ENABLE_LOCKS */
4834 #ifdef RX_ENABLE_LOCKS
4835 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4836 * clearing them out.
4839 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4841 struct rx_packet *p, *tp;
4844 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4845 p->flags |= RX_PKTFLAG_ACKED;
4849 call->flags |= RX_CALL_TQ_CLEARME;
4850 call->flags |= RX_CALL_TQ_SOME_ACKED;
4853 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4854 call->tfirst = call->tnext;
4855 call->nSoftAcked = 0;
4857 if (call->flags & RX_CALL_FAST_RECOVER) {
4858 call->flags &= ~RX_CALL_FAST_RECOVER;
4859 call->cwind = call->nextCwind;
4860 call->nextCwind = 0;
4863 CV_SIGNAL(&call->cv_twind);
4865 #endif /* RX_ENABLE_LOCKS */
4867 /* Clear out the transmit queue for the current call (all packets have
4868 * been received by peer) */
4870 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4872 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4873 struct rx_packet *p, *tp;
4875 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4877 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4878 p->flags |= RX_PKTFLAG_ACKED;
4882 call->flags |= RX_CALL_TQ_CLEARME;
4883 call->flags |= RX_CALL_TQ_SOME_ACKED;
4886 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4887 #ifdef RXDEBUG_PACKET
4889 #endif /* RXDEBUG_PACKET */
4890 rxi_FreePackets(0, &call->tq);
4891 rxi_WakeUpTransmitQueue(call);
4892 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4893 call->flags &= ~RX_CALL_TQ_CLEARME;
4895 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4897 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4898 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4899 call->nSoftAcked = 0;
4901 if (call->flags & RX_CALL_FAST_RECOVER) {
4902 call->flags &= ~RX_CALL_FAST_RECOVER;
4903 call->cwind = call->nextCwind;
4905 #ifdef RX_ENABLE_LOCKS
4906 CV_SIGNAL(&call->cv_twind);
4908 osi_rxWakeup(&call->twind);
4913 rxi_ClearReceiveQueue(struct rx_call *call)
4915 if (queue_IsNotEmpty(&call->rq)) {
4918 count = rxi_FreePackets(0, &call->rq);
4919 rx_packetReclaims += count;
4920 #ifdef RXDEBUG_PACKET
4922 if ( call->rqc != 0 )
4923 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
4925 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4927 if (call->state == RX_STATE_PRECALL) {
4928 call->flags |= RX_CALL_CLEARED;
4932 /* Send an abort packet for the specified call */
4934 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4935 int istack, int force)
4938 struct clock when, now;
4943 /* Clients should never delay abort messages */
4944 if (rx_IsClientConn(call->conn))
4947 if (call->abortCode != call->error) {
4948 call->abortCode = call->error;
4949 call->abortCount = 0;
4952 if (force || rxi_callAbortThreshhold == 0
4953 || call->abortCount < rxi_callAbortThreshhold) {
4954 if (call->delayedAbortEvent) {
4955 rxevent_Cancel(call->delayedAbortEvent, call,
4956 RX_CALL_REFCOUNT_ABORT);
4958 error = htonl(call->error);
4961 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4962 (char *)&error, sizeof(error), istack);
4963 } else if (!call->delayedAbortEvent) {
4964 clock_GetTime(&now);
4966 clock_Addmsec(&when, rxi_callAbortDelay);
4967 MUTEX_ENTER(&rx_refcnt_mutex);
4968 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4969 MUTEX_EXIT(&rx_refcnt_mutex);
4970 call->delayedAbortEvent =
4971 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4976 /* Send an abort packet for the specified connection. Packet is an
4977 * optional pointer to a packet that can be used to send the abort.
4978 * Once the number of abort messages reaches the threshhold, an
4979 * event is scheduled to send the abort. Setting the force flag
4980 * overrides sending delayed abort messages.
4982 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4983 * to send the abort packet.
4986 rxi_SendConnectionAbort(struct rx_connection *conn,
4987 struct rx_packet *packet, int istack, int force)
4990 struct clock when, now;
4995 /* Clients should never delay abort messages */
4996 if (rx_IsClientConn(conn))
4999 if (force || rxi_connAbortThreshhold == 0
5000 || conn->abortCount < rxi_connAbortThreshhold) {
5001 if (conn->delayedAbortEvent) {
5002 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
5004 error = htonl(conn->error);
5006 MUTEX_EXIT(&conn->conn_data_lock);
5008 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5009 RX_PACKET_TYPE_ABORT, (char *)&error,
5010 sizeof(error), istack);
5011 MUTEX_ENTER(&conn->conn_data_lock);
5012 } else if (!conn->delayedAbortEvent) {
5013 clock_GetTime(&now);
5015 clock_Addmsec(&when, rxi_connAbortDelay);
5016 conn->delayedAbortEvent =
5017 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
5022 /* Associate an error all of the calls owned by a connection. Called
5023 * with error non-zero. This is only for really fatal things, like
5024 * bad authentication responses. The connection itself is set in
5025 * error at this point, so that future packets received will be
5028 rxi_ConnectionError(struct rx_connection *conn,
5034 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5036 MUTEX_ENTER(&conn->conn_data_lock);
5037 if (conn->challengeEvent)
5038 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
5039 if (conn->natKeepAliveEvent)
5040 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
5041 if (conn->checkReachEvent) {
5042 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
5043 conn->checkReachEvent = 0;
5044 conn->flags &= ~RX_CONN_ATTACHWAIT;
5045 MUTEX_ENTER(&rx_refcnt_mutex);
5047 MUTEX_EXIT(&rx_refcnt_mutex);
5049 MUTEX_EXIT(&conn->conn_data_lock);
5050 for (i = 0; i < RX_MAXCALLS; i++) {
5051 struct rx_call *call = conn->call[i];
5053 MUTEX_ENTER(&call->lock);
5054 rxi_CallError(call, error);
5055 MUTEX_EXIT(&call->lock);
5058 conn->error = error;
5059 if (rx_stats_active)
5060 rx_atomic_inc(&rx_stats.fatalErrors);
5065 * Interrupt an in-progress call with the specified error and wakeup waiters.
5067 * @param[in] call The call to interrupt
5068 * @param[in] error The error code to send to the peer
5071 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5073 MUTEX_ENTER(&call->lock);
5074 rxi_CallError(call, error);
5075 rxi_SendCallAbort(call, NULL, 0, 1);
5076 MUTEX_EXIT(&call->lock);
5080 rxi_CallError(struct rx_call *call, afs_int32 error)
5083 osirx_AssertMine(&call->lock, "rxi_CallError");
5085 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5087 error = call->error;
5089 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5090 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5091 rxi_ResetCall(call, 0);
5094 rxi_ResetCall(call, 0);
5096 call->error = error;
5099 /* Reset various fields in a call structure, and wakeup waiting
5100 * processes. Some fields aren't changed: state & mode are not
5101 * touched (these must be set by the caller), and bufptr, nLeft, and
5102 * nFree are not reset, since these fields are manipulated by
5103 * unprotected macros, and may only be reset by non-interrupting code.
5106 /* this code requires that call->conn be set properly as a pre-condition. */
5107 #endif /* ADAPT_WINDOW */
5110 rxi_ResetCall(struct rx_call *call, int newcall)
5113 struct rx_peer *peer;
5114 struct rx_packet *packet;
5116 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5118 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5120 /* Notify anyone who is waiting for asynchronous packet arrival */
5121 if (call->arrivalProc) {
5122 (*call->arrivalProc) (call, call->arrivalProcHandle,
5123 call->arrivalProcArg);
5124 call->arrivalProc = (void (*)())0;
5127 if (call->growMTUEvent)
5128 rxevent_Cancel(call->growMTUEvent, call,
5129 RX_CALL_REFCOUNT_ALIVE);
5131 if (call->delayedAbortEvent) {
5132 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5133 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5135 rxi_SendCallAbort(call, packet, 0, 1);
5136 rxi_FreePacket(packet);
5141 * Update the peer with the congestion information in this call
5142 * so other calls on this connection can pick up where this call
5143 * left off. If the congestion sequence numbers don't match then
5144 * another call experienced a retransmission.
5146 peer = call->conn->peer;
5147 MUTEX_ENTER(&peer->peer_lock);
5149 if (call->congestSeq == peer->congestSeq) {
5150 peer->cwind = MAX(peer->cwind, call->cwind);
5151 peer->MTU = MAX(peer->MTU, call->MTU);
5152 peer->nDgramPackets =
5153 MAX(peer->nDgramPackets, call->nDgramPackets);
5156 call->abortCode = 0;
5157 call->abortCount = 0;
5159 if (peer->maxDgramPackets > 1) {
5160 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5162 call->MTU = peer->MTU;
5164 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5165 call->ssthresh = rx_maxSendWindow;
5166 call->nDgramPackets = peer->nDgramPackets;
5167 call->congestSeq = peer->congestSeq;
5168 MUTEX_EXIT(&peer->peer_lock);
5170 flags = call->flags;
5171 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5172 rxi_WaitforTQBusy(call);
5173 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5175 rxi_ClearTransmitQueue(call, 1);
5176 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5177 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5181 if ((flags & RX_CALL_PEER_BUSY)) {
5182 /* The call channel is still busy; resetting the call doesn't change
5184 call->flags |= RX_CALL_PEER_BUSY;
5187 rxi_ClearReceiveQueue(call);
5188 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5192 call->twind = call->conn->twind[call->channel];
5193 call->rwind = call->conn->rwind[call->channel];
5194 call->nSoftAcked = 0;
5195 call->nextCwind = 0;
5198 call->nCwindAcks = 0;
5199 call->nSoftAcks = 0;
5200 call->nHardAcks = 0;
5202 call->tfirst = call->rnext = call->tnext = 1;
5205 call->lastAcked = 0;
5206 call->localStatus = call->remoteStatus = 0;
5208 if (flags & RX_CALL_READER_WAIT) {
5209 #ifdef RX_ENABLE_LOCKS
5210 CV_BROADCAST(&call->cv_rq);
5212 osi_rxWakeup(&call->rq);
5215 if (flags & RX_CALL_WAIT_PACKETS) {
5216 MUTEX_ENTER(&rx_freePktQ_lock);
5217 rxi_PacketsUnWait(); /* XXX */
5218 MUTEX_EXIT(&rx_freePktQ_lock);
5220 #ifdef RX_ENABLE_LOCKS
5221 CV_SIGNAL(&call->cv_twind);
5223 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5224 osi_rxWakeup(&call->twind);
5227 #ifdef RX_ENABLE_LOCKS
5228 /* The following ensures that we don't mess with any queue while some
5229 * other thread might also be doing so. The call_queue_lock field is
5230 * is only modified under the call lock. If the call is in the process
5231 * of being removed from a queue, the call is not locked until the
5232 * the queue lock is dropped and only then is the call_queue_lock field
5233 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5234 * Note that any other routine which removes a call from a queue has to
5235 * obtain the queue lock before examing the queue and removing the call.
5237 if (call->call_queue_lock) {
5238 MUTEX_ENTER(call->call_queue_lock);
5239 if (queue_IsOnQueue(call)) {
5241 if (flags & RX_CALL_WAIT_PROC) {
5242 rx_atomic_dec(&rx_nWaiting);
5245 MUTEX_EXIT(call->call_queue_lock);
5246 CLEAR_CALL_QUEUE_LOCK(call);
5248 #else /* RX_ENABLE_LOCKS */
5249 if (queue_IsOnQueue(call)) {
5251 if (flags & RX_CALL_WAIT_PROC)
5252 rx_atomic_dec(&rx_nWaiting);
5254 #endif /* RX_ENABLE_LOCKS */
5256 rxi_KeepAliveOff(call);
5257 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5260 /* Send an acknowledge for the indicated packet (seq,serial) of the
5261 * indicated call, for the indicated reason (reason). This
5262 * acknowledge will specifically acknowledge receiving the packet, and
5263 * will also specify which other packets for this call have been
5264 * received. This routine returns the packet that was used to the
5265 * caller. The caller is responsible for freeing it or re-using it.
5266 * This acknowledgement also returns the highest sequence number
5267 * actually read out by the higher level to the sender; the sender
5268 * promises to keep around packets that have not been read by the
5269 * higher level yet (unless, of course, the sender decides to abort
5270 * the call altogether). Any of p, seq, serial, pflags, or reason may
5271 * be set to zero without ill effect. That is, if they are zero, they
5272 * will not convey any information.
5273 * NOW there is a trailer field, after the ack where it will safely be
5274 * ignored by mundanes, which indicates the maximum size packet this
5275 * host can swallow. */
5277 struct rx_packet *optionalPacket; use to send ack (or null)
5278 int seq; Sequence number of the packet we are acking
5279 int serial; Serial number of the packet
5280 int pflags; Flags field from packet header
5281 int reason; Reason an acknowledge was prompted
5285 rxi_SendAck(struct rx_call *call,
5286 struct rx_packet *optionalPacket, int serial, int reason,
5289 struct rx_ackPacket *ap;
5290 struct rx_packet *rqp;
5291 struct rx_packet *nxp; /* For queue_Scan */
5292 struct rx_packet *p;
5295 afs_uint32 padbytes = 0;
5296 #ifdef RX_ENABLE_TSFPQ
5297 struct rx_ts_info_t * rx_ts_info;
5301 * Open the receive window once a thread starts reading packets
5303 if (call->rnext > 1) {
5304 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5307 /* Don't attempt to grow MTU if this is a critical ping */
5308 if (reason == RX_ACK_MTU) {
5309 /* keep track of per-call attempts, if we're over max, do in small
5310 * otherwise in larger? set a size to increment by, decrease
5313 if (call->conn->peer->maxPacketSize &&
5314 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5316 padbytes = call->conn->peer->maxPacketSize+16;
5318 padbytes = call->conn->peer->maxMTU + 128;
5320 /* do always try a minimum size ping */
5321 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5323 /* subtract the ack payload */
5324 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5325 reason = RX_ACK_PING;
5328 call->nHardAcks = 0;
5329 call->nSoftAcks = 0;
5330 if (call->rnext > call->lastAcked)
5331 call->lastAcked = call->rnext;
5335 rx_computelen(p, p->length); /* reset length, you never know */
5336 } /* where that's been... */
5337 #ifdef RX_ENABLE_TSFPQ
5339 RX_TS_INFO_GET(rx_ts_info);
5340 if ((p = rx_ts_info->local_special_packet)) {
5341 rx_computelen(p, p->length);
5342 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5343 rx_ts_info->local_special_packet = p;
5344 } else { /* We won't send the ack, but don't panic. */
5345 return optionalPacket;
5349 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5350 /* We won't send the ack, but don't panic. */
5351 return optionalPacket;
5356 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5359 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5360 #ifndef RX_ENABLE_TSFPQ
5361 if (!optionalPacket)
5364 return optionalPacket;
5366 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5367 if (rx_Contiguous(p) < templ) {
5368 #ifndef RX_ENABLE_TSFPQ
5369 if (!optionalPacket)
5372 return optionalPacket;
5377 /* MTUXXX failing to send an ack is very serious. We should */
5378 /* try as hard as possible to send even a partial ack; it's */
5379 /* better than nothing. */
5380 ap = (struct rx_ackPacket *)rx_DataOf(p);
5381 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5382 ap->reason = reason;
5384 /* The skew computation used to be bogus, I think it's better now. */
5385 /* We should start paying attention to skew. XXX */
5386 ap->serial = htonl(serial);
5387 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5389 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5390 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5392 /* No fear of running out of ack packet here because there can only be at most
5393 * one window full of unacknowledged packets. The window size must be constrained
5394 * to be less than the maximum ack size, of course. Also, an ack should always
5395 * fit into a single packet -- it should not ever be fragmented. */
5396 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5397 if (!rqp || !call->rq.next
5398 || (rqp->header.seq > (call->rnext + call->rwind))) {
5399 #ifndef RX_ENABLE_TSFPQ
5400 if (!optionalPacket)
5403 rxi_CallError(call, RX_CALL_DEAD);
5404 return optionalPacket;
5407 while (rqp->header.seq > call->rnext + offset)
5408 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5409 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5411 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5412 #ifndef RX_ENABLE_TSFPQ
5413 if (!optionalPacket)
5416 rxi_CallError(call, RX_CALL_DEAD);
5417 return optionalPacket;
5422 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5424 /* these are new for AFS 3.3 */
5425 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5426 templ = htonl(templ);
5427 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5428 templ = htonl(call->conn->peer->ifMTU);
5429 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5430 sizeof(afs_int32), &templ);
5432 /* new for AFS 3.4 */
5433 templ = htonl(call->rwind);
5434 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5435 sizeof(afs_int32), &templ);
5437 /* new for AFS 3.5 */
5438 templ = htonl(call->conn->peer->ifDgramPackets);
5439 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5440 sizeof(afs_int32), &templ);
5442 p->header.serviceId = call->conn->serviceId;
5443 p->header.cid = (call->conn->cid | call->channel);
5444 p->header.callNumber = *call->callNumber;
5446 p->header.securityIndex = call->conn->securityIndex;
5447 p->header.epoch = call->conn->epoch;
5448 p->header.type = RX_PACKET_TYPE_ACK;
5449 p->header.flags = RX_SLOW_START_OK;
5450 if (reason == RX_ACK_PING) {
5451 p->header.flags |= RX_REQUEST_ACK;
5453 clock_GetTime(&call->pingRequestTime);
5456 p->length = padbytes +
5457 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5460 /* not fast but we can potentially use this if truncated
5461 * fragments are delivered to figure out the mtu.
5463 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5464 sizeof(afs_int32), sizeof(afs_int32),
5468 if (call->conn->type == RX_CLIENT_CONNECTION)
5469 p->header.flags |= RX_CLIENT_INITIATED;
5473 if (rxdebug_active) {
5477 len = _snprintf(msg, sizeof(msg),
5478 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5479 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5480 ntohl(ap->serial), ntohl(ap->previousPacket),
5481 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5482 ap->nAcks, ntohs(ap->bufferSpace) );
5486 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5487 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5491 OutputDebugString(msg);
5493 #else /* AFS_NT40_ENV */
5495 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5496 ap->reason, ntohl(ap->previousPacket),
5497 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5499 for (offset = 0; offset < ap->nAcks; offset++)
5500 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5505 #endif /* AFS_NT40_ENV */
5508 int i, nbytes = p->length;
5510 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5511 if (nbytes <= p->wirevec[i].iov_len) {
5514 savelen = p->wirevec[i].iov_len;
5516 p->wirevec[i].iov_len = nbytes;
5518 rxi_Send(call, p, istack);
5519 p->wirevec[i].iov_len = savelen;
5523 nbytes -= p->wirevec[i].iov_len;
5526 if (rx_stats_active)
5527 rx_atomic_inc(&rx_stats.ackPacketsSent);
5528 #ifndef RX_ENABLE_TSFPQ
5529 if (!optionalPacket)
5532 return optionalPacket; /* Return packet for re-use by caller */
5536 struct rx_packet **list;
5541 /* Send all of the packets in the list in single datagram */
5543 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5544 int istack, int moreFlag)
5549 struct clock now, retryTime;
5550 struct rx_connection *conn = call->conn;
5551 struct rx_peer *peer = conn->peer;
5553 MUTEX_ENTER(&peer->peer_lock);
5554 peer->nSent += xmit->len;
5555 if (xmit->resending)
5556 peer->reSends += xmit->len;
5557 retryTime = peer->timeout;
5558 MUTEX_EXIT(&peer->peer_lock);
5560 if (rx_stats_active) {
5561 if (xmit->resending)
5562 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5564 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5567 clock_GetTime(&now);
5568 clock_Add(&retryTime, &now);
5570 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5574 /* Set the packet flags and schedule the resend events */
5575 /* Only request an ack for the last packet in the list */
5576 for (i = 0; i < xmit->len; i++) {
5577 struct rx_packet *packet = xmit->list[i];
5579 packet->retryTime = retryTime;
5580 if (packet->header.serial) {
5581 /* Exponentially backoff retry times */
5582 if (packet->backoff < MAXBACKOFF) {
5583 /* so it can't stay == 0 */
5584 packet->backoff = (packet->backoff << 1) + 1;
5587 clock_Addmsec(&(packet->retryTime),
5588 ((afs_uint32) packet->backoff) << 8);
5591 /* Wait a little extra for the ack on the last packet */
5593 && !(packet->header.flags & RX_CLIENT_INITIATED)) {
5594 clock_Addmsec(&(packet->retryTime), 400);
5597 /* Record the time sent */
5598 packet->timeSent = now;
5600 /* Ask for an ack on retransmitted packets, on every other packet
5601 * if the peer doesn't support slow start. Ask for an ack on every
5602 * packet until the congestion window reaches the ack rate. */
5603 if (packet->header.serial) {
5606 /* improved RTO calculation- not Karn */
5607 packet->firstSent = now;
5608 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5609 || (!(call->flags & RX_CALL_SLOW_START_OK)
5610 && (packet->header.seq & 1)))) {
5615 /* Tag this packet as not being the last in this group,
5616 * for the receiver's benefit */
5617 if (i < xmit->len - 1 || moreFlag) {
5618 packet->header.flags |= RX_MORE_PACKETS;
5623 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5626 /* Since we're about to send a data packet to the peer, it's
5627 * safe to nuke any scheduled end-of-packets ack */
5628 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5630 MUTEX_EXIT(&call->lock);
5631 MUTEX_ENTER(&rx_refcnt_mutex);
5632 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5633 MUTEX_EXIT(&rx_refcnt_mutex);
5634 if (xmit->len > 1) {
5635 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5637 rxi_SendPacket(call, conn, xmit->list[0], istack);
5639 MUTEX_ENTER(&call->lock);
5640 MUTEX_ENTER(&rx_refcnt_mutex);
5641 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5642 MUTEX_EXIT(&rx_refcnt_mutex);
5644 /* Update last send time for this call (for keep-alive
5645 * processing), and for the connection (so that we can discover
5646 * idle connections) */
5647 conn->lastSendTime = call->lastSendTime = clock_Sec();
5648 /* Let a set of retransmits trigger an idle timeout */
5649 if (!xmit->resending)
5650 call->lastSendData = call->lastSendTime;
5653 /* When sending packets we need to follow these rules:
5654 * 1. Never send more than maxDgramPackets in a jumbogram.
5655 * 2. Never send a packet with more than two iovecs in a jumbogram.
5656 * 3. Never send a retransmitted packet in a jumbogram.
5657 * 4. Never send more than cwind/4 packets in a jumbogram
5658 * We always keep the last list we should have sent so we
5659 * can set the RX_MORE_PACKETS flags correctly.
5663 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5667 struct xmitlist working;
5668 struct xmitlist last;
5670 struct rx_peer *peer = call->conn->peer;
5671 int morePackets = 0;
5673 memset(&last, 0, sizeof(struct xmitlist));
5674 working.list = &list[0];
5676 working.resending = 0;
5678 for (i = 0; i < len; i++) {
5679 /* Does the current packet force us to flush the current list? */
5681 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5682 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5684 /* This sends the 'last' list and then rolls the current working
5685 * set into the 'last' one, and resets the working set */
5688 rxi_SendList(call, &last, istack, 1);
5689 /* If the call enters an error state stop sending, or if
5690 * we entered congestion recovery mode, stop sending */
5691 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5696 working.resending = 0;
5697 working.list = &list[i];
5699 /* Add the current packet to the list if it hasn't been acked.
5700 * Otherwise adjust the list pointer to skip the current packet. */
5701 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5704 if (list[i]->header.serial)
5705 working.resending = 1;
5707 /* Do we need to flush the list? */
5708 if (working.len >= (int)peer->maxDgramPackets
5709 || working.len >= (int)call->nDgramPackets
5710 || working.len >= (int)call->cwind
5711 || list[i]->header.serial
5712 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5714 rxi_SendList(call, &last, istack, 1);
5715 /* If the call enters an error state stop sending, or if
5716 * we entered congestion recovery mode, stop sending */
5718 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5723 working.resending = 0;
5724 working.list = &list[i + 1];
5727 if (working.len != 0) {
5728 osi_Panic("rxi_SendList error");
5730 working.list = &list[i + 1];
5734 /* Send the whole list when the call is in receive mode, when
5735 * the call is in eof mode, when we are in fast recovery mode,
5736 * and when we have the last packet */
5737 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5738 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5739 || (call->flags & RX_CALL_FAST_RECOVER)) {
5740 /* Check for the case where the current list contains
5741 * an acked packet. Since we always send retransmissions
5742 * in a separate packet, we only need to check the first
5743 * packet in the list */
5744 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5748 rxi_SendList(call, &last, istack, morePackets);
5749 /* If the call enters an error state stop sending, or if
5750 * we entered congestion recovery mode, stop sending */
5751 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5755 rxi_SendList(call, &working, istack, 0);
5757 } else if (last.len > 0) {
5758 rxi_SendList(call, &last, istack, 0);
5759 /* Packets which are in 'working' are not sent by this call */
5763 #ifdef RX_ENABLE_LOCKS
5764 /* Call rxi_Start, below, but with the call lock held. */
5766 rxi_StartUnlocked(struct rxevent *event,
5767 void *arg0, void *arg1, int istack)
5769 struct rx_call *call = arg0;
5771 MUTEX_ENTER(&call->lock);
5772 rxi_Start(event, call, arg1, istack);
5773 MUTEX_EXIT(&call->lock);
5775 #endif /* RX_ENABLE_LOCKS */
5777 /* This routine is called when new packets are readied for
5778 * transmission and when retransmission may be necessary, or when the
5779 * transmission window or burst count are favourable. This should be
5780 * better optimized for new packets, the usual case, now that we've
5781 * got rid of queues of send packets. XXXXXXXXXXX */
5783 rxi_Start(struct rxevent *event,
5784 void *arg0, void *arg1, int istack)
5786 struct rx_call *call = arg0;
5788 struct rx_packet *p;
5789 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5790 struct clock now, usenow, retryTime;
5795 /* If rxi_Start is being called as a result of a resend event,
5796 * then make sure that the event pointer is removed from the call
5797 * structure, since there is no longer a per-call retransmission
5799 if (event && event == call->resendEvent) {
5800 MUTEX_ENTER(&rx_refcnt_mutex);
5801 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5802 MUTEX_EXIT(&rx_refcnt_mutex);
5803 call->resendEvent = NULL;
5805 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5806 rxi_CheckBusy(call);
5809 if (queue_IsEmpty(&call->tq)) {
5816 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5817 if (rx_stats_active)
5818 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5823 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5825 clock_GetTime(&now);
5828 /* Send (or resend) any packets that need it, subject to
5829 * window restrictions and congestion burst control
5830 * restrictions. Ask for an ack on the last packet sent in
5831 * this burst. For now, we're relying upon the window being
5832 * considerably bigger than the largest number of packets that
5833 * are typically sent at once by one initial call to
5834 * rxi_Start. This is probably bogus (perhaps we should ask
5835 * for an ack when we're half way through the current
5836 * window?). Also, for non file transfer applications, this
5837 * may end up asking for an ack for every packet. Bogus. XXXX
5840 * But check whether we're here recursively, and let the other guy
5843 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5844 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5845 call->flags |= RX_CALL_TQ_BUSY;
5847 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5849 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5850 call->flags &= ~RX_CALL_NEED_START;
5851 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5853 maxXmitPackets = MIN(call->twind, call->cwind);
5854 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5855 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5856 /* We shouldn't be sending packets if a thread is waiting
5857 * to initiate congestion recovery */
5858 dpf(("call %d waiting to initiate fast recovery\n",
5859 *(call->callNumber)));
5863 && (call->flags & RX_CALL_FAST_RECOVER)) {
5864 /* Only send one packet during fast recovery */
5865 dpf(("call %d restricted to one packet per send during fast recovery\n",
5866 *(call->callNumber)));
5869 #ifdef RX_TRACK_PACKETS
5870 if ((p->flags & RX_PKTFLAG_FREE)
5871 || (!queue_IsEnd(&call->tq, nxp)
5872 && (nxp->flags & RX_PKTFLAG_FREE))
5873 || (p == (struct rx_packet *)&rx_freePacketQueue)
5874 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5875 osi_Panic("rxi_Start: xmit queue clobbered");
5878 if (p->flags & RX_PKTFLAG_ACKED) {
5879 /* Since we may block, don't trust this */
5880 usenow.sec = usenow.usec = 0;
5881 if (rx_stats_active)
5882 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5883 continue; /* Ignore this packet if it has been acknowledged */
5886 /* Turn off all flags except these ones, which are the same
5887 * on each transmission */
5888 p->header.flags &= RX_PRESET_FLAGS;
5890 if (p->header.seq >=
5891 call->tfirst + MIN((int)call->twind,
5892 (int)(call->nSoftAcked +
5894 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5895 /* Note: if we're waiting for more window space, we can
5896 * still send retransmits; hence we don't return here, but
5897 * break out to schedule a retransmit event */
5898 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5899 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5904 /* Transmit the packet if it needs to be sent. */
5905 if (!clock_Lt(&now, &p->retryTime)) {
5906 if (nXmitPackets == maxXmitPackets) {
5907 rxi_SendXmitList(call, call->xmitList,
5908 nXmitPackets, istack);
5911 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u\n",
5912 *(call->callNumber), p,
5914 p->retryTime.sec, p->retryTime.usec));
5915 call->xmitList[nXmitPackets++] = p;
5919 /* xmitList now hold pointers to all of the packets that are
5920 * ready to send. Now we loop to send the packets */
5921 if (nXmitPackets > 0) {
5922 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
5926 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5928 * TQ references no longer protected by this flag; they must remain
5929 * protected by the global lock.
5931 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5932 call->flags &= ~RX_CALL_TQ_BUSY;
5933 rxi_WakeUpTransmitQueue(call);
5937 /* We went into the error state while sending packets. Now is
5938 * the time to reset the call. This will also inform the using
5939 * process that the call is in an error state.
5941 if (rx_stats_active)
5942 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
5943 call->flags &= ~RX_CALL_TQ_BUSY;
5944 rxi_WakeUpTransmitQueue(call);
5945 rxi_CallError(call, call->error);
5948 #ifdef RX_ENABLE_LOCKS
5949 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5951 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5952 /* Some packets have received acks. If they all have, we can clear
5953 * the transmit queue.
5956 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5957 if (p->header.seq < call->tfirst
5958 && (p->flags & RX_PKTFLAG_ACKED)) {
5960 #ifdef RX_TRACK_PACKETS
5961 p->flags &= ~RX_PKTFLAG_TQ;
5963 #ifdef RXDEBUG_PACKET
5971 call->flags |= RX_CALL_TQ_CLEARME;
5973 #endif /* RX_ENABLE_LOCKS */
5974 /* Don't bother doing retransmits if the TQ is cleared. */
5975 if (call->flags & RX_CALL_TQ_CLEARME) {
5976 rxi_ClearTransmitQueue(call, 1);
5978 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5981 /* Always post a resend event, if there is anything in the
5982 * queue, and resend is possible. There should be at least
5983 * one unacknowledged packet in the queue ... otherwise none
5984 * of these packets should be on the queue in the first place.
5986 if (call->resendEvent) {
5987 /* Cancel the existing event and post a new one */
5988 rxevent_Cancel(call->resendEvent, call,
5989 RX_CALL_REFCOUNT_RESEND);
5992 /* The retry time is the retry time on the first unacknowledged
5993 * packet inside the current window */
5995 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5996 /* Don't set timers for packets outside the window */
5997 if (p->header.seq >= call->tfirst + call->twind) {
6001 if (!(p->flags & RX_PKTFLAG_ACKED)
6002 && !clock_IsZero(&p->retryTime)) {
6004 retryTime = p->retryTime;
6009 /* Post a new event to re-run rxi_Start when retries may be needed */
6010 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
6011 #ifdef RX_ENABLE_LOCKS
6012 MUTEX_ENTER(&rx_refcnt_mutex);
6013 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
6014 MUTEX_EXIT(&rx_refcnt_mutex);
6016 rxevent_PostNow2(&retryTime, &usenow,
6018 (void *)call, 0, istack);
6019 #else /* RX_ENABLE_LOCKS */
6021 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
6022 (void *)call, 0, istack);
6023 #endif /* RX_ENABLE_LOCKS */
6026 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6027 } while (call->flags & RX_CALL_NEED_START);
6029 * TQ references no longer protected by this flag; they must remain
6030 * protected by the global lock.
6032 call->flags &= ~RX_CALL_TQ_BUSY;
6033 rxi_WakeUpTransmitQueue(call);
6035 call->flags |= RX_CALL_NEED_START;
6037 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6039 if (call->resendEvent) {
6040 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6045 /* Also adjusts the keep alive parameters for the call, to reflect
6046 * that we have just sent a packet (so keep alives aren't sent
6049 rxi_Send(struct rx_call *call, struct rx_packet *p,
6052 struct rx_connection *conn = call->conn;
6054 /* Stamp each packet with the user supplied status */
6055 p->header.userStatus = call->localStatus;
6057 /* Allow the security object controlling this call's security to
6058 * make any last-minute changes to the packet */
6059 RXS_SendPacket(conn->securityObject, call, p);
6061 /* Since we're about to send SOME sort of packet to the peer, it's
6062 * safe to nuke any scheduled end-of-packets ack */
6063 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6065 /* Actually send the packet, filling in more connection-specific fields */
6066 MUTEX_EXIT(&call->lock);
6067 MUTEX_ENTER(&rx_refcnt_mutex);
6068 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6069 MUTEX_EXIT(&rx_refcnt_mutex);
6070 rxi_SendPacket(call, conn, p, istack);
6071 MUTEX_ENTER(&rx_refcnt_mutex);
6072 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6073 MUTEX_EXIT(&rx_refcnt_mutex);
6074 MUTEX_ENTER(&call->lock);
6076 /* Update last send time for this call (for keep-alive
6077 * processing), and for the connection (so that we can discover
6078 * idle connections) */
6079 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6080 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6081 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6083 conn->lastSendTime = call->lastSendTime = clock_Sec();
6084 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6085 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6086 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6087 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6088 RX_ACK_PING_RESPONSE)))
6089 call->lastSendData = call->lastSendTime;
6093 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6094 * that things are fine. Also called periodically to guarantee that nothing
6095 * falls through the cracks (e.g. (error + dally) connections have keepalive
6096 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6098 * haveCTLock Set if calling from rxi_ReapConnections
6100 #ifdef RX_ENABLE_LOCKS
6102 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6103 #else /* RX_ENABLE_LOCKS */
6105 rxi_CheckCall(struct rx_call *call)
6106 #endif /* RX_ENABLE_LOCKS */
6108 struct rx_connection *conn = call->conn;
6110 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6111 afs_uint32 fudgeFactor;
6115 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6116 if (call->flags & RX_CALL_TQ_BUSY) {
6117 /* Call is active and will be reset by rxi_Start if it's
6118 * in an error state.
6123 /* RTT + 8*MDEV, rounded up to the next second. */
6124 fudgeFactor = (((afs_uint32) conn->peer->rtt >> 3) +
6125 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
6127 deadTime = conn->secondsUntilDead + fudgeFactor;
6129 /* These are computed to the second (+- 1 second). But that's
6130 * good enough for these values, which should be a significant
6131 * number of seconds. */
6132 if (now > (call->lastReceiveTime + deadTime)) {
6133 if (call->state == RX_STATE_ACTIVE) {
6135 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
6137 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6138 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6139 ip_stack_t *ipst = ns->netstack_ip;
6141 ire = ire_cache_lookup(conn->peer->host
6142 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6144 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6146 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6153 if (ire && ire->ire_max_frag > 0)
6154 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6156 #if defined(GLOBAL_NETSTACKID)
6160 #endif /* ADAPT_PMTU */
6161 cerror = RX_CALL_DEAD;
6164 #ifdef RX_ENABLE_LOCKS
6165 /* Cancel pending events */
6166 rxevent_Cancel(call->delayedAckEvent, call,
6167 RX_CALL_REFCOUNT_DELAY);
6168 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6169 rxevent_Cancel(call->keepAliveEvent, call,
6170 RX_CALL_REFCOUNT_ALIVE);
6171 if (call->growMTUEvent)
6172 rxevent_Cancel(call->growMTUEvent, call,
6173 RX_CALL_REFCOUNT_ALIVE);
6174 MUTEX_ENTER(&rx_refcnt_mutex);
6175 if (call->refCount == 0) {
6176 rxi_FreeCall(call, haveCTLock);
6177 MUTEX_EXIT(&rx_refcnt_mutex);
6180 MUTEX_EXIT(&rx_refcnt_mutex);
6182 #else /* RX_ENABLE_LOCKS */
6183 rxi_FreeCall(call, 0);
6185 #endif /* RX_ENABLE_LOCKS */
6187 /* Non-active calls are destroyed if they are not responding
6188 * to pings; active calls are simply flagged in error, so the
6189 * attached process can die reasonably gracefully. */
6192 if (conn->idleDeadTime) {
6193 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6196 /* see if we have a non-activity timeout */
6197 if (call->startWait && idleDeadTime
6198 && ((call->startWait + idleDeadTime) < now) &&
6199 (call->flags & RX_CALL_READER_WAIT)) {
6200 if (call->state == RX_STATE_ACTIVE) {
6201 cerror = RX_CALL_TIMEOUT;
6205 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6206 && ((call->lastSendData + idleDeadTime) < now)) {
6207 if (call->state == RX_STATE_ACTIVE) {
6208 cerror = conn->idleDeadErr;
6213 if (conn->hardDeadTime) {
6214 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6217 /* see if we have a hard timeout */
6219 && (now > (hardDeadTime + call->startTime.sec))) {
6220 if (call->state == RX_STATE_ACTIVE)
6221 rxi_CallError(call, RX_CALL_TIMEOUT);
6226 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6227 && call->lastReceiveTime) {
6228 int oldMTU = conn->peer->ifMTU;
6230 /* if we thought we could send more, perhaps things got worse */
6231 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6232 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6233 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6234 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6236 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6238 /* minimum capped in SetPeerMtu */
6239 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6242 conn->lastPacketSize = 0;
6244 /* needed so ResetCall doesn't clobber us. */
6245 call->MTU = conn->peer->ifMTU;
6247 /* if we never succeeded, let the error pass out as-is */
6248 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6249 cerror = conn->msgsizeRetryErr;
6252 rxi_CallError(call, cerror);
6257 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6259 struct rx_connection *conn = arg1;
6260 struct rx_header theader;
6261 char tbuffer[1 + sizeof(struct rx_header)];
6262 struct sockaddr_in taddr;
6265 struct iovec tmpiov[2];
6268 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6271 tp = &tbuffer[sizeof(struct rx_header)];
6272 taddr.sin_family = AF_INET;
6273 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6274 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6275 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6276 taddr.sin_len = sizeof(struct sockaddr_in);
6278 memset(&theader, 0, sizeof(theader));
6279 theader.epoch = htonl(999);
6281 theader.callNumber = 0;
6284 theader.type = RX_PACKET_TYPE_VERSION;
6285 theader.flags = RX_LAST_PACKET;
6286 theader.serviceId = 0;
6288 memcpy(tbuffer, &theader, sizeof(theader));
6289 memcpy(tp, &a, sizeof(a));
6290 tmpiov[0].iov_base = tbuffer;
6291 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6293 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6295 MUTEX_ENTER(&conn->conn_data_lock);
6296 MUTEX_ENTER(&rx_refcnt_mutex);
6297 /* Only reschedule ourselves if the connection would not be destroyed */
6298 if (conn->refCount <= 1) {
6299 conn->natKeepAliveEvent = NULL;
6300 MUTEX_EXIT(&rx_refcnt_mutex);
6301 MUTEX_EXIT(&conn->conn_data_lock);
6302 rx_DestroyConnection(conn); /* drop the reference for this */
6304 conn->refCount--; /* drop the reference for this */
6305 MUTEX_EXIT(&rx_refcnt_mutex);
6306 conn->natKeepAliveEvent = NULL;
6307 rxi_ScheduleNatKeepAliveEvent(conn);
6308 MUTEX_EXIT(&conn->conn_data_lock);
6313 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6315 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6316 struct clock when, now;
6317 clock_GetTime(&now);
6319 when.sec += conn->secondsUntilNatPing;
6320 MUTEX_ENTER(&rx_refcnt_mutex);
6321 conn->refCount++; /* hold a reference for this */
6322 MUTEX_EXIT(&rx_refcnt_mutex);
6323 conn->natKeepAliveEvent =
6324 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6329 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6331 MUTEX_ENTER(&conn->conn_data_lock);
6332 conn->secondsUntilNatPing = seconds;
6334 rxi_ScheduleNatKeepAliveEvent(conn);
6335 MUTEX_EXIT(&conn->conn_data_lock);
6339 rxi_NatKeepAliveOn(struct rx_connection *conn)
6341 MUTEX_ENTER(&conn->conn_data_lock);
6342 rxi_ScheduleNatKeepAliveEvent(conn);
6343 MUTEX_EXIT(&conn->conn_data_lock);
6346 /* When a call is in progress, this routine is called occasionally to
6347 * make sure that some traffic has arrived (or been sent to) the peer.
6348 * If nothing has arrived in a reasonable amount of time, the call is
6349 * declared dead; if nothing has been sent for a while, we send a
6350 * keep-alive packet (if we're actually trying to keep the call alive)
6353 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6355 struct rx_call *call = arg1;
6356 struct rx_connection *conn;
6359 MUTEX_ENTER(&rx_refcnt_mutex);
6360 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6361 MUTEX_EXIT(&rx_refcnt_mutex);
6362 MUTEX_ENTER(&call->lock);
6363 if (event == call->keepAliveEvent)
6364 call->keepAliveEvent = NULL;
6367 #ifdef RX_ENABLE_LOCKS
6368 if (rxi_CheckCall(call, 0)) {
6369 MUTEX_EXIT(&call->lock);
6372 #else /* RX_ENABLE_LOCKS */
6373 if (rxi_CheckCall(call))
6375 #endif /* RX_ENABLE_LOCKS */
6377 /* Don't try to keep alive dallying calls */
6378 if (call->state == RX_STATE_DALLY) {
6379 MUTEX_EXIT(&call->lock);
6384 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6385 /* Don't try to send keepalives if there is unacknowledged data */
6386 /* the rexmit code should be good enough, this little hack
6387 * doesn't quite work XXX */
6388 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6390 rxi_ScheduleKeepAliveEvent(call);
6391 MUTEX_EXIT(&call->lock);
6394 /* Does what's on the nameplate. */
6396 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6398 struct rx_call *call = arg1;
6399 struct rx_connection *conn;
6401 MUTEX_ENTER(&rx_refcnt_mutex);
6402 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6403 MUTEX_EXIT(&rx_refcnt_mutex);
6404 MUTEX_ENTER(&call->lock);
6406 if (event == call->growMTUEvent)
6407 call->growMTUEvent = NULL;
6409 #ifdef RX_ENABLE_LOCKS
6410 if (rxi_CheckCall(call, 0)) {
6411 MUTEX_EXIT(&call->lock);
6414 #else /* RX_ENABLE_LOCKS */
6415 if (rxi_CheckCall(call))
6417 #endif /* RX_ENABLE_LOCKS */
6419 /* Don't bother with dallying calls */
6420 if (call->state == RX_STATE_DALLY) {
6421 MUTEX_EXIT(&call->lock);
6428 * keep being scheduled, just don't do anything if we're at peak,
6429 * or we're not set up to be properly handled (idle timeout required)
6431 if ((conn->peer->maxPacketSize != 0) &&
6432 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6433 (conn->idleDeadErr))
6434 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6435 rxi_ScheduleGrowMTUEvent(call, 0);
6436 MUTEX_EXIT(&call->lock);
6440 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6442 if (!call->keepAliveEvent) {
6443 struct clock when, now;
6444 clock_GetTime(&now);
6446 when.sec += call->conn->secondsUntilPing;
6447 MUTEX_ENTER(&rx_refcnt_mutex);
6448 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6449 MUTEX_EXIT(&rx_refcnt_mutex);
6450 call->keepAliveEvent =
6451 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6456 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6458 if (!call->growMTUEvent) {
6459 struct clock when, now;
6461 clock_GetTime(&now);
6464 if (call->conn->secondsUntilPing)
6465 secs = (6*call->conn->secondsUntilPing)-1;
6467 if (call->conn->secondsUntilDead)
6468 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6472 MUTEX_ENTER(&rx_refcnt_mutex);
6473 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6474 MUTEX_EXIT(&rx_refcnt_mutex);
6475 call->growMTUEvent =
6476 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6480 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6482 rxi_KeepAliveOn(struct rx_call *call)
6484 /* Pretend last packet received was received now--i.e. if another
6485 * packet isn't received within the keep alive time, then the call
6486 * will die; Initialize last send time to the current time--even
6487 * if a packet hasn't been sent yet. This will guarantee that a
6488 * keep-alive is sent within the ping time */
6489 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6490 rxi_ScheduleKeepAliveEvent(call);
6494 rxi_GrowMTUOn(struct rx_call *call)
6496 struct rx_connection *conn = call->conn;
6497 MUTEX_ENTER(&conn->conn_data_lock);
6498 conn->lastPingSizeSer = conn->lastPingSize = 0;
6499 MUTEX_EXIT(&conn->conn_data_lock);
6500 rxi_ScheduleGrowMTUEvent(call, 1);
6503 /* This routine is called to send connection abort messages
6504 * that have been delayed to throttle looping clients. */
6506 rxi_SendDelayedConnAbort(struct rxevent *event,
6507 void *arg1, void *unused)
6509 struct rx_connection *conn = arg1;
6512 struct rx_packet *packet;
6514 MUTEX_ENTER(&conn->conn_data_lock);
6515 conn->delayedAbortEvent = NULL;
6516 error = htonl(conn->error);
6518 MUTEX_EXIT(&conn->conn_data_lock);
6519 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6522 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6523 RX_PACKET_TYPE_ABORT, (char *)&error,
6525 rxi_FreePacket(packet);
6529 /* This routine is called to send call abort messages
6530 * that have been delayed to throttle looping clients. */
6532 rxi_SendDelayedCallAbort(struct rxevent *event,
6533 void *arg1, void *dummy)
6535 struct rx_call *call = arg1;
6538 struct rx_packet *packet;
6540 MUTEX_ENTER(&call->lock);
6541 call->delayedAbortEvent = NULL;
6542 error = htonl(call->error);
6544 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6547 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6548 (char *)&error, sizeof(error), 0);
6549 rxi_FreePacket(packet);
6551 MUTEX_EXIT(&call->lock);
6552 MUTEX_ENTER(&rx_refcnt_mutex);
6553 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6554 MUTEX_EXIT(&rx_refcnt_mutex);
6557 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6558 * seconds) to ask the client to authenticate itself. The routine
6559 * issues a challenge to the client, which is obtained from the
6560 * security object associated with the connection */
6562 rxi_ChallengeEvent(struct rxevent *event,
6563 void *arg0, void *arg1, int tries)
6565 struct rx_connection *conn = arg0;
6567 conn->challengeEvent = NULL;
6568 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6569 struct rx_packet *packet;
6570 struct clock when, now;
6573 /* We've failed to authenticate for too long.
6574 * Reset any calls waiting for authentication;
6575 * they are all in RX_STATE_PRECALL.
6579 MUTEX_ENTER(&conn->conn_call_lock);
6580 for (i = 0; i < RX_MAXCALLS; i++) {
6581 struct rx_call *call = conn->call[i];
6583 MUTEX_ENTER(&call->lock);
6584 if (call->state == RX_STATE_PRECALL) {
6585 rxi_CallError(call, RX_CALL_DEAD);
6586 rxi_SendCallAbort(call, NULL, 0, 0);
6588 MUTEX_EXIT(&call->lock);
6591 MUTEX_EXIT(&conn->conn_call_lock);
6595 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6597 /* If there's no packet available, do this later. */
6598 RXS_GetChallenge(conn->securityObject, conn, packet);
6599 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6600 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6601 rxi_FreePacket(packet);
6603 clock_GetTime(&now);
6605 when.sec += RX_CHALLENGE_TIMEOUT;
6606 conn->challengeEvent =
6607 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6612 /* Call this routine to start requesting the client to authenticate
6613 * itself. This will continue until authentication is established,
6614 * the call times out, or an invalid response is returned. The
6615 * security object associated with the connection is asked to create
6616 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6617 * defined earlier. */
6619 rxi_ChallengeOn(struct rx_connection *conn)
6621 if (!conn->challengeEvent) {
6622 RXS_CreateChallenge(conn->securityObject, conn);
6623 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6628 /* rxi_ComputeRoundTripTime is called with peer locked. */
6629 /* peer may be null */
6631 rxi_ComputeRoundTripTime(struct rx_packet *p,
6632 struct rx_ackPacket *ack,
6633 struct rx_peer *peer,
6636 struct clock thisRtt, *sentp;
6640 /* If the ACK is delayed, then do nothing */
6641 if (ack->reason == RX_ACK_DELAY)
6644 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6645 * their RTT multiple times, so only include the RTT of the last packet
6647 if (p->flags & RX_JUMBO_PACKET)
6650 /* Use the serial number to determine which transmission the ACK is for,
6651 * and set the sent time to match this. If we have no serial number, then
6652 * only use the ACK for RTT calculations if the packet has not been
6656 serial = ntohl(ack->serial);
6658 if (serial == p->header.serial) {
6659 sentp = &p->timeSent;
6660 } else if (serial == p->firstSerial) {
6661 sentp = &p->firstSent;
6662 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6663 sentp = &p->firstSent;
6667 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6668 sentp = &p->firstSent;
6675 if (clock_Lt(&thisRtt, sentp))
6676 return; /* somebody set the clock back, don't count this time. */
6678 clock_Sub(&thisRtt, sentp);
6679 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6680 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6682 if (clock_IsZero(&thisRtt)) {
6684 * The actual round trip time is shorter than the
6685 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6686 * Since we can't tell which at the moment we will assume 1ms.
6688 thisRtt.usec = 1000;
6691 if (rx_stats_active) {
6692 MUTEX_ENTER(&rx_stats_mutex);
6693 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6694 rx_stats.minRtt = thisRtt;
6695 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6696 if (thisRtt.sec > 60) {
6697 MUTEX_EXIT(&rx_stats_mutex);
6698 return; /* somebody set the clock ahead */
6700 rx_stats.maxRtt = thisRtt;
6702 clock_Add(&rx_stats.totalRtt, &thisRtt);
6703 rx_atomic_inc(&rx_stats.nRttSamples);
6704 MUTEX_EXIT(&rx_stats_mutex);
6707 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6709 /* Apply VanJacobson round-trip estimations */
6714 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6715 * srtt is stored as fixed point with 3 bits after the binary
6716 * point (i.e., scaled by 8). The following magic is
6717 * equivalent to the smoothing algorithm in rfc793 with an
6718 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6719 * srtt'*8 = rtt + srtt*7
6720 * srtt'*8 = srtt*8 + rtt - srtt
6721 * srtt' = srtt + rtt/8 - srtt/8
6722 * srtt' = srtt + (rtt - srtt)/8
6725 delta = _8THMSEC(&thisRtt) - peer->rtt;
6726 peer->rtt += (delta >> 3);
6729 * We accumulate a smoothed rtt variance (actually, a smoothed
6730 * mean difference), then set the retransmit timer to smoothed
6731 * rtt + 4 times the smoothed variance (was 2x in van's original
6732 * paper, but 4x works better for me, and apparently for him as
6734 * rttvar is stored as
6735 * fixed point with 2 bits after the binary point (scaled by
6736 * 4). The following is equivalent to rfc793 smoothing with
6737 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6738 * rttvar'*4 = rttvar*3 + |delta|
6739 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6740 * rttvar' = rttvar + |delta|/4 - rttvar/4
6741 * rttvar' = rttvar + (|delta| - rttvar)/4
6742 * This replaces rfc793's wired-in beta.
6743 * dev*4 = dev*4 + (|actual - expected| - dev)
6749 delta -= (peer->rtt_dev << 1);
6750 peer->rtt_dev += (delta >> 3);
6752 /* I don't have a stored RTT so I start with this value. Since I'm
6753 * probably just starting a call, and will be pushing more data down
6754 * this, I expect congestion to increase rapidly. So I fudge a
6755 * little, and I set deviance to half the rtt. In practice,
6756 * deviance tends to approach something a little less than
6757 * half the smoothed rtt. */
6758 peer->rtt = _8THMSEC(&thisRtt) + 8;
6759 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6761 /* the timeout is RTT + 4*MDEV + rx_minPeerTimeout msec.
6762 * This is because one end or the other of these connections is usually
6763 * in a user process, and can be switched and/or swapped out. So on fast,
6764 * reliable networks, the timeout would otherwise be too short. */
6765 rtt_timeout = ((peer->rtt >> 3) + peer->rtt_dev) + rx_minPeerTimeout;
6766 clock_Zero(&(peer->timeout));
6767 clock_Addmsec(&(peer->timeout), rtt_timeout);
6769 /* Reset the backedOff flag since we just computed a new timeout value */
6770 peer->backedOff = 0;
6772 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6773 p->header.callNumber, p, MSEC(&thisRtt), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6777 /* Find all server connections that have not been active for a long time, and
6780 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6782 struct clock now, when;
6783 clock_GetTime(&now);
6785 /* Find server connection structures that haven't been used for
6786 * greater than rx_idleConnectionTime */
6788 struct rx_connection **conn_ptr, **conn_end;
6789 int i, havecalls = 0;
6790 MUTEX_ENTER(&rx_connHashTable_lock);
6791 for (conn_ptr = &rx_connHashTable[0], conn_end =
6792 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6794 struct rx_connection *conn, *next;
6795 struct rx_call *call;
6799 for (conn = *conn_ptr; conn; conn = next) {
6800 /* XXX -- Shouldn't the connection be locked? */
6803 for (i = 0; i < RX_MAXCALLS; i++) {
6804 call = conn->call[i];
6808 code = MUTEX_TRYENTER(&call->lock);
6811 #ifdef RX_ENABLE_LOCKS
6812 result = rxi_CheckCall(call, 1);
6813 #else /* RX_ENABLE_LOCKS */
6814 result = rxi_CheckCall(call);
6815 #endif /* RX_ENABLE_LOCKS */
6816 MUTEX_EXIT(&call->lock);
6818 /* If CheckCall freed the call, it might
6819 * have destroyed the connection as well,
6820 * which screws up the linked lists.
6826 if (conn->type == RX_SERVER_CONNECTION) {
6827 /* This only actually destroys the connection if
6828 * there are no outstanding calls */
6829 MUTEX_ENTER(&conn->conn_data_lock);
6830 MUTEX_ENTER(&rx_refcnt_mutex);
6831 if (!havecalls && !conn->refCount
6832 && ((conn->lastSendTime + rx_idleConnectionTime) <
6834 conn->refCount++; /* it will be decr in rx_DestroyConn */
6835 MUTEX_EXIT(&rx_refcnt_mutex);
6836 MUTEX_EXIT(&conn->conn_data_lock);
6837 #ifdef RX_ENABLE_LOCKS
6838 rxi_DestroyConnectionNoLock(conn);
6839 #else /* RX_ENABLE_LOCKS */
6840 rxi_DestroyConnection(conn);
6841 #endif /* RX_ENABLE_LOCKS */
6843 #ifdef RX_ENABLE_LOCKS
6845 MUTEX_EXIT(&rx_refcnt_mutex);
6846 MUTEX_EXIT(&conn->conn_data_lock);
6848 #endif /* RX_ENABLE_LOCKS */
6852 #ifdef RX_ENABLE_LOCKS
6853 while (rx_connCleanup_list) {
6854 struct rx_connection *conn;
6855 conn = rx_connCleanup_list;
6856 rx_connCleanup_list = rx_connCleanup_list->next;
6857 MUTEX_EXIT(&rx_connHashTable_lock);
6858 rxi_CleanupConnection(conn);
6859 MUTEX_ENTER(&rx_connHashTable_lock);
6861 MUTEX_EXIT(&rx_connHashTable_lock);
6862 #endif /* RX_ENABLE_LOCKS */
6865 /* Find any peer structures that haven't been used (haven't had an
6866 * associated connection) for greater than rx_idlePeerTime */
6868 struct rx_peer **peer_ptr, **peer_end;
6872 * Why do we need to hold the rx_peerHashTable_lock across
6873 * the incrementing of peer_ptr since the rx_peerHashTable
6874 * array is not changing? We don't.
6876 * By dropping the lock periodically we can permit other
6877 * activities to be performed while a rxi_ReapConnections
6878 * call is in progress. The goal of reap connections
6879 * is to clean up quickly without causing large amounts
6880 * of contention. Therefore, it is important that global
6881 * mutexes not be held for extended periods of time.
6883 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6884 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6886 struct rx_peer *peer, *next, *prev;
6888 MUTEX_ENTER(&rx_peerHashTable_lock);
6889 for (prev = peer = *peer_ptr; peer; peer = next) {
6891 code = MUTEX_TRYENTER(&peer->peer_lock);
6892 if ((code) && (peer->refCount == 0)
6893 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6894 rx_interface_stat_p rpc_stat, nrpc_stat;
6898 * now know that this peer object is one to be
6899 * removed from the hash table. Once it is removed
6900 * it can't be referenced by other threads.
6901 * Lets remove it first and decrement the struct
6902 * nPeerStructs count.
6904 if (peer == *peer_ptr) {
6910 if (rx_stats_active)
6911 rx_atomic_dec(&rx_stats.nPeerStructs);
6914 * Now if we hold references on 'prev' and 'next'
6915 * we can safely drop the rx_peerHashTable_lock
6916 * while we destroy this 'peer' object.
6922 MUTEX_EXIT(&rx_peerHashTable_lock);
6924 MUTEX_EXIT(&peer->peer_lock);
6925 MUTEX_DESTROY(&peer->peer_lock);
6927 (&peer->rpcStats, rpc_stat, nrpc_stat,
6928 rx_interface_stat)) {
6929 unsigned int num_funcs;
6932 queue_Remove(&rpc_stat->queue_header);
6933 queue_Remove(&rpc_stat->all_peers);
6934 num_funcs = rpc_stat->stats[0].func_total;
6936 sizeof(rx_interface_stat_t) +
6937 rpc_stat->stats[0].func_total *
6938 sizeof(rx_function_entry_v1_t);
6940 rxi_Free(rpc_stat, space);
6942 MUTEX_ENTER(&rx_rpc_stats);
6943 rxi_rpc_peer_stat_cnt -= num_funcs;
6944 MUTEX_EXIT(&rx_rpc_stats);
6949 * Regain the rx_peerHashTable_lock and
6950 * decrement the reference count on 'prev'
6953 MUTEX_ENTER(&rx_peerHashTable_lock);
6960 MUTEX_EXIT(&peer->peer_lock);
6965 MUTEX_EXIT(&rx_peerHashTable_lock);
6969 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6970 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6971 * GC, just below. Really, we shouldn't have to keep moving packets from
6972 * one place to another, but instead ought to always know if we can
6973 * afford to hold onto a packet in its particular use. */
6974 MUTEX_ENTER(&rx_freePktQ_lock);
6975 if (rx_waitingForPackets) {
6976 rx_waitingForPackets = 0;
6977 #ifdef RX_ENABLE_LOCKS
6978 CV_BROADCAST(&rx_waitingForPackets_cv);
6980 osi_rxWakeup(&rx_waitingForPackets);
6983 MUTEX_EXIT(&rx_freePktQ_lock);
6986 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6987 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6991 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6992 * rx.h is sort of strange this is better. This is called with a security
6993 * object before it is discarded. Each connection using a security object has
6994 * its own refcount to the object so it won't actually be freed until the last
6995 * connection is destroyed.
6997 * This is the only rxs module call. A hold could also be written but no one
7001 rxs_Release(struct rx_securityClass *aobj)
7003 return RXS_Close(aobj);
7007 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
7008 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
7009 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
7010 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
7012 /* Adjust our estimate of the transmission rate to this peer, given
7013 * that the packet p was just acked. We can adjust peer->timeout and
7014 * call->twind. Pragmatically, this is called
7015 * only with packets of maximal length.
7016 * Called with peer and call locked.
7020 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
7021 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
7023 afs_int32 xferSize, xferMs;
7027 /* Count down packets */
7028 if (peer->rateFlag > 0)
7030 /* Do nothing until we're enabled */
7031 if (peer->rateFlag != 0)
7036 /* Count only when the ack seems legitimate */
7037 switch (ackReason) {
7038 case RX_ACK_REQUESTED:
7040 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
7044 case RX_ACK_PING_RESPONSE:
7045 if (p) /* want the response to ping-request, not data send */
7047 clock_GetTime(&newTO);
7048 if (clock_Gt(&newTO, &call->pingRequestTime)) {
7049 clock_Sub(&newTO, &call->pingRequestTime);
7050 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
7054 xferSize = rx_AckDataSize(rx_maxSendWindow) + RX_HEADER_SIZE;
7061 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)\n",
7062 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
7063 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
7065 /* Track only packets that are big enough. */
7066 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
7070 /* absorb RTT data (in milliseconds) for these big packets */
7071 if (peer->smRtt == 0) {
7072 peer->smRtt = xferMs;
7074 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
7079 if (peer->countDown) {
7083 peer->countDown = 10; /* recalculate only every so often */
7085 /* In practice, we can measure only the RTT for full packets,
7086 * because of the way Rx acks the data that it receives. (If it's
7087 * smaller than a full packet, it often gets implicitly acked
7088 * either by the call response (from a server) or by the next call
7089 * (from a client), and either case confuses transmission times
7090 * with processing times.) Therefore, replace the above
7091 * more-sophisticated processing with a simpler version, where the
7092 * smoothed RTT is kept for full-size packets, and the time to
7093 * transmit a windowful of full-size packets is simply RTT *
7094 * windowSize. Again, we take two steps:
7095 - ensure the timeout is large enough for a single packet's RTT;
7096 - ensure that the window is small enough to fit in the desired timeout.*/
7098 /* First, the timeout check. */
7099 minTime = peer->smRtt;
7100 /* Get a reasonable estimate for a timeout period */
7102 newTO.sec = minTime / 1000;
7103 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
7105 /* Increase the timeout period so that we can always do at least
7106 * one packet exchange */
7107 if (clock_Gt(&newTO, &peer->timeout)) {
7109 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u)\n",
7110 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
7111 newTO.sec, newTO.usec, peer->smRtt));
7113 peer->timeout = newTO;
7116 /* Now, get an estimate for the transmit window size. */
7117 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
7118 /* Now, convert to the number of full packets that could fit in a
7119 * reasonable fraction of that interval */
7120 minTime /= (peer->smRtt << 1);
7121 minTime = MAX(minTime, rx_minPeerTimeout);
7122 xferSize = minTime; /* (make a copy) */
7124 /* Now clamp the size to reasonable bounds. */
7127 else if (minTime > rx_maxSendWindow)
7128 minTime = rx_maxSendWindow;
7129 /* if (minTime != peer->maxWindow) {
7130 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u)\n",
7131 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
7132 peer->timeout.sec, peer->timeout.usec, peer->smRtt));
7133 peer->maxWindow = minTime;
7134 elide... call->twind = minTime;
7138 /* Cut back on the peer timeout if it had earlier grown unreasonably.
7139 * Discern this by calculating the timeout necessary for rx_Window
7141 if ((xferSize > rx_maxSendWindow) && (peer->timeout.sec >= 3)) {
7142 /* calculate estimate for transmission interval in milliseconds */
7143 minTime = rx_maxSendWindow * peer->smRtt;
7144 if (minTime < 1000) {
7145 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u)\n",
7146 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
7147 peer->timeout.usec, peer->smRtt));
7149 newTO.sec = 0; /* cut back on timeout by half a second */
7150 newTO.usec = 500000;
7151 clock_Sub(&peer->timeout, &newTO);
7156 } /* end of rxi_ComputeRate */
7157 #endif /* ADAPT_WINDOW */
7165 #define TRACE_OPTION_RX_DEBUG 16
7173 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7174 0, KEY_QUERY_VALUE, &parmKey);
7175 if (code != ERROR_SUCCESS)
7178 dummyLen = sizeof(TraceOption);
7179 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7180 (BYTE *) &TraceOption, &dummyLen);
7181 if (code == ERROR_SUCCESS) {
7182 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7184 RegCloseKey (parmKey);
7185 #endif /* AFS_NT40_ENV */
7190 rx_DebugOnOff(int on)
7194 rxdebug_active = on;
7200 rx_StatsOnOff(int on)
7202 rx_stats_active = on;
7206 /* Don't call this debugging routine directly; use dpf */
7208 rxi_DebugPrint(char *format, ...)
7217 va_start(ap, format);
7219 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7222 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7224 OutputDebugString(msg);
7230 va_start(ap, format);
7232 clock_GetTime(&now);
7233 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7234 (unsigned int)now.usec);
7235 vfprintf(rx_Log, format, ap);
7243 * This function is used to process the rx_stats structure that is local
7244 * to a process as well as an rx_stats structure received from a remote
7245 * process (via rxdebug). Therefore, it needs to do minimal version
7249 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7250 afs_int32 freePackets, char version)
7254 if (size != sizeof(struct rx_statistics)) {
7256 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7257 size, sizeof(struct rx_statistics));
7260 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7263 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7264 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7265 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7266 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7267 s->specialPktAllocFailures);
7269 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7270 s->receivePktAllocFailures, s->sendPktAllocFailures,
7271 s->specialPktAllocFailures);
7275 " greedy %u, " "bogusReads %u (last from host %x), "
7276 "noPackets %u, " "noBuffers %u, " "selects %u, "
7277 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7278 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7279 s->selects, s->sendSelects);
7281 fprintf(file, " packets read: ");
7282 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7283 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7285 fprintf(file, "\n");
7288 " other read counters: data %u, " "ack %u, " "dup %u "
7289 "spurious %u " "dally %u\n", s->dataPacketsRead,
7290 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7291 s->ignorePacketDally);
7293 fprintf(file, " packets sent: ");
7294 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7295 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7297 fprintf(file, "\n");
7300 " other send counters: ack %u, " "data %u (not resends), "
7301 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7302 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7303 s->dataPacketsPushed, s->ignoreAckedPacket);
7306 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7307 s->netSendFailures, (int)s->fatalErrors);
7309 if (s->nRttSamples) {
7310 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7311 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7313 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7314 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7318 " %d server connections, " "%d client connections, "
7319 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7320 s->nServerConns, s->nClientConns, s->nPeerStructs,
7321 s->nCallStructs, s->nFreeCallStructs);
7323 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7324 fprintf(file, " %d clock updates\n", clock_nUpdates);
7328 /* for backward compatibility */
7330 rx_PrintStats(FILE * file)
7332 MUTEX_ENTER(&rx_stats_mutex);
7333 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7334 sizeof(rx_stats), rx_nFreePackets,
7336 MUTEX_EXIT(&rx_stats_mutex);
7340 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7342 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7343 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7344 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7347 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7348 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7349 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7352 " Packet size %d, " "max in packet skew %d, "
7353 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7354 (int)peer->outPacketSkew);
7358 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7360 * This mutex protects the following static variables:
7364 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7365 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7367 #define LOCK_RX_DEBUG
7368 #define UNLOCK_RX_DEBUG
7369 #endif /* AFS_PTHREAD_ENV */
7371 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7373 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7374 u_char type, void *inputData, size_t inputLength,
7375 void *outputData, size_t outputLength)
7377 static afs_int32 counter = 100;
7378 time_t waitTime, waitCount;
7379 struct rx_header theader;
7382 struct timeval tv_now, tv_wake, tv_delta;
7383 struct sockaddr_in taddr, faddr;
7397 tp = &tbuffer[sizeof(struct rx_header)];
7398 taddr.sin_family = AF_INET;
7399 taddr.sin_port = remotePort;
7400 taddr.sin_addr.s_addr = remoteAddr;
7401 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7402 taddr.sin_len = sizeof(struct sockaddr_in);
7405 memset(&theader, 0, sizeof(theader));
7406 theader.epoch = htonl(999);
7408 theader.callNumber = htonl(counter);
7411 theader.type = type;
7412 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7413 theader.serviceId = 0;
7415 memcpy(tbuffer, &theader, sizeof(theader));
7416 memcpy(tp, inputData, inputLength);
7418 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7419 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7421 /* see if there's a packet available */
7422 gettimeofday(&tv_wake, NULL);
7423 tv_wake.tv_sec += waitTime;
7426 FD_SET(socket, &imask);
7427 tv_delta.tv_sec = tv_wake.tv_sec;
7428 tv_delta.tv_usec = tv_wake.tv_usec;
7429 gettimeofday(&tv_now, NULL);
7431 if (tv_delta.tv_usec < tv_now.tv_usec) {
7433 tv_delta.tv_usec += 1000000;
7436 tv_delta.tv_usec -= tv_now.tv_usec;
7438 if (tv_delta.tv_sec < tv_now.tv_sec) {
7442 tv_delta.tv_sec -= tv_now.tv_sec;
7445 code = select(0, &imask, 0, 0, &tv_delta);
7446 #else /* AFS_NT40_ENV */
7447 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7448 #endif /* AFS_NT40_ENV */
7449 if (code == 1 && FD_ISSET(socket, &imask)) {
7450 /* now receive a packet */
7451 faddrLen = sizeof(struct sockaddr_in);
7453 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7454 (struct sockaddr *)&faddr, &faddrLen);
7457 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7458 if (counter == ntohl(theader.callNumber))
7466 /* see if we've timed out */
7474 code -= sizeof(struct rx_header);
7475 if (code > outputLength)
7476 code = outputLength;
7477 memcpy(outputData, tp, code);
7480 #endif /* RXDEBUG */
7483 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7484 afs_uint16 remotePort, struct rx_debugStats * stat,
7485 afs_uint32 * supportedValues)
7487 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7489 struct rx_debugIn in;
7491 *supportedValues = 0;
7492 in.type = htonl(RX_DEBUGI_GETSTATS);
7495 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7496 &in, sizeof(in), stat, sizeof(*stat));
7499 * If the call was successful, fixup the version and indicate
7500 * what contents of the stat structure are valid.
7501 * Also do net to host conversion of fields here.
7505 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7506 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7508 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7509 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7511 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7512 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7514 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7515 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7517 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7518 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7520 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7521 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7523 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7524 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7526 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7527 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7529 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7530 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7532 stat->nFreePackets = ntohl(stat->nFreePackets);
7533 stat->packetReclaims = ntohl(stat->packetReclaims);
7534 stat->callsExecuted = ntohl(stat->callsExecuted);
7535 stat->nWaiting = ntohl(stat->nWaiting);
7536 stat->idleThreads = ntohl(stat->idleThreads);
7537 stat->nWaited = ntohl(stat->nWaited);
7538 stat->nPackets = ntohl(stat->nPackets);
7547 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7548 afs_uint16 remotePort, struct rx_statistics * stat,
7549 afs_uint32 * supportedValues)
7551 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7553 struct rx_debugIn in;
7554 afs_int32 *lp = (afs_int32 *) stat;
7558 * supportedValues is currently unused, but added to allow future
7559 * versioning of this function.
7562 *supportedValues = 0;
7563 in.type = htonl(RX_DEBUGI_RXSTATS);
7565 memset(stat, 0, sizeof(*stat));
7567 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7568 &in, sizeof(in), stat, sizeof(*stat));
7573 * Do net to host conversion here
7576 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7587 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7588 afs_uint16 remotePort, size_t version_length,
7591 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7593 return MakeDebugCall(socket, remoteAddr, remotePort,
7594 RX_PACKET_TYPE_VERSION, a, 1, version,
7602 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7603 afs_uint16 remotePort, afs_int32 * nextConnection,
7604 int allConnections, afs_uint32 debugSupportedValues,
7605 struct rx_debugConn * conn,
7606 afs_uint32 * supportedValues)
7608 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7610 struct rx_debugIn in;
7614 * supportedValues is currently unused, but added to allow future
7615 * versioning of this function.
7618 *supportedValues = 0;
7619 if (allConnections) {
7620 in.type = htonl(RX_DEBUGI_GETALLCONN);
7622 in.type = htonl(RX_DEBUGI_GETCONN);
7624 in.index = htonl(*nextConnection);
7625 memset(conn, 0, sizeof(*conn));
7627 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7628 &in, sizeof(in), conn, sizeof(*conn));
7631 *nextConnection += 1;
7634 * Convert old connection format to new structure.
7637 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7638 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7639 #define MOVEvL(a) (conn->a = vL->a)
7641 /* any old or unrecognized version... */
7642 for (i = 0; i < RX_MAXCALLS; i++) {
7643 MOVEvL(callState[i]);
7644 MOVEvL(callMode[i]);
7645 MOVEvL(callFlags[i]);
7646 MOVEvL(callOther[i]);
7648 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7649 MOVEvL(secStats.type);
7650 MOVEvL(secStats.level);
7651 MOVEvL(secStats.flags);
7652 MOVEvL(secStats.expires);
7653 MOVEvL(secStats.packetsReceived);
7654 MOVEvL(secStats.packetsSent);
7655 MOVEvL(secStats.bytesReceived);
7656 MOVEvL(secStats.bytesSent);
7661 * Do net to host conversion here
7663 * I don't convert host or port since we are most likely
7664 * going to want these in NBO.
7666 conn->cid = ntohl(conn->cid);
7667 conn->serial = ntohl(conn->serial);
7668 for (i = 0; i < RX_MAXCALLS; i++) {
7669 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7671 conn->error = ntohl(conn->error);
7672 conn->secStats.flags = ntohl(conn->secStats.flags);
7673 conn->secStats.expires = ntohl(conn->secStats.expires);
7674 conn->secStats.packetsReceived =
7675 ntohl(conn->secStats.packetsReceived);
7676 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7677 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7678 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7679 conn->epoch = ntohl(conn->epoch);
7680 conn->natMTU = ntohl(conn->natMTU);
7689 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7690 afs_uint16 remotePort, afs_int32 * nextPeer,
7691 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7692 afs_uint32 * supportedValues)
7694 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7696 struct rx_debugIn in;
7699 * supportedValues is currently unused, but added to allow future
7700 * versioning of this function.
7703 *supportedValues = 0;
7704 in.type = htonl(RX_DEBUGI_GETPEER);
7705 in.index = htonl(*nextPeer);
7706 memset(peer, 0, sizeof(*peer));
7708 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7709 &in, sizeof(in), peer, sizeof(*peer));
7715 * Do net to host conversion here
7717 * I don't convert host or port since we are most likely
7718 * going to want these in NBO.
7720 peer->ifMTU = ntohs(peer->ifMTU);
7721 peer->idleWhen = ntohl(peer->idleWhen);
7722 peer->refCount = ntohs(peer->refCount);
7723 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7724 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7725 peer->rtt = ntohl(peer->rtt);
7726 peer->rtt_dev = ntohl(peer->rtt_dev);
7727 peer->timeout.sec = ntohl(peer->timeout.sec);
7728 peer->timeout.usec = ntohl(peer->timeout.usec);
7729 peer->nSent = ntohl(peer->nSent);
7730 peer->reSends = ntohl(peer->reSends);
7731 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7732 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7733 peer->rateFlag = ntohl(peer->rateFlag);
7734 peer->natMTU = ntohs(peer->natMTU);
7735 peer->maxMTU = ntohs(peer->maxMTU);
7736 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7737 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7738 peer->MTU = ntohs(peer->MTU);
7739 peer->cwind = ntohs(peer->cwind);
7740 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7741 peer->congestSeq = ntohs(peer->congestSeq);
7742 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7743 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7744 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7745 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7754 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7755 struct rx_debugPeer * peerStats)
7758 afs_int32 error = 1; /* default to "did not succeed" */
7759 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7761 MUTEX_ENTER(&rx_peerHashTable_lock);
7762 for(tp = rx_peerHashTable[hashValue];
7763 tp != NULL; tp = tp->next) {
7764 if (tp->host == peerHost)
7770 MUTEX_EXIT(&rx_peerHashTable_lock);
7774 MUTEX_ENTER(&tp->peer_lock);
7775 peerStats->host = tp->host;
7776 peerStats->port = tp->port;
7777 peerStats->ifMTU = tp->ifMTU;
7778 peerStats->idleWhen = tp->idleWhen;
7779 peerStats->refCount = tp->refCount;
7780 peerStats->burstSize = tp->burstSize;
7781 peerStats->burst = tp->burst;
7782 peerStats->burstWait.sec = tp->burstWait.sec;
7783 peerStats->burstWait.usec = tp->burstWait.usec;
7784 peerStats->rtt = tp->rtt;
7785 peerStats->rtt_dev = tp->rtt_dev;
7786 peerStats->timeout.sec = tp->timeout.sec;
7787 peerStats->timeout.usec = tp->timeout.usec;
7788 peerStats->nSent = tp->nSent;
7789 peerStats->reSends = tp->reSends;
7790 peerStats->inPacketSkew = tp->inPacketSkew;
7791 peerStats->outPacketSkew = tp->outPacketSkew;
7792 peerStats->rateFlag = tp->rateFlag;
7793 peerStats->natMTU = tp->natMTU;
7794 peerStats->maxMTU = tp->maxMTU;
7795 peerStats->maxDgramPackets = tp->maxDgramPackets;
7796 peerStats->ifDgramPackets = tp->ifDgramPackets;
7797 peerStats->MTU = tp->MTU;
7798 peerStats->cwind = tp->cwind;
7799 peerStats->nDgramPackets = tp->nDgramPackets;
7800 peerStats->congestSeq = tp->congestSeq;
7801 peerStats->bytesSent.high = tp->bytesSent.high;
7802 peerStats->bytesSent.low = tp->bytesSent.low;
7803 peerStats->bytesReceived.high = tp->bytesReceived.high;
7804 peerStats->bytesReceived.low = tp->bytesReceived.low;
7805 MUTEX_EXIT(&tp->peer_lock);
7807 MUTEX_ENTER(&rx_peerHashTable_lock);
7810 MUTEX_EXIT(&rx_peerHashTable_lock);
7818 struct rx_serverQueueEntry *np;
7821 struct rx_call *call;
7822 struct rx_serverQueueEntry *sq;
7826 if (rxinit_status == 1) {
7828 return; /* Already shutdown. */
7832 #ifndef AFS_PTHREAD_ENV
7833 FD_ZERO(&rx_selectMask);
7834 #endif /* AFS_PTHREAD_ENV */
7835 rxi_dataQuota = RX_MAX_QUOTA;
7836 #ifndef AFS_PTHREAD_ENV
7838 #endif /* AFS_PTHREAD_ENV */
7841 #ifndef AFS_PTHREAD_ENV
7842 #ifndef AFS_USE_GETTIMEOFDAY
7844 #endif /* AFS_USE_GETTIMEOFDAY */
7845 #endif /* AFS_PTHREAD_ENV */
7847 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7848 call = queue_First(&rx_freeCallQueue, rx_call);
7850 rxi_Free(call, sizeof(struct rx_call));
7853 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7854 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7860 struct rx_peer **peer_ptr, **peer_end;
7861 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7862 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7864 struct rx_peer *peer, *next;
7866 MUTEX_ENTER(&rx_peerHashTable_lock);
7867 for (peer = *peer_ptr; peer; peer = next) {
7868 rx_interface_stat_p rpc_stat, nrpc_stat;
7871 MUTEX_ENTER(&rx_rpc_stats);
7872 MUTEX_ENTER(&peer->peer_lock);
7874 (&peer->rpcStats, rpc_stat, nrpc_stat,
7875 rx_interface_stat)) {
7876 unsigned int num_funcs;
7879 queue_Remove(&rpc_stat->queue_header);
7880 queue_Remove(&rpc_stat->all_peers);
7881 num_funcs = rpc_stat->stats[0].func_total;
7883 sizeof(rx_interface_stat_t) +
7884 rpc_stat->stats[0].func_total *
7885 sizeof(rx_function_entry_v1_t);
7887 rxi_Free(rpc_stat, space);
7889 /* rx_rpc_stats must be held */
7890 rxi_rpc_peer_stat_cnt -= num_funcs;
7892 MUTEX_EXIT(&peer->peer_lock);
7893 MUTEX_EXIT(&rx_rpc_stats);
7897 if (rx_stats_active)
7898 rx_atomic_dec(&rx_stats.nPeerStructs);
7900 MUTEX_EXIT(&rx_peerHashTable_lock);
7903 for (i = 0; i < RX_MAX_SERVICES; i++) {
7905 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7907 for (i = 0; i < rx_hashTableSize; i++) {
7908 struct rx_connection *tc, *ntc;
7909 MUTEX_ENTER(&rx_connHashTable_lock);
7910 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7912 for (j = 0; j < RX_MAXCALLS; j++) {
7914 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7917 rxi_Free(tc, sizeof(*tc));
7919 MUTEX_EXIT(&rx_connHashTable_lock);
7922 MUTEX_ENTER(&freeSQEList_lock);
7924 while ((np = rx_FreeSQEList)) {
7925 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7926 MUTEX_DESTROY(&np->lock);
7927 rxi_Free(np, sizeof(*np));
7930 MUTEX_EXIT(&freeSQEList_lock);
7931 MUTEX_DESTROY(&freeSQEList_lock);
7932 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7933 MUTEX_DESTROY(&rx_connHashTable_lock);
7934 MUTEX_DESTROY(&rx_peerHashTable_lock);
7935 MUTEX_DESTROY(&rx_serverPool_lock);
7937 osi_Free(rx_connHashTable,
7938 rx_hashTableSize * sizeof(struct rx_connection *));
7939 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7941 UNPIN(rx_connHashTable,
7942 rx_hashTableSize * sizeof(struct rx_connection *));
7943 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7945 rxi_FreeAllPackets();
7947 MUTEX_ENTER(&rx_quota_mutex);
7948 rxi_dataQuota = RX_MAX_QUOTA;
7949 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7950 MUTEX_EXIT(&rx_quota_mutex);
7955 #ifdef RX_ENABLE_LOCKS
7957 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7959 if (!MUTEX_ISMINE(lockaddr))
7960 osi_Panic("Lock not held: %s", msg);
7962 #endif /* RX_ENABLE_LOCKS */
7967 * Routines to implement connection specific data.
7971 rx_KeyCreate(rx_destructor_t rtn)
7974 MUTEX_ENTER(&rxi_keyCreate_lock);
7975 key = rxi_keyCreate_counter++;
7976 rxi_keyCreate_destructor = (rx_destructor_t *)
7977 realloc((void *)rxi_keyCreate_destructor,
7978 (key + 1) * sizeof(rx_destructor_t));
7979 rxi_keyCreate_destructor[key] = rtn;
7980 MUTEX_EXIT(&rxi_keyCreate_lock);
7985 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7988 MUTEX_ENTER(&conn->conn_data_lock);
7989 if (!conn->specific) {
7990 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7991 for (i = 0; i < key; i++)
7992 conn->specific[i] = NULL;
7993 conn->nSpecific = key + 1;
7994 conn->specific[key] = ptr;
7995 } else if (key >= conn->nSpecific) {
7996 conn->specific = (void **)
7997 realloc(conn->specific, (key + 1) * sizeof(void *));
7998 for (i = conn->nSpecific; i < key; i++)
7999 conn->specific[i] = NULL;
8000 conn->nSpecific = key + 1;
8001 conn->specific[key] = ptr;
8003 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8004 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8005 conn->specific[key] = ptr;
8007 MUTEX_EXIT(&conn->conn_data_lock);
8011 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8014 MUTEX_ENTER(&svc->svc_data_lock);
8015 if (!svc->specific) {
8016 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
8017 for (i = 0; i < key; i++)
8018 svc->specific[i] = NULL;
8019 svc->nSpecific = key + 1;
8020 svc->specific[key] = ptr;
8021 } else if (key >= svc->nSpecific) {
8022 svc->specific = (void **)
8023 realloc(svc->specific, (key + 1) * sizeof(void *));
8024 for (i = svc->nSpecific; i < key; i++)
8025 svc->specific[i] = NULL;
8026 svc->nSpecific = key + 1;
8027 svc->specific[key] = ptr;
8029 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8030 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8031 svc->specific[key] = ptr;
8033 MUTEX_EXIT(&svc->svc_data_lock);
8037 rx_GetSpecific(struct rx_connection *conn, int key)
8040 MUTEX_ENTER(&conn->conn_data_lock);
8041 if (key >= conn->nSpecific)
8044 ptr = conn->specific[key];
8045 MUTEX_EXIT(&conn->conn_data_lock);
8050 rx_GetServiceSpecific(struct rx_service *svc, int key)
8053 MUTEX_ENTER(&svc->svc_data_lock);
8054 if (key >= svc->nSpecific)
8057 ptr = svc->specific[key];
8058 MUTEX_EXIT(&svc->svc_data_lock);
8063 #endif /* !KERNEL */
8066 * processStats is a queue used to store the statistics for the local
8067 * process. Its contents are similar to the contents of the rpcStats
8068 * queue on a rx_peer structure, but the actual data stored within
8069 * this queue contains totals across the lifetime of the process (assuming
8070 * the stats have not been reset) - unlike the per peer structures
8071 * which can come and go based upon the peer lifetime.
8074 static struct rx_queue processStats = { &processStats, &processStats };
8077 * peerStats is a queue used to store the statistics for all peer structs.
8078 * Its contents are the union of all the peer rpcStats queues.
8081 static struct rx_queue peerStats = { &peerStats, &peerStats };
8084 * rxi_monitor_processStats is used to turn process wide stat collection
8088 static int rxi_monitor_processStats = 0;
8091 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8094 static int rxi_monitor_peerStats = 0;
8097 * rxi_AddRpcStat - given all of the information for a particular rpc
8098 * call, create (if needed) and update the stat totals for the rpc.
8102 * IN stats - the queue of stats that will be updated with the new value
8104 * IN rxInterface - a unique number that identifies the rpc interface
8106 * IN currentFunc - the index of the function being invoked
8108 * IN totalFunc - the total number of functions in this interface
8110 * IN queueTime - the amount of time this function waited for a thread
8112 * IN execTime - the amount of time this function invocation took to execute
8114 * IN bytesSent - the number bytes sent by this invocation
8116 * IN bytesRcvd - the number bytes received by this invocation
8118 * IN isServer - if true, this invocation was made to a server
8120 * IN remoteHost - the ip address of the remote host
8122 * IN remotePort - the port of the remote host
8124 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8126 * INOUT counter - if a new stats structure is allocated, the counter will
8127 * be updated with the new number of allocated stat structures
8135 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8136 afs_uint32 currentFunc, afs_uint32 totalFunc,
8137 struct clock *queueTime, struct clock *execTime,
8138 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8139 afs_uint32 remoteHost, afs_uint32 remotePort,
8140 int addToPeerList, unsigned int *counter)
8143 rx_interface_stat_p rpc_stat, nrpc_stat;
8146 * See if there's already a structure for this interface
8149 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8150 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8151 && (rpc_stat->stats[0].remote_is_server == isServer))
8156 * Didn't find a match so allocate a new structure and add it to the
8160 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8161 || (rpc_stat->stats[0].interfaceId != rxInterface)
8162 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8167 sizeof(rx_interface_stat_t) +
8168 totalFunc * sizeof(rx_function_entry_v1_t);
8170 rpc_stat = rxi_Alloc(space);
8171 if (rpc_stat == NULL) {
8175 *counter += totalFunc;
8176 for (i = 0; i < totalFunc; i++) {
8177 rpc_stat->stats[i].remote_peer = remoteHost;
8178 rpc_stat->stats[i].remote_port = remotePort;
8179 rpc_stat->stats[i].remote_is_server = isServer;
8180 rpc_stat->stats[i].interfaceId = rxInterface;
8181 rpc_stat->stats[i].func_total = totalFunc;
8182 rpc_stat->stats[i].func_index = i;
8183 hzero(rpc_stat->stats[i].invocations);
8184 hzero(rpc_stat->stats[i].bytes_sent);
8185 hzero(rpc_stat->stats[i].bytes_rcvd);
8186 rpc_stat->stats[i].queue_time_sum.sec = 0;
8187 rpc_stat->stats[i].queue_time_sum.usec = 0;
8188 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8189 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8190 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8191 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8192 rpc_stat->stats[i].queue_time_max.sec = 0;
8193 rpc_stat->stats[i].queue_time_max.usec = 0;
8194 rpc_stat->stats[i].execution_time_sum.sec = 0;
8195 rpc_stat->stats[i].execution_time_sum.usec = 0;
8196 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8197 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8198 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8199 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8200 rpc_stat->stats[i].execution_time_max.sec = 0;
8201 rpc_stat->stats[i].execution_time_max.usec = 0;
8203 queue_Prepend(stats, rpc_stat);
8204 if (addToPeerList) {
8205 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8210 * Increment the stats for this function
8213 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8214 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8215 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8216 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8217 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8218 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8219 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8221 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8222 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8224 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8225 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8227 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8228 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8230 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8231 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8239 * rx_IncrementTimeAndCount - increment the times and count for a particular
8244 * IN peer - the peer who invoked the rpc
8246 * IN rxInterface - a unique number that identifies the rpc interface
8248 * IN currentFunc - the index of the function being invoked
8250 * IN totalFunc - the total number of functions in this interface
8252 * IN queueTime - the amount of time this function waited for a thread
8254 * IN execTime - the amount of time this function invocation took to execute
8256 * IN bytesSent - the number bytes sent by this invocation
8258 * IN bytesRcvd - the number bytes received by this invocation
8260 * IN isServer - if true, this invocation was made to a server
8268 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8269 afs_uint32 currentFunc, afs_uint32 totalFunc,
8270 struct clock *queueTime, struct clock *execTime,
8271 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8275 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8278 MUTEX_ENTER(&rx_rpc_stats);
8280 if (rxi_monitor_peerStats) {
8281 MUTEX_ENTER(&peer->peer_lock);
8282 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8283 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8284 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8285 MUTEX_EXIT(&peer->peer_lock);
8288 if (rxi_monitor_processStats) {
8289 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8290 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8291 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8294 MUTEX_EXIT(&rx_rpc_stats);
8299 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8303 * IN callerVersion - the rpc stat version of the caller.
8305 * IN count - the number of entries to marshall.
8307 * IN stats - pointer to stats to be marshalled.
8309 * OUT ptr - Where to store the marshalled data.
8316 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8317 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8323 * We only support the first version
8325 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8326 *(ptr++) = stats->remote_peer;
8327 *(ptr++) = stats->remote_port;
8328 *(ptr++) = stats->remote_is_server;
8329 *(ptr++) = stats->interfaceId;
8330 *(ptr++) = stats->func_total;
8331 *(ptr++) = stats->func_index;
8332 *(ptr++) = hgethi(stats->invocations);
8333 *(ptr++) = hgetlo(stats->invocations);
8334 *(ptr++) = hgethi(stats->bytes_sent);
8335 *(ptr++) = hgetlo(stats->bytes_sent);
8336 *(ptr++) = hgethi(stats->bytes_rcvd);
8337 *(ptr++) = hgetlo(stats->bytes_rcvd);
8338 *(ptr++) = stats->queue_time_sum.sec;
8339 *(ptr++) = stats->queue_time_sum.usec;
8340 *(ptr++) = stats->queue_time_sum_sqr.sec;
8341 *(ptr++) = stats->queue_time_sum_sqr.usec;
8342 *(ptr++) = stats->queue_time_min.sec;
8343 *(ptr++) = stats->queue_time_min.usec;
8344 *(ptr++) = stats->queue_time_max.sec;
8345 *(ptr++) = stats->queue_time_max.usec;
8346 *(ptr++) = stats->execution_time_sum.sec;
8347 *(ptr++) = stats->execution_time_sum.usec;
8348 *(ptr++) = stats->execution_time_sum_sqr.sec;
8349 *(ptr++) = stats->execution_time_sum_sqr.usec;
8350 *(ptr++) = stats->execution_time_min.sec;
8351 *(ptr++) = stats->execution_time_min.usec;
8352 *(ptr++) = stats->execution_time_max.sec;
8353 *(ptr++) = stats->execution_time_max.usec;
8359 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8364 * IN callerVersion - the rpc stat version of the caller
8366 * OUT myVersion - the rpc stat version of this function
8368 * OUT clock_sec - local time seconds
8370 * OUT clock_usec - local time microseconds
8372 * OUT allocSize - the number of bytes allocated to contain stats
8374 * OUT statCount - the number stats retrieved from this process.
8376 * OUT stats - the actual stats retrieved from this process.
8380 * Returns void. If successful, stats will != NULL.
8384 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8385 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8386 size_t * allocSize, afs_uint32 * statCount,
8387 afs_uint32 ** stats)
8397 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8400 * Check to see if stats are enabled
8403 MUTEX_ENTER(&rx_rpc_stats);
8404 if (!rxi_monitor_processStats) {
8405 MUTEX_EXIT(&rx_rpc_stats);
8409 clock_GetTime(&now);
8410 *clock_sec = now.sec;
8411 *clock_usec = now.usec;
8414 * Allocate the space based upon the caller version
8416 * If the client is at an older version than we are,
8417 * we return the statistic data in the older data format, but
8418 * we still return our version number so the client knows we
8419 * are maintaining more data than it can retrieve.
8422 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8423 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8424 *statCount = rxi_rpc_process_stat_cnt;
8427 * This can't happen yet, but in the future version changes
8428 * can be handled by adding additional code here
8432 if (space > (size_t) 0) {
8434 ptr = *stats = rxi_Alloc(space);
8437 rx_interface_stat_p rpc_stat, nrpc_stat;
8441 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8443 * Copy the data based upon the caller version
8445 rx_MarshallProcessRPCStats(callerVersion,
8446 rpc_stat->stats[0].func_total,
8447 rpc_stat->stats, &ptr);
8453 MUTEX_EXIT(&rx_rpc_stats);
8458 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8462 * IN callerVersion - the rpc stat version of the caller
8464 * OUT myVersion - the rpc stat version of this function
8466 * OUT clock_sec - local time seconds
8468 * OUT clock_usec - local time microseconds
8470 * OUT allocSize - the number of bytes allocated to contain stats
8472 * OUT statCount - the number of stats retrieved from the individual
8475 * OUT stats - the actual stats retrieved from the individual peer structures.
8479 * Returns void. If successful, stats will != NULL.
8483 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8484 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8485 size_t * allocSize, afs_uint32 * statCount,
8486 afs_uint32 ** stats)
8496 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8499 * Check to see if stats are enabled
8502 MUTEX_ENTER(&rx_rpc_stats);
8503 if (!rxi_monitor_peerStats) {
8504 MUTEX_EXIT(&rx_rpc_stats);
8508 clock_GetTime(&now);
8509 *clock_sec = now.sec;
8510 *clock_usec = now.usec;
8513 * Allocate the space based upon the caller version
8515 * If the client is at an older version than we are,
8516 * we return the statistic data in the older data format, but
8517 * we still return our version number so the client knows we
8518 * are maintaining more data than it can retrieve.
8521 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8522 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8523 *statCount = rxi_rpc_peer_stat_cnt;
8526 * This can't happen yet, but in the future version changes
8527 * can be handled by adding additional code here
8531 if (space > (size_t) 0) {
8533 ptr = *stats = rxi_Alloc(space);
8536 rx_interface_stat_p rpc_stat, nrpc_stat;
8540 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8542 * We have to fix the offset of rpc_stat since we are
8543 * keeping this structure on two rx_queues. The rx_queue
8544 * package assumes that the rx_queue member is the first
8545 * member of the structure. That is, rx_queue assumes that
8546 * any one item is only on one queue at a time. We are
8547 * breaking that assumption and so we have to do a little
8548 * math to fix our pointers.
8551 fix_offset = (char *)rpc_stat;
8552 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8553 rpc_stat = (rx_interface_stat_p) fix_offset;
8556 * Copy the data based upon the caller version
8558 rx_MarshallProcessRPCStats(callerVersion,
8559 rpc_stat->stats[0].func_total,
8560 rpc_stat->stats, &ptr);
8566 MUTEX_EXIT(&rx_rpc_stats);
8571 * rx_FreeRPCStats - free memory allocated by
8572 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8576 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8577 * rx_RetrievePeerRPCStats
8579 * IN allocSize - the number of bytes in stats.
8587 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8589 rxi_Free(stats, allocSize);
8593 * rx_queryProcessRPCStats - see if process rpc stat collection is
8594 * currently enabled.
8600 * Returns 0 if stats are not enabled != 0 otherwise
8604 rx_queryProcessRPCStats(void)
8607 MUTEX_ENTER(&rx_rpc_stats);
8608 rc = rxi_monitor_processStats;
8609 MUTEX_EXIT(&rx_rpc_stats);
8614 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8620 * Returns 0 if stats are not enabled != 0 otherwise
8624 rx_queryPeerRPCStats(void)
8627 MUTEX_ENTER(&rx_rpc_stats);
8628 rc = rxi_monitor_peerStats;
8629 MUTEX_EXIT(&rx_rpc_stats);
8634 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8644 rx_enableProcessRPCStats(void)
8646 MUTEX_ENTER(&rx_rpc_stats);
8647 rx_enable_stats = 1;
8648 rxi_monitor_processStats = 1;
8649 MUTEX_EXIT(&rx_rpc_stats);
8653 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8663 rx_enablePeerRPCStats(void)
8665 MUTEX_ENTER(&rx_rpc_stats);
8666 rx_enable_stats = 1;
8667 rxi_monitor_peerStats = 1;
8668 MUTEX_EXIT(&rx_rpc_stats);
8672 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8682 rx_disableProcessRPCStats(void)
8684 rx_interface_stat_p rpc_stat, nrpc_stat;
8687 MUTEX_ENTER(&rx_rpc_stats);
8690 * Turn off process statistics and if peer stats is also off, turn
8694 rxi_monitor_processStats = 0;
8695 if (rxi_monitor_peerStats == 0) {
8696 rx_enable_stats = 0;
8699 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8700 unsigned int num_funcs = 0;
8703 queue_Remove(rpc_stat);
8704 num_funcs = rpc_stat->stats[0].func_total;
8706 sizeof(rx_interface_stat_t) +
8707 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8709 rxi_Free(rpc_stat, space);
8710 rxi_rpc_process_stat_cnt -= num_funcs;
8712 MUTEX_EXIT(&rx_rpc_stats);
8716 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8726 rx_disablePeerRPCStats(void)
8728 struct rx_peer **peer_ptr, **peer_end;
8732 * Turn off peer statistics and if process stats is also off, turn
8736 rxi_monitor_peerStats = 0;
8737 if (rxi_monitor_processStats == 0) {
8738 rx_enable_stats = 0;
8741 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8742 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8744 struct rx_peer *peer, *next, *prev;
8746 MUTEX_ENTER(&rx_peerHashTable_lock);
8747 MUTEX_ENTER(&rx_rpc_stats);
8748 for (prev = peer = *peer_ptr; peer; peer = next) {
8750 code = MUTEX_TRYENTER(&peer->peer_lock);
8752 rx_interface_stat_p rpc_stat, nrpc_stat;
8755 if (prev == *peer_ptr) {
8766 MUTEX_EXIT(&rx_peerHashTable_lock);
8769 (&peer->rpcStats, rpc_stat, nrpc_stat,
8770 rx_interface_stat)) {
8771 unsigned int num_funcs = 0;
8774 queue_Remove(&rpc_stat->queue_header);
8775 queue_Remove(&rpc_stat->all_peers);
8776 num_funcs = rpc_stat->stats[0].func_total;
8778 sizeof(rx_interface_stat_t) +
8779 rpc_stat->stats[0].func_total *
8780 sizeof(rx_function_entry_v1_t);
8782 rxi_Free(rpc_stat, space);
8783 rxi_rpc_peer_stat_cnt -= num_funcs;
8785 MUTEX_EXIT(&peer->peer_lock);
8787 MUTEX_ENTER(&rx_peerHashTable_lock);
8797 MUTEX_EXIT(&rx_rpc_stats);
8798 MUTEX_EXIT(&rx_peerHashTable_lock);
8803 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8808 * IN clearFlag - flag indicating which stats to clear
8816 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8818 rx_interface_stat_p rpc_stat, nrpc_stat;
8820 MUTEX_ENTER(&rx_rpc_stats);
8822 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8823 unsigned int num_funcs = 0, i;
8824 num_funcs = rpc_stat->stats[0].func_total;
8825 for (i = 0; i < num_funcs; i++) {
8826 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8827 hzero(rpc_stat->stats[i].invocations);
8829 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8830 hzero(rpc_stat->stats[i].bytes_sent);
8832 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8833 hzero(rpc_stat->stats[i].bytes_rcvd);
8835 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8836 rpc_stat->stats[i].queue_time_sum.sec = 0;
8837 rpc_stat->stats[i].queue_time_sum.usec = 0;
8839 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8840 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8841 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8843 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8844 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8845 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8847 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8848 rpc_stat->stats[i].queue_time_max.sec = 0;
8849 rpc_stat->stats[i].queue_time_max.usec = 0;
8851 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8852 rpc_stat->stats[i].execution_time_sum.sec = 0;
8853 rpc_stat->stats[i].execution_time_sum.usec = 0;
8855 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8856 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8857 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8859 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8860 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8861 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8863 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8864 rpc_stat->stats[i].execution_time_max.sec = 0;
8865 rpc_stat->stats[i].execution_time_max.usec = 0;
8870 MUTEX_EXIT(&rx_rpc_stats);
8874 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8879 * IN clearFlag - flag indicating which stats to clear
8887 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8889 rx_interface_stat_p rpc_stat, nrpc_stat;
8891 MUTEX_ENTER(&rx_rpc_stats);
8893 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8894 unsigned int num_funcs = 0, i;
8897 * We have to fix the offset of rpc_stat since we are
8898 * keeping this structure on two rx_queues. The rx_queue
8899 * package assumes that the rx_queue member is the first
8900 * member of the structure. That is, rx_queue assumes that
8901 * any one item is only on one queue at a time. We are
8902 * breaking that assumption and so we have to do a little
8903 * math to fix our pointers.
8906 fix_offset = (char *)rpc_stat;
8907 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8908 rpc_stat = (rx_interface_stat_p) fix_offset;
8910 num_funcs = rpc_stat->stats[0].func_total;
8911 for (i = 0; i < num_funcs; i++) {
8912 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8913 hzero(rpc_stat->stats[i].invocations);
8915 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8916 hzero(rpc_stat->stats[i].bytes_sent);
8918 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8919 hzero(rpc_stat->stats[i].bytes_rcvd);
8921 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8922 rpc_stat->stats[i].queue_time_sum.sec = 0;
8923 rpc_stat->stats[i].queue_time_sum.usec = 0;
8925 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8926 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8927 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8929 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8930 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8931 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8933 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8934 rpc_stat->stats[i].queue_time_max.sec = 0;
8935 rpc_stat->stats[i].queue_time_max.usec = 0;
8937 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8938 rpc_stat->stats[i].execution_time_sum.sec = 0;
8939 rpc_stat->stats[i].execution_time_sum.usec = 0;
8941 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8942 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8943 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8945 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8946 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8947 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8949 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8950 rpc_stat->stats[i].execution_time_max.sec = 0;
8951 rpc_stat->stats[i].execution_time_max.usec = 0;
8956 MUTEX_EXIT(&rx_rpc_stats);
8960 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8961 * is authorized to enable/disable/clear RX statistics.
8963 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8966 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8968 rxi_rxstat_userok = proc;
8972 rx_RxStatUserOk(struct rx_call *call)
8974 if (!rxi_rxstat_userok)
8976 return rxi_rxstat_userok(call);
8981 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8982 * function in the MSVC runtime DLL (msvcrt.dll).
8984 * Note: the system serializes calls to this function.
8987 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8988 DWORD reason, /* reason function is being called */
8989 LPVOID reserved) /* reserved for future use */
8992 case DLL_PROCESS_ATTACH:
8993 /* library is being attached to a process */
8997 case DLL_PROCESS_DETACH:
9004 #endif /* AFS_NT40_ENV */
9007 int rx_DumpCalls(FILE *outputFile, char *cookie)
9009 #ifdef RXDEBUG_PACKET
9010 #ifdef KDUMP_RX_LOCK
9011 struct rx_call_rx_lock *c;
9018 #define RXDPRINTF sprintf
9019 #define RXDPRINTOUT output
9021 #define RXDPRINTF fprintf
9022 #define RXDPRINTOUT outputFile
9025 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9027 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9030 for (c = rx_allCallsp; c; c = c->allNextp) {
9031 u_short rqc, tqc, iovqc;
9032 struct rx_packet *p, *np;
9034 MUTEX_ENTER(&c->lock);
9035 queue_Count(&c->rq, p, np, rx_packet, rqc);
9036 queue_Count(&c->tq, p, np, rx_packet, tqc);
9037 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9039 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, "
9040 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9041 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9042 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9043 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9044 #ifdef RX_ENABLE_LOCKS
9047 #ifdef RX_REFCOUNT_CHECK
9048 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9049 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9052 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,
9053 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9054 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9055 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9056 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9057 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9058 #ifdef RX_ENABLE_LOCKS
9059 , (afs_uint32)c->refCount
9061 #ifdef RX_REFCOUNT_CHECK
9062 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9065 MUTEX_EXIT(&c->lock);
9068 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9071 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9073 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9075 #endif /* RXDEBUG_PACKET */