2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
14 #include "afs/param.h"
16 #include <afs/param.h>
21 #include "afs/sysincludes.h"
22 #include "afsincludes.h"
28 #include <net/net_globals.h>
29 #endif /* AFS_OSF_ENV */
30 #ifdef AFS_LINUX20_ENV
33 #include "netinet/in.h"
35 #include "inet/common.h"
37 #include "inet/ip_ire.h"
39 #include "afs/afs_args.h"
40 #include "afs/afs_osi.h"
41 #ifdef RX_KERNEL_TRACE
42 #include "rx_kcommon.h"
44 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
48 #undef RXDEBUG /* turn off debugging */
50 #if defined(AFS_SGI_ENV)
51 #include "sys/debug.h"
59 #endif /* AFS_OSF_ENV */
61 #include "afs/sysincludes.h"
62 #include "afsincludes.h"
65 #include "rx_kmutex.h"
66 #include "rx_kernel.h"
70 #include "rx_globals.h"
72 #include "rx_atomic.h"
73 #include "rx_internal.h"
75 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
76 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
77 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
79 extern afs_int32 afs_termState;
81 #include "sys/lockl.h"
82 #include "sys/lock_def.h"
83 #endif /* AFS_AIX41_ENV */
84 # include "afs/rxgen_consts.h"
86 # include <sys/types.h>
96 # include <afs/afsutil.h>
97 # include <WINNT\afsreg.h>
99 # include <sys/socket.h>
100 # include <sys/file.h>
102 # include <sys/stat.h>
103 # include <netinet/in.h>
104 # include <sys/time.h>
107 # include "rx_user.h"
108 # include "rx_clock.h"
109 # include "rx_queue.h"
110 # include "rx_atomic.h"
111 # include "rx_globals.h"
112 # include "rx_trace.h"
113 # include "rx_internal.h"
114 # include "rx_stats.h"
115 # include <afs/rxgen_consts.h>
119 #ifdef AFS_PTHREAD_ENV
121 int (*registerProgram) (pid_t, char *) = 0;
122 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
125 int (*registerProgram) (PROCESS, char *) = 0;
126 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
130 /* Local static routines */
131 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
132 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct clock *,
133 struct rx_peer *, struct clock *);
135 #ifdef RX_ENABLE_LOCKS
136 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
139 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
141 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
142 rx_atomic_t rxi_start_in_error;
144 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
147 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
148 * currently allocated within rx. This number is used to allocate the
149 * memory required to return the statistics when queried.
150 * Protected by the rx_rpc_stats mutex.
153 static unsigned int rxi_rpc_peer_stat_cnt;
156 * rxi_rpc_process_stat_cnt counts the total number of local process stat
157 * structures currently allocated within rx. The number is used to allocate
158 * the memory required to return the statistics when queried.
159 * Protected by the rx_rpc_stats mutex.
162 static unsigned int rxi_rpc_process_stat_cnt;
164 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
165 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
167 #if !defined(offsetof)
168 #include <stddef.h> /* for definition of offsetof() */
171 #ifdef RX_ENABLE_LOCKS
172 afs_kmutex_t rx_atomic_mutex;
175 #ifdef AFS_PTHREAD_ENV
179 * Use procedural initialization of mutexes/condition variables
183 extern afs_kmutex_t rx_quota_mutex;
184 extern afs_kmutex_t rx_pthread_mutex;
185 extern afs_kmutex_t rx_packets_mutex;
186 extern afs_kmutex_t rx_refcnt_mutex;
187 extern afs_kmutex_t des_init_mutex;
188 extern afs_kmutex_t des_random_mutex;
189 extern afs_kmutex_t rx_clock_mutex;
190 extern afs_kmutex_t rxi_connCacheMutex;
191 extern afs_kmutex_t rx_event_mutex;
192 extern afs_kmutex_t osi_malloc_mutex;
193 extern afs_kmutex_t event_handler_mutex;
194 extern afs_kmutex_t listener_mutex;
195 extern afs_kmutex_t rx_if_init_mutex;
196 extern afs_kmutex_t rx_if_mutex;
197 extern afs_kmutex_t rxkad_client_uid_mutex;
198 extern afs_kmutex_t rxkad_random_mutex;
200 extern afs_kcondvar_t rx_event_handler_cond;
201 extern afs_kcondvar_t rx_listener_cond;
203 static afs_kmutex_t epoch_mutex;
204 static afs_kmutex_t rx_init_mutex;
205 static afs_kmutex_t rx_debug_mutex;
206 static afs_kmutex_t rx_rpc_stats;
209 rxi_InitPthread(void)
211 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
216 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
217 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
220 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
222 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
224 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
226 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
228 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
229 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
230 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
231 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
233 assert(pthread_cond_init
234 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
235 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
237 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
238 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
240 rxkad_global_stats_init();
242 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
243 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
244 #ifdef RX_ENABLE_LOCKS
247 #endif /* RX_LOCKS_DB */
248 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
249 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
251 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
253 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
255 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
257 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
258 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
259 #endif /* RX_ENABLE_LOCKS */
262 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
263 #define INIT_PTHREAD_LOCKS \
264 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
266 * The rx_stats_mutex mutex protects the following global variables:
267 * rxi_lowConnRefCount
268 * rxi_lowPeerRefCount
277 * The rx_quota_mutex mutex protects the following global variables:
285 * The rx_freePktQ_lock protects the following global variables:
290 * The rx_packets_mutex mutex protects the following global variables:
298 * The rx_pthread_mutex mutex protects the following global variables:
299 * rxi_fcfs_thread_num
302 #define INIT_PTHREAD_LOCKS
306 /* Variables for handling the minProcs implementation. availProcs gives the
307 * number of threads available in the pool at this moment (not counting dudes
308 * executing right now). totalMin gives the total number of procs required
309 * for handling all minProcs requests. minDeficit is a dynamic variable
310 * tracking the # of procs required to satisfy all of the remaining minProcs
312 * For fine grain locking to work, the quota check and the reservation of
313 * a server thread has to come while rxi_availProcs and rxi_minDeficit
314 * are locked. To this end, the code has been modified under #ifdef
315 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
316 * same time. A new function, ReturnToServerPool() returns the allocation.
318 * A call can be on several queue's (but only one at a time). When
319 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
320 * that no one else is touching the queue. To this end, we store the address
321 * of the queue lock in the call structure (under the call lock) when we
322 * put the call on a queue, and we clear the call_queue_lock when the
323 * call is removed from a queue (once the call lock has been obtained).
324 * This allows rxi_ResetCall to safely synchronize with others wishing
325 * to manipulate the queue.
328 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
329 static afs_kmutex_t rx_rpc_stats;
330 void rxi_StartUnlocked(struct rxevent *event, void *call,
331 void *arg1, int istack);
334 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
335 ** pretty good that the next packet coming in is from the same connection
336 ** as the last packet, since we're send multiple packets in a transmit window.
338 struct rx_connection *rxLastConn = 0;
340 #ifdef RX_ENABLE_LOCKS
341 /* The locking hierarchy for rx fine grain locking is composed of these
344 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
345 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
346 * call->lock - locks call data fields.
347 * These are independent of each other:
348 * rx_freeCallQueue_lock
353 * serverQueueEntry->lock
354 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
356 * peer->lock - locks peer data fields.
357 * conn_data_lock - that more than one thread is not updating a conn data
358 * field at the same time.
369 * Do we need a lock to protect the peer field in the conn structure?
370 * conn->peer was previously a constant for all intents and so has no
371 * lock protecting this field. The multihomed client delta introduced
372 * a RX code change : change the peer field in the connection structure
373 * to that remote interface from which the last packet for this
374 * connection was sent out. This may become an issue if further changes
377 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
378 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
380 /* rxdb_fileID is used to identify the lock location, along with line#. */
381 static int rxdb_fileID = RXDB_FILE_RX;
382 #endif /* RX_LOCKS_DB */
383 #else /* RX_ENABLE_LOCKS */
384 #define SET_CALL_QUEUE_LOCK(C, L)
385 #define CLEAR_CALL_QUEUE_LOCK(C)
386 #endif /* RX_ENABLE_LOCKS */
387 struct rx_serverQueueEntry *rx_waitForPacket = 0;
388 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
390 /* ------------Exported Interfaces------------- */
392 /* This function allows rxkad to set the epoch to a suitably random number
393 * which rx_NewConnection will use in the future. The principle purpose is to
394 * get rxnull connections to use the same epoch as the rxkad connections do, at
395 * least once the first rxkad connection is established. This is important now
396 * that the host/port addresses aren't used in FindConnection: the uniqueness
397 * of epoch/cid matters and the start time won't do. */
399 #ifdef AFS_PTHREAD_ENV
401 * This mutex protects the following global variables:
405 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
406 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
410 #endif /* AFS_PTHREAD_ENV */
413 rx_SetEpoch(afs_uint32 epoch)
420 /* Initialize rx. A port number may be mentioned, in which case this
421 * becomes the default port number for any service installed later.
422 * If 0 is provided for the port number, a random port will be chosen
423 * by the kernel. Whether this will ever overlap anything in
424 * /etc/services is anybody's guess... Returns 0 on success, -1 on
429 int rxinit_status = 1;
430 #ifdef AFS_PTHREAD_ENV
432 * This mutex protects the following global variables:
436 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
437 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
440 #define UNLOCK_RX_INIT
444 rx_InitHost(u_int host, u_int port)
451 char *htable, *ptable;
458 if (rxinit_status == 0) {
459 tmp_status = rxinit_status;
461 return tmp_status; /* Already started; return previous error code. */
467 if (afs_winsockInit() < 0)
473 * Initialize anything necessary to provide a non-premptive threading
476 rxi_InitializeThreadSupport();
479 /* Allocate and initialize a socket for client and perhaps server
482 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
483 if (rx_socket == OSI_NULLSOCKET) {
487 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
490 #endif /* RX_LOCKS_DB */
491 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
492 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
493 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
494 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
495 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
496 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
497 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
498 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
499 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
501 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
503 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
505 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
507 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
508 #if defined(AFS_HPUX110_ENV)
510 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
511 #endif /* AFS_HPUX110_ENV */
512 #endif /* RX_ENABLE_LOCKS && KERNEL */
515 rx_connDeadTime = 12;
516 rx_tranquil = 0; /* reset flag */
517 rxi_ResetStatistics();
519 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
520 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
521 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
522 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
523 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
524 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
526 /* Malloc up a bunch of packets & buffers */
528 queue_Init(&rx_freePacketQueue);
529 rxi_NeedMorePackets = FALSE;
530 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
532 /* enforce a minimum number of allocated packets */
533 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
534 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
536 /* allocate the initial free packet pool */
537 #ifdef RX_ENABLE_TSFPQ
538 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
539 #else /* RX_ENABLE_TSFPQ */
540 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
541 #endif /* RX_ENABLE_TSFPQ */
548 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
549 tv.tv_sec = clock_now.sec;
550 tv.tv_usec = clock_now.usec;
551 srand((unsigned int)tv.tv_usec);
558 #if defined(KERNEL) && !defined(UKERNEL)
559 /* Really, this should never happen in a real kernel */
562 struct sockaddr_in addr;
564 int addrlen = sizeof(addr);
566 socklen_t addrlen = sizeof(addr);
568 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
572 rx_port = addr.sin_port;
575 rx_stats.minRtt.sec = 9999999;
577 rx_SetEpoch(tv.tv_sec | 0x80000000);
579 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
580 * will provide a randomer value. */
582 MUTEX_ENTER(&rx_quota_mutex);
583 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
584 MUTEX_EXIT(&rx_quota_mutex);
585 /* *Slightly* random start time for the cid. This is just to help
586 * out with the hashing function at the peer */
587 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
588 rx_connHashTable = (struct rx_connection **)htable;
589 rx_peerHashTable = (struct rx_peer **)ptable;
591 rx_lastAckDelay.sec = 0;
592 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
593 rx_hardAckDelay.sec = 0;
594 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
595 rx_softAckDelay.sec = 0;
596 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
598 rxevent_Init(20, rxi_ReScheduleEvents);
600 /* Initialize various global queues */
601 queue_Init(&rx_idleServerQueue);
602 queue_Init(&rx_incomingCallQueue);
603 queue_Init(&rx_freeCallQueue);
605 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
606 /* Initialize our list of usable IP addresses. */
610 /* Start listener process (exact function is dependent on the
611 * implementation environment--kernel or user space) */
615 tmp_status = rxinit_status = 0;
623 return rx_InitHost(htonl(INADDR_ANY), port);
626 /* called with unincremented nRequestsRunning to see if it is OK to start
627 * a new thread in this service. Could be "no" for two reasons: over the
628 * max quota, or would prevent others from reaching their min quota.
630 #ifdef RX_ENABLE_LOCKS
631 /* This verion of QuotaOK reserves quota if it's ok while the
632 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
635 QuotaOK(struct rx_service *aservice)
637 /* check if over max quota */
638 if (aservice->nRequestsRunning >= aservice->maxProcs) {
642 /* under min quota, we're OK */
643 /* otherwise, can use only if there are enough to allow everyone
644 * to go to their min quota after this guy starts.
647 MUTEX_ENTER(&rx_quota_mutex);
648 if ((aservice->nRequestsRunning < aservice->minProcs)
649 || (rxi_availProcs > rxi_minDeficit)) {
650 aservice->nRequestsRunning++;
651 /* just started call in minProcs pool, need fewer to maintain
653 if (aservice->nRequestsRunning <= aservice->minProcs)
656 MUTEX_EXIT(&rx_quota_mutex);
659 MUTEX_EXIT(&rx_quota_mutex);
665 ReturnToServerPool(struct rx_service *aservice)
667 aservice->nRequestsRunning--;
668 MUTEX_ENTER(&rx_quota_mutex);
669 if (aservice->nRequestsRunning < aservice->minProcs)
672 MUTEX_EXIT(&rx_quota_mutex);
675 #else /* RX_ENABLE_LOCKS */
677 QuotaOK(struct rx_service *aservice)
680 /* under min quota, we're OK */
681 if (aservice->nRequestsRunning < aservice->minProcs)
684 /* check if over max quota */
685 if (aservice->nRequestsRunning >= aservice->maxProcs)
688 /* otherwise, can use only if there are enough to allow everyone
689 * to go to their min quota after this guy starts.
691 MUTEX_ENTER(&rx_quota_mutex);
692 if (rxi_availProcs > rxi_minDeficit)
694 MUTEX_EXIT(&rx_quota_mutex);
697 #endif /* RX_ENABLE_LOCKS */
700 /* Called by rx_StartServer to start up lwp's to service calls.
701 NExistingProcs gives the number of procs already existing, and which
702 therefore needn't be created. */
704 rxi_StartServerProcs(int nExistingProcs)
706 struct rx_service *service;
711 /* For each service, reserve N processes, where N is the "minimum"
712 * number of processes that MUST be able to execute a request in parallel,
713 * at any time, for that process. Also compute the maximum difference
714 * between any service's maximum number of processes that can run
715 * (i.e. the maximum number that ever will be run, and a guarantee
716 * that this number will run if other services aren't running), and its
717 * minimum number. The result is the extra number of processes that
718 * we need in order to provide the latter guarantee */
719 for (i = 0; i < RX_MAX_SERVICES; i++) {
721 service = rx_services[i];
722 if (service == (struct rx_service *)0)
724 nProcs += service->minProcs;
725 diff = service->maxProcs - service->minProcs;
729 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
730 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
731 for (i = 0; i < nProcs; i++) {
732 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
738 /* This routine is only required on Windows */
740 rx_StartClientThread(void)
742 #ifdef AFS_PTHREAD_ENV
744 pid = pthread_self();
745 #endif /* AFS_PTHREAD_ENV */
747 #endif /* AFS_NT40_ENV */
749 /* This routine must be called if any services are exported. If the
750 * donateMe flag is set, the calling process is donated to the server
753 rx_StartServer(int donateMe)
755 struct rx_service *service;
761 /* Start server processes, if necessary (exact function is dependent
762 * on the implementation environment--kernel or user space). DonateMe
763 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
764 * case, one less new proc will be created rx_StartServerProcs.
766 rxi_StartServerProcs(donateMe);
768 /* count up the # of threads in minProcs, and add set the min deficit to
769 * be that value, too.
771 for (i = 0; i < RX_MAX_SERVICES; i++) {
772 service = rx_services[i];
773 if (service == (struct rx_service *)0)
775 MUTEX_ENTER(&rx_quota_mutex);
776 rxi_totalMin += service->minProcs;
777 /* below works even if a thread is running, since minDeficit would
778 * still have been decremented and later re-incremented.
780 rxi_minDeficit += service->minProcs;
781 MUTEX_EXIT(&rx_quota_mutex);
784 /* Turn on reaping of idle server connections */
785 rxi_ReapConnections(NULL, NULL, NULL);
794 #ifdef AFS_PTHREAD_ENV
796 pid = afs_pointer_to_int(pthread_self());
797 #else /* AFS_PTHREAD_ENV */
799 LWP_CurrentProcess(&pid);
800 #endif /* AFS_PTHREAD_ENV */
802 sprintf(name, "srv_%d", ++nProcs);
804 (*registerProgram) (pid, name);
806 #endif /* AFS_NT40_ENV */
807 rx_ServerProc(NULL); /* Never returns */
809 #ifdef RX_ENABLE_TSFPQ
810 /* no use leaving packets around in this thread's local queue if
811 * it isn't getting donated to the server thread pool.
813 rxi_FlushLocalPacketsTSFPQ();
814 #endif /* RX_ENABLE_TSFPQ */
818 /* Create a new client connection to the specified service, using the
819 * specified security object to implement the security model for this
821 struct rx_connection *
822 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
823 struct rx_securityClass *securityObject,
824 int serviceSecurityIndex)
828 struct rx_connection *conn;
833 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
834 "serviceSecurityIndex %d)\n",
835 ntohl(shost), ntohs(sport), sservice, securityObject,
836 serviceSecurityIndex));
838 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
839 * the case of kmem_alloc? */
840 conn = rxi_AllocConnection();
841 #ifdef RX_ENABLE_LOCKS
842 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
843 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
844 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
847 MUTEX_ENTER(&rx_connHashTable_lock);
848 cid = (rx_nextCid += RX_MAXCALLS);
849 conn->type = RX_CLIENT_CONNECTION;
851 conn->epoch = rx_epoch;
852 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
853 conn->serviceId = sservice;
854 conn->securityObject = securityObject;
855 conn->securityData = (void *) 0;
856 conn->securityIndex = serviceSecurityIndex;
857 rx_SetConnDeadTime(conn, rx_connDeadTime);
858 rx_SetConnSecondsUntilNatPing(conn, 0);
859 conn->ackRate = RX_FAST_ACK_RATE;
861 conn->specific = NULL;
862 conn->challengeEvent = NULL;
863 conn->delayedAbortEvent = NULL;
864 conn->abortCount = 0;
866 for (i = 0; i < RX_MAXCALLS; i++) {
867 conn->twind[i] = rx_initSendWindow;
868 conn->rwind[i] = rx_initReceiveWindow;
871 RXS_NewConnection(securityObject, conn);
873 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
875 conn->refCount++; /* no lock required since only this thread knows... */
876 conn->next = rx_connHashTable[hashindex];
877 rx_connHashTable[hashindex] = conn;
879 rx_atomic_inc(&rx_stats.nClientConns);
880 MUTEX_EXIT(&rx_connHashTable_lock);
886 * Ensure a connection's timeout values are valid.
888 * @param[in] conn The connection to check
890 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
891 * unless idleDeadTime and/or hardDeadTime are not set
895 rxi_CheckConnTimeouts(struct rx_connection *conn)
897 /* a connection's timeouts must have the relationship
898 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
899 * total loss of network to a peer may cause an idle timeout instead of a
900 * dead timeout, simply because the idle timeout gets hit first. Also set
901 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
902 /* this logic is slightly complicated by the fact that
903 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
905 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
906 if (conn->idleDeadTime) {
907 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
909 if (conn->hardDeadTime) {
910 if (conn->idleDeadTime) {
911 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
913 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
919 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
921 /* The idea is to set the dead time to a value that allows several
922 * keepalives to be dropped without timing out the connection. */
923 conn->secondsUntilDead = seconds;
924 rxi_CheckConnTimeouts(conn);
925 conn->secondsUntilPing = conn->secondsUntilDead / 6;
929 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
931 conn->hardDeadTime = seconds;
932 rxi_CheckConnTimeouts(conn);
936 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
938 conn->idleDeadTime = seconds;
939 rxi_CheckConnTimeouts(conn);
942 int rxi_lowPeerRefCount = 0;
943 int rxi_lowConnRefCount = 0;
946 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
947 * NOTE: must not be called with rx_connHashTable_lock held.
950 rxi_CleanupConnection(struct rx_connection *conn)
952 /* Notify the service exporter, if requested, that this connection
953 * is being destroyed */
954 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
955 (*conn->service->destroyConnProc) (conn);
957 /* Notify the security module that this connection is being destroyed */
958 RXS_DestroyConnection(conn->securityObject, conn);
960 /* If this is the last connection using the rx_peer struct, set its
961 * idle time to now. rxi_ReapConnections will reap it if it's still
962 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
964 MUTEX_ENTER(&rx_peerHashTable_lock);
965 if (conn->peer->refCount < 2) {
966 conn->peer->idleWhen = clock_Sec();
967 if (conn->peer->refCount < 1) {
968 conn->peer->refCount = 1;
969 if (rx_stats_active) {
970 MUTEX_ENTER(&rx_stats_mutex);
971 rxi_lowPeerRefCount++;
972 MUTEX_EXIT(&rx_stats_mutex);
976 conn->peer->refCount--;
977 MUTEX_EXIT(&rx_peerHashTable_lock);
981 if (conn->type == RX_SERVER_CONNECTION)
982 rx_atomic_dec(&rx_stats.nServerConns);
984 rx_atomic_dec(&rx_stats.nClientConns);
987 if (conn->specific) {
989 for (i = 0; i < conn->nSpecific; i++) {
990 if (conn->specific[i] && rxi_keyCreate_destructor[i])
991 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
992 conn->specific[i] = NULL;
994 free(conn->specific);
996 conn->specific = NULL;
1000 MUTEX_DESTROY(&conn->conn_call_lock);
1001 MUTEX_DESTROY(&conn->conn_data_lock);
1002 CV_DESTROY(&conn->conn_call_cv);
1004 rxi_FreeConnection(conn);
1007 /* Destroy the specified connection */
1009 rxi_DestroyConnection(struct rx_connection *conn)
1011 MUTEX_ENTER(&rx_connHashTable_lock);
1012 rxi_DestroyConnectionNoLock(conn);
1013 /* conn should be at the head of the cleanup list */
1014 if (conn == rx_connCleanup_list) {
1015 rx_connCleanup_list = rx_connCleanup_list->next;
1016 MUTEX_EXIT(&rx_connHashTable_lock);
1017 rxi_CleanupConnection(conn);
1019 #ifdef RX_ENABLE_LOCKS
1021 MUTEX_EXIT(&rx_connHashTable_lock);
1023 #endif /* RX_ENABLE_LOCKS */
1027 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1029 struct rx_connection **conn_ptr;
1031 struct rx_packet *packet;
1038 MUTEX_ENTER(&conn->conn_data_lock);
1039 MUTEX_ENTER(&rx_refcnt_mutex);
1040 if (conn->refCount > 0)
1043 if (rx_stats_active) {
1044 MUTEX_ENTER(&rx_stats_mutex);
1045 rxi_lowConnRefCount++;
1046 MUTEX_EXIT(&rx_stats_mutex);
1050 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1051 /* Busy; wait till the last guy before proceeding */
1052 MUTEX_EXIT(&rx_refcnt_mutex);
1053 MUTEX_EXIT(&conn->conn_data_lock);
1058 /* If the client previously called rx_NewCall, but it is still
1059 * waiting, treat this as a running call, and wait to destroy the
1060 * connection later when the call completes. */
1061 if ((conn->type == RX_CLIENT_CONNECTION)
1062 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1063 conn->flags |= RX_CONN_DESTROY_ME;
1064 MUTEX_EXIT(&conn->conn_data_lock);
1068 MUTEX_EXIT(&rx_refcnt_mutex);
1069 MUTEX_EXIT(&conn->conn_data_lock);
1071 /* Check for extant references to this connection */
1072 for (i = 0; i < RX_MAXCALLS; i++) {
1073 struct rx_call *call = conn->call[i];
1076 if (conn->type == RX_CLIENT_CONNECTION) {
1077 MUTEX_ENTER(&call->lock);
1078 if (call->delayedAckEvent) {
1079 /* Push the final acknowledgment out now--there
1080 * won't be a subsequent call to acknowledge the
1081 * last reply packets */
1082 rxevent_Cancel(call->delayedAckEvent, call,
1083 RX_CALL_REFCOUNT_DELAY);
1084 if (call->state == RX_STATE_PRECALL
1085 || call->state == RX_STATE_ACTIVE) {
1086 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1088 rxi_AckAll(NULL, call, 0);
1091 MUTEX_EXIT(&call->lock);
1095 #ifdef RX_ENABLE_LOCKS
1097 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1098 MUTEX_EXIT(&conn->conn_data_lock);
1100 /* Someone is accessing a packet right now. */
1104 #endif /* RX_ENABLE_LOCKS */
1107 /* Don't destroy the connection if there are any call
1108 * structures still in use */
1109 MUTEX_ENTER(&conn->conn_data_lock);
1110 conn->flags |= RX_CONN_DESTROY_ME;
1111 MUTEX_EXIT(&conn->conn_data_lock);
1116 if (conn->natKeepAliveEvent) {
1117 rxi_NatKeepAliveOff(conn);
1120 if (conn->delayedAbortEvent) {
1121 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1122 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1124 MUTEX_ENTER(&conn->conn_data_lock);
1125 rxi_SendConnectionAbort(conn, packet, 0, 1);
1126 MUTEX_EXIT(&conn->conn_data_lock);
1127 rxi_FreePacket(packet);
1131 /* Remove from connection hash table before proceeding */
1133 &rx_connHashTable[CONN_HASH
1134 (peer->host, peer->port, conn->cid, conn->epoch,
1136 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1137 if (*conn_ptr == conn) {
1138 *conn_ptr = conn->next;
1142 /* if the conn that we are destroying was the last connection, then we
1143 * clear rxLastConn as well */
1144 if (rxLastConn == conn)
1147 /* Make sure the connection is completely reset before deleting it. */
1148 /* get rid of pending events that could zap us later */
1149 if (conn->challengeEvent)
1150 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1151 if (conn->checkReachEvent)
1152 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1153 if (conn->natKeepAliveEvent)
1154 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1156 /* Add the connection to the list of destroyed connections that
1157 * need to be cleaned up. This is necessary to avoid deadlocks
1158 * in the routines we call to inform others that this connection is
1159 * being destroyed. */
1160 conn->next = rx_connCleanup_list;
1161 rx_connCleanup_list = conn;
1164 /* Externally available version */
1166 rx_DestroyConnection(struct rx_connection *conn)
1171 rxi_DestroyConnection(conn);
1176 rx_GetConnection(struct rx_connection *conn)
1181 MUTEX_ENTER(&rx_refcnt_mutex);
1183 MUTEX_EXIT(&rx_refcnt_mutex);
1187 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1188 /* Wait for the transmit queue to no longer be busy.
1189 * requires the call->lock to be held */
1190 static void rxi_WaitforTQBusy(struct rx_call *call) {
1191 while (call->flags & RX_CALL_TQ_BUSY) {
1192 call->flags |= RX_CALL_TQ_WAIT;
1194 #ifdef RX_ENABLE_LOCKS
1195 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1196 CV_WAIT(&call->cv_tq, &call->lock);
1197 #else /* RX_ENABLE_LOCKS */
1198 osi_rxSleep(&call->tq);
1199 #endif /* RX_ENABLE_LOCKS */
1201 if (call->tqWaiters == 0) {
1202 call->flags &= ~RX_CALL_TQ_WAIT;
1208 /* Start a new rx remote procedure call, on the specified connection.
1209 * If wait is set to 1, wait for a free call channel; otherwise return
1210 * 0. Maxtime gives the maximum number of seconds this call may take,
1211 * after rx_NewCall returns. After this time interval, a call to any
1212 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1213 * For fine grain locking, we hold the conn_call_lock in order to
1214 * to ensure that we don't get signalle after we found a call in an active
1215 * state and before we go to sleep.
1218 rx_NewCall(struct rx_connection *conn)
1221 struct rx_call *call;
1222 struct clock queueTime;
1226 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1229 clock_GetTime(&queueTime);
1231 * Check if there are others waiting for a new call.
1232 * If so, let them go first to avoid starving them.
1233 * This is a fairly simple scheme, and might not be
1234 * a complete solution for large numbers of waiters.
1236 * makeCallWaiters keeps track of the number of
1237 * threads waiting to make calls and the
1238 * RX_CONN_MAKECALL_WAITING flag bit is used to
1239 * indicate that there are indeed calls waiting.
1240 * The flag is set when the waiter is incremented.
1241 * It is only cleared when makeCallWaiters is 0.
1242 * This prevents us from accidently destroying the
1243 * connection while it is potentially about to be used.
1245 MUTEX_ENTER(&conn->conn_call_lock);
1246 MUTEX_ENTER(&conn->conn_data_lock);
1247 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1248 conn->flags |= RX_CONN_MAKECALL_WAITING;
1249 conn->makeCallWaiters++;
1250 MUTEX_EXIT(&conn->conn_data_lock);
1252 #ifdef RX_ENABLE_LOCKS
1253 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1257 MUTEX_ENTER(&conn->conn_data_lock);
1258 conn->makeCallWaiters--;
1259 if (conn->makeCallWaiters == 0)
1260 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1263 /* We are now the active thread in rx_NewCall */
1264 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1265 MUTEX_EXIT(&conn->conn_data_lock);
1270 for (i = 0; i < RX_MAXCALLS; i++) {
1271 call = conn->call[i];
1273 if (call->state == RX_STATE_DALLY) {
1274 MUTEX_ENTER(&call->lock);
1275 if (call->state == RX_STATE_DALLY) {
1277 * We are setting the state to RX_STATE_RESET to
1278 * ensure that no one else will attempt to use this
1279 * call once we drop the conn->conn_call_lock and
1280 * call->lock. We must drop the conn->conn_call_lock
1281 * before calling rxi_ResetCall because the process
1282 * of clearing the transmit queue can block for an
1283 * extended period of time. If we block while holding
1284 * the conn->conn_call_lock, then all rx_EndCall
1285 * processing will block as well. This has a detrimental
1286 * effect on overall system performance.
1288 call->state = RX_STATE_RESET;
1289 MUTEX_EXIT(&conn->conn_call_lock);
1290 MUTEX_ENTER(&rx_refcnt_mutex);
1291 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1292 MUTEX_EXIT(&rx_refcnt_mutex);
1293 rxi_ResetCall(call, 0);
1294 (*call->callNumber)++;
1295 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1299 * If we failed to be able to safely obtain the
1300 * conn->conn_call_lock we will have to drop the
1301 * call->lock to avoid a deadlock. When the call->lock
1302 * is released the state of the call can change. If it
1303 * is no longer RX_STATE_RESET then some other thread is
1306 MUTEX_EXIT(&call->lock);
1307 MUTEX_ENTER(&conn->conn_call_lock);
1308 MUTEX_ENTER(&call->lock);
1310 if (call->state == RX_STATE_RESET)
1314 * If we get here it means that after dropping
1315 * the conn->conn_call_lock and call->lock that
1316 * the call is no longer ours. If we can't find
1317 * a free call in the remaining slots we should
1318 * not go immediately to RX_CONN_MAKECALL_WAITING
1319 * because by dropping the conn->conn_call_lock
1320 * we have given up synchronization with rx_EndCall.
1321 * Instead, cycle through one more time to see if
1322 * we can find a call that can call our own.
1324 MUTEX_ENTER(&rx_refcnt_mutex);
1325 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1326 MUTEX_EXIT(&rx_refcnt_mutex);
1329 MUTEX_EXIT(&call->lock);
1332 /* rxi_NewCall returns with mutex locked */
1333 call = rxi_NewCall(conn, i);
1334 MUTEX_ENTER(&rx_refcnt_mutex);
1335 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1336 MUTEX_EXIT(&rx_refcnt_mutex);
1340 if (i < RX_MAXCALLS) {
1346 MUTEX_ENTER(&conn->conn_data_lock);
1347 conn->flags |= RX_CONN_MAKECALL_WAITING;
1348 conn->makeCallWaiters++;
1349 MUTEX_EXIT(&conn->conn_data_lock);
1351 #ifdef RX_ENABLE_LOCKS
1352 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1356 MUTEX_ENTER(&conn->conn_data_lock);
1357 conn->makeCallWaiters--;
1358 if (conn->makeCallWaiters == 0)
1359 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1360 MUTEX_EXIT(&conn->conn_data_lock);
1362 /* Client is initially in send mode */
1363 call->state = RX_STATE_ACTIVE;
1364 call->error = conn->error;
1366 call->mode = RX_MODE_ERROR;
1368 call->mode = RX_MODE_SENDING;
1370 /* remember start time for call in case we have hard dead time limit */
1371 call->queueTime = queueTime;
1372 clock_GetTime(&call->startTime);
1373 hzero(call->bytesSent);
1374 hzero(call->bytesRcvd);
1376 /* Turn on busy protocol. */
1377 rxi_KeepAliveOn(call);
1379 /* Attempt MTU discovery */
1380 rxi_GrowMTUOn(call);
1383 * We are no longer the active thread in rx_NewCall
1385 MUTEX_ENTER(&conn->conn_data_lock);
1386 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1387 MUTEX_EXIT(&conn->conn_data_lock);
1390 * Wake up anyone else who might be giving us a chance to
1391 * run (see code above that avoids resource starvation).
1393 #ifdef RX_ENABLE_LOCKS
1394 CV_BROADCAST(&conn->conn_call_cv);
1398 MUTEX_EXIT(&conn->conn_call_lock);
1400 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1401 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1402 osi_Panic("rx_NewCall call about to be used without an empty tq");
1404 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1406 MUTEX_EXIT(&call->lock);
1409 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1414 rxi_HasActiveCalls(struct rx_connection *aconn)
1417 struct rx_call *tcall;
1421 for (i = 0; i < RX_MAXCALLS; i++) {
1422 if ((tcall = aconn->call[i])) {
1423 if ((tcall->state == RX_STATE_ACTIVE)
1424 || (tcall->state == RX_STATE_PRECALL)) {
1435 rxi_GetCallNumberVector(struct rx_connection *aconn,
1436 afs_int32 * aint32s)
1439 struct rx_call *tcall;
1443 for (i = 0; i < RX_MAXCALLS; i++) {
1444 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1445 aint32s[i] = aconn->callNumber[i] + 1;
1447 aint32s[i] = aconn->callNumber[i];
1454 rxi_SetCallNumberVector(struct rx_connection *aconn,
1455 afs_int32 * aint32s)
1458 struct rx_call *tcall;
1462 for (i = 0; i < RX_MAXCALLS; i++) {
1463 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1464 aconn->callNumber[i] = aint32s[i] - 1;
1466 aconn->callNumber[i] = aint32s[i];
1472 /* Advertise a new service. A service is named locally by a UDP port
1473 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1476 char *serviceName; Name for identification purposes (e.g. the
1477 service name might be used for probing for
1480 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1481 char *serviceName, struct rx_securityClass **securityObjects,
1482 int nSecurityObjects,
1483 afs_int32(*serviceProc) (struct rx_call * acall))
1485 osi_socket socket = OSI_NULLSOCKET;
1486 struct rx_service *tservice;
1492 if (serviceId == 0) {
1494 "rx_NewService: service id for service %s is not non-zero.\n",
1501 "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",
1509 tservice = rxi_AllocService();
1512 #ifdef RX_ENABLE_LOCKS
1513 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1516 for (i = 0; i < RX_MAX_SERVICES; i++) {
1517 struct rx_service *service = rx_services[i];
1519 if (port == service->servicePort && host == service->serviceHost) {
1520 if (service->serviceId == serviceId) {
1521 /* The identical service has already been
1522 * installed; if the caller was intending to
1523 * change the security classes used by this
1524 * service, he/she loses. */
1526 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1527 serviceName, serviceId, service->serviceName);
1529 rxi_FreeService(tservice);
1532 /* Different service, same port: re-use the socket
1533 * which is bound to the same port */
1534 socket = service->socket;
1537 if (socket == OSI_NULLSOCKET) {
1538 /* If we don't already have a socket (from another
1539 * service on same port) get a new one */
1540 socket = rxi_GetHostUDPSocket(host, port);
1541 if (socket == OSI_NULLSOCKET) {
1543 rxi_FreeService(tservice);
1548 service->socket = socket;
1549 service->serviceHost = host;
1550 service->servicePort = port;
1551 service->serviceId = serviceId;
1552 service->serviceName = serviceName;
1553 service->nSecurityObjects = nSecurityObjects;
1554 service->securityObjects = securityObjects;
1555 service->minProcs = 0;
1556 service->maxProcs = 1;
1557 service->idleDeadTime = 60;
1558 service->idleDeadErr = 0;
1559 service->connDeadTime = rx_connDeadTime;
1560 service->executeRequestProc = serviceProc;
1561 service->checkReach = 0;
1562 service->nSpecific = 0;
1563 service->specific = NULL;
1564 rx_services[i] = service; /* not visible until now */
1570 rxi_FreeService(tservice);
1571 (osi_Msg "rx_NewService: cannot support > %d services\n",
1576 /* Set configuration options for all of a service's security objects */
1579 rx_SetSecurityConfiguration(struct rx_service *service,
1580 rx_securityConfigVariables type,
1584 for (i = 0; i<service->nSecurityObjects; i++) {
1585 if (service->securityObjects[i]) {
1586 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1594 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1595 struct rx_securityClass **securityObjects, int nSecurityObjects,
1596 afs_int32(*serviceProc) (struct rx_call * acall))
1598 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1601 /* Generic request processing loop. This routine should be called
1602 * by the implementation dependent rx_ServerProc. If socketp is
1603 * non-null, it will be set to the file descriptor that this thread
1604 * is now listening on. If socketp is null, this routine will never
1607 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1609 struct rx_call *call;
1611 struct rx_service *tservice = NULL;
1618 call = rx_GetCall(threadID, tservice, socketp);
1619 if (socketp && *socketp != OSI_NULLSOCKET) {
1620 /* We are now a listener thread */
1625 /* if server is restarting( typically smooth shutdown) then do not
1626 * allow any new calls.
1629 if (rx_tranquil && (call != NULL)) {
1633 MUTEX_ENTER(&call->lock);
1635 rxi_CallError(call, RX_RESTARTING);
1636 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1638 MUTEX_EXIT(&call->lock);
1642 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1643 #ifdef RX_ENABLE_LOCKS
1645 #endif /* RX_ENABLE_LOCKS */
1646 afs_termState = AFSOP_STOP_AFS;
1647 afs_osi_Wakeup(&afs_termState);
1648 #ifdef RX_ENABLE_LOCKS
1650 #endif /* RX_ENABLE_LOCKS */
1655 tservice = call->conn->service;
1657 if (tservice->beforeProc)
1658 (*tservice->beforeProc) (call);
1660 code = tservice->executeRequestProc(call);
1662 if (tservice->afterProc)
1663 (*tservice->afterProc) (call, code);
1665 rx_EndCall(call, code);
1666 if (rx_stats_active) {
1667 MUTEX_ENTER(&rx_stats_mutex);
1669 MUTEX_EXIT(&rx_stats_mutex);
1676 rx_WakeupServerProcs(void)
1678 struct rx_serverQueueEntry *np, *tqp;
1682 MUTEX_ENTER(&rx_serverPool_lock);
1684 #ifdef RX_ENABLE_LOCKS
1685 if (rx_waitForPacket)
1686 CV_BROADCAST(&rx_waitForPacket->cv);
1687 #else /* RX_ENABLE_LOCKS */
1688 if (rx_waitForPacket)
1689 osi_rxWakeup(rx_waitForPacket);
1690 #endif /* RX_ENABLE_LOCKS */
1691 MUTEX_ENTER(&freeSQEList_lock);
1692 for (np = rx_FreeSQEList; np; np = tqp) {
1693 tqp = *(struct rx_serverQueueEntry **)np;
1694 #ifdef RX_ENABLE_LOCKS
1695 CV_BROADCAST(&np->cv);
1696 #else /* RX_ENABLE_LOCKS */
1698 #endif /* RX_ENABLE_LOCKS */
1700 MUTEX_EXIT(&freeSQEList_lock);
1701 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1702 #ifdef RX_ENABLE_LOCKS
1703 CV_BROADCAST(&np->cv);
1704 #else /* RX_ENABLE_LOCKS */
1706 #endif /* RX_ENABLE_LOCKS */
1708 MUTEX_EXIT(&rx_serverPool_lock);
1713 * One thing that seems to happen is that all the server threads get
1714 * tied up on some empty or slow call, and then a whole bunch of calls
1715 * arrive at once, using up the packet pool, so now there are more
1716 * empty calls. The most critical resources here are server threads
1717 * and the free packet pool. The "doreclaim" code seems to help in
1718 * general. I think that eventually we arrive in this state: there
1719 * are lots of pending calls which do have all their packets present,
1720 * so they won't be reclaimed, are multi-packet calls, so they won't
1721 * be scheduled until later, and thus are tying up most of the free
1722 * packet pool for a very long time.
1724 * 1. schedule multi-packet calls if all the packets are present.
1725 * Probably CPU-bound operation, useful to return packets to pool.
1726 * Do what if there is a full window, but the last packet isn't here?
1727 * 3. preserve one thread which *only* runs "best" calls, otherwise
1728 * it sleeps and waits for that type of call.
1729 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1730 * the current dataquota business is badly broken. The quota isn't adjusted
1731 * to reflect how many packets are presently queued for a running call.
1732 * So, when we schedule a queued call with a full window of packets queued
1733 * up for it, that *should* free up a window full of packets for other 2d-class
1734 * calls to be able to use from the packet pool. But it doesn't.
1736 * NB. Most of the time, this code doesn't run -- since idle server threads
1737 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1738 * as a new call arrives.
1740 /* Sleep until a call arrives. Returns a pointer to the call, ready
1741 * for an rx_Read. */
1742 #ifdef RX_ENABLE_LOCKS
1744 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1746 struct rx_serverQueueEntry *sq;
1747 struct rx_call *call = (struct rx_call *)0;
1748 struct rx_service *service = NULL;
1751 MUTEX_ENTER(&freeSQEList_lock);
1753 if ((sq = rx_FreeSQEList)) {
1754 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1755 MUTEX_EXIT(&freeSQEList_lock);
1756 } else { /* otherwise allocate a new one and return that */
1757 MUTEX_EXIT(&freeSQEList_lock);
1758 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1759 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1760 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1763 MUTEX_ENTER(&rx_serverPool_lock);
1764 if (cur_service != NULL) {
1765 ReturnToServerPool(cur_service);
1768 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1769 struct rx_call *tcall, *ncall, *choice2 = NULL;
1771 /* Scan for eligible incoming calls. A call is not eligible
1772 * if the maximum number of calls for its service type are
1773 * already executing */
1774 /* One thread will process calls FCFS (to prevent starvation),
1775 * while the other threads may run ahead looking for calls which
1776 * have all their input data available immediately. This helps
1777 * keep threads from blocking, waiting for data from the client. */
1778 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1779 service = tcall->conn->service;
1780 if (!QuotaOK(service)) {
1783 MUTEX_ENTER(&rx_pthread_mutex);
1784 if (tno == rxi_fcfs_thread_num
1785 || !tcall->queue_item_header.next) {
1786 MUTEX_EXIT(&rx_pthread_mutex);
1787 /* If we're the fcfs thread , then we'll just use
1788 * this call. If we haven't been able to find an optimal
1789 * choice, and we're at the end of the list, then use a
1790 * 2d choice if one has been identified. Otherwise... */
1791 call = (choice2 ? choice2 : tcall);
1792 service = call->conn->service;
1794 MUTEX_EXIT(&rx_pthread_mutex);
1795 if (!queue_IsEmpty(&tcall->rq)) {
1796 struct rx_packet *rp;
1797 rp = queue_First(&tcall->rq, rx_packet);
1798 if (rp->header.seq == 1) {
1800 || (rp->header.flags & RX_LAST_PACKET)) {
1802 } else if (rxi_2dchoice && !choice2
1803 && !(tcall->flags & RX_CALL_CLEARED)
1804 && (tcall->rprev > rxi_HardAckRate)) {
1814 ReturnToServerPool(service);
1821 MUTEX_EXIT(&rx_serverPool_lock);
1822 MUTEX_ENTER(&call->lock);
1824 if (call->flags & RX_CALL_WAIT_PROC) {
1825 call->flags &= ~RX_CALL_WAIT_PROC;
1826 rx_atomic_dec(&rx_nWaiting);
1829 if (call->state != RX_STATE_PRECALL || call->error) {
1830 MUTEX_EXIT(&call->lock);
1831 MUTEX_ENTER(&rx_serverPool_lock);
1832 ReturnToServerPool(service);
1837 if (queue_IsEmpty(&call->rq)
1838 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1839 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1841 CLEAR_CALL_QUEUE_LOCK(call);
1844 /* If there are no eligible incoming calls, add this process
1845 * to the idle server queue, to wait for one */
1849 *socketp = OSI_NULLSOCKET;
1851 sq->socketp = socketp;
1852 queue_Append(&rx_idleServerQueue, sq);
1853 #ifndef AFS_AIX41_ENV
1854 rx_waitForPacket = sq;
1856 rx_waitingForPacket = sq;
1857 #endif /* AFS_AIX41_ENV */
1859 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1861 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1862 MUTEX_EXIT(&rx_serverPool_lock);
1863 return (struct rx_call *)0;
1866 } while (!(call = sq->newcall)
1867 && !(socketp && *socketp != OSI_NULLSOCKET));
1868 MUTEX_EXIT(&rx_serverPool_lock);
1870 MUTEX_ENTER(&call->lock);
1876 MUTEX_ENTER(&freeSQEList_lock);
1877 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1878 rx_FreeSQEList = sq;
1879 MUTEX_EXIT(&freeSQEList_lock);
1882 clock_GetTime(&call->startTime);
1883 call->state = RX_STATE_ACTIVE;
1884 call->mode = RX_MODE_RECEIVING;
1885 #ifdef RX_KERNEL_TRACE
1886 if (ICL_SETACTIVE(afs_iclSetp)) {
1887 int glockOwner = ISAFS_GLOCK();
1890 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1891 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1898 rxi_calltrace(RX_CALL_START, call);
1899 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1900 call->conn->service->servicePort, call->conn->service->serviceId,
1903 MUTEX_EXIT(&call->lock);
1904 MUTEX_ENTER(&rx_refcnt_mutex);
1905 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1906 MUTEX_EXIT(&rx_refcnt_mutex);
1908 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1913 #else /* RX_ENABLE_LOCKS */
1915 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1917 struct rx_serverQueueEntry *sq;
1918 struct rx_call *call = (struct rx_call *)0, *choice2;
1919 struct rx_service *service = NULL;
1923 MUTEX_ENTER(&freeSQEList_lock);
1925 if ((sq = rx_FreeSQEList)) {
1926 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1927 MUTEX_EXIT(&freeSQEList_lock);
1928 } else { /* otherwise allocate a new one and return that */
1929 MUTEX_EXIT(&freeSQEList_lock);
1930 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1931 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1932 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1934 MUTEX_ENTER(&sq->lock);
1936 if (cur_service != NULL) {
1937 cur_service->nRequestsRunning--;
1938 MUTEX_ENTER(&rx_quota_mutex);
1939 if (cur_service->nRequestsRunning < cur_service->minProcs)
1942 MUTEX_EXIT(&rx_quota_mutex);
1944 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1945 struct rx_call *tcall, *ncall;
1946 /* Scan for eligible incoming calls. A call is not eligible
1947 * if the maximum number of calls for its service type are
1948 * already executing */
1949 /* One thread will process calls FCFS (to prevent starvation),
1950 * while the other threads may run ahead looking for calls which
1951 * have all their input data available immediately. This helps
1952 * keep threads from blocking, waiting for data from the client. */
1953 choice2 = (struct rx_call *)0;
1954 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1955 service = tcall->conn->service;
1956 if (QuotaOK(service)) {
1957 MUTEX_ENTER(&rx_pthread_mutex);
1958 if (tno == rxi_fcfs_thread_num
1959 || !tcall->queue_item_header.next) {
1960 MUTEX_EXIT(&rx_pthread_mutex);
1961 /* If we're the fcfs thread, then we'll just use
1962 * this call. If we haven't been able to find an optimal
1963 * choice, and we're at the end of the list, then use a
1964 * 2d choice if one has been identified. Otherwise... */
1965 call = (choice2 ? choice2 : tcall);
1966 service = call->conn->service;
1968 MUTEX_EXIT(&rx_pthread_mutex);
1969 if (!queue_IsEmpty(&tcall->rq)) {
1970 struct rx_packet *rp;
1971 rp = queue_First(&tcall->rq, rx_packet);
1972 if (rp->header.seq == 1
1974 || (rp->header.flags & RX_LAST_PACKET))) {
1976 } else if (rxi_2dchoice && !choice2
1977 && !(tcall->flags & RX_CALL_CLEARED)
1978 && (tcall->rprev > rxi_HardAckRate)) {
1992 /* we can't schedule a call if there's no data!!! */
1993 /* send an ack if there's no data, if we're missing the
1994 * first packet, or we're missing something between first
1995 * and last -- there's a "hole" in the incoming data. */
1996 if (queue_IsEmpty(&call->rq)
1997 || queue_First(&call->rq, rx_packet)->header.seq != 1
1998 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1999 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2001 call->flags &= (~RX_CALL_WAIT_PROC);
2002 service->nRequestsRunning++;
2003 /* just started call in minProcs pool, need fewer to maintain
2005 MUTEX_ENTER(&rx_quota_mutex);
2006 if (service->nRequestsRunning <= service->minProcs)
2009 MUTEX_EXIT(&rx_quota_mutex);
2010 rx_atomic_dec(&rx_nWaiting);
2011 /* MUTEX_EXIT(&call->lock); */
2013 /* If there are no eligible incoming calls, add this process
2014 * to the idle server queue, to wait for one */
2017 *socketp = OSI_NULLSOCKET;
2019 sq->socketp = socketp;
2020 queue_Append(&rx_idleServerQueue, sq);
2024 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2026 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2027 return (struct rx_call *)0;
2030 } while (!(call = sq->newcall)
2031 && !(socketp && *socketp != OSI_NULLSOCKET));
2033 MUTEX_EXIT(&sq->lock);
2035 MUTEX_ENTER(&freeSQEList_lock);
2036 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2037 rx_FreeSQEList = sq;
2038 MUTEX_EXIT(&freeSQEList_lock);
2041 clock_GetTime(&call->startTime);
2042 call->state = RX_STATE_ACTIVE;
2043 call->mode = RX_MODE_RECEIVING;
2044 #ifdef RX_KERNEL_TRACE
2045 if (ICL_SETACTIVE(afs_iclSetp)) {
2046 int glockOwner = ISAFS_GLOCK();
2049 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2050 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2057 rxi_calltrace(RX_CALL_START, call);
2058 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2059 call->conn->service->servicePort, call->conn->service->serviceId,
2062 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2069 #endif /* RX_ENABLE_LOCKS */
2073 /* Establish a procedure to be called when a packet arrives for a
2074 * call. This routine will be called at most once after each call,
2075 * and will also be called if there is an error condition on the or
2076 * the call is complete. Used by multi rx to build a selection
2077 * function which determines which of several calls is likely to be a
2078 * good one to read from.
2079 * NOTE: the way this is currently implemented it is probably only a
2080 * good idea to (1) use it immediately after a newcall (clients only)
2081 * and (2) only use it once. Other uses currently void your warranty
2084 rx_SetArrivalProc(struct rx_call *call,
2085 void (*proc) (struct rx_call * call,
2088 void * handle, int arg)
2090 call->arrivalProc = proc;
2091 call->arrivalProcHandle = handle;
2092 call->arrivalProcArg = arg;
2095 /* Call is finished (possibly prematurely). Return rc to the peer, if
2096 * appropriate, and return the final error code from the conversation
2100 rx_EndCall(struct rx_call *call, afs_int32 rc)
2102 struct rx_connection *conn = call->conn;
2106 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2107 call, rc, call->error, call->abortCode));
2110 MUTEX_ENTER(&call->lock);
2112 if (rc == 0 && call->error == 0) {
2113 call->abortCode = 0;
2114 call->abortCount = 0;
2117 call->arrivalProc = (void (*)())0;
2118 if (rc && call->error == 0) {
2119 rxi_CallError(call, rc);
2120 call->mode = RX_MODE_ERROR;
2121 /* Send an abort message to the peer if this error code has
2122 * only just been set. If it was set previously, assume the
2123 * peer has already been sent the error code or will request it
2125 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2127 if (conn->type == RX_SERVER_CONNECTION) {
2128 /* Make sure reply or at least dummy reply is sent */
2129 if (call->mode == RX_MODE_RECEIVING) {
2130 MUTEX_EXIT(&call->lock);
2131 rxi_WriteProc(call, 0, 0);
2132 MUTEX_ENTER(&call->lock);
2134 if (call->mode == RX_MODE_SENDING) {
2135 MUTEX_EXIT(&call->lock);
2136 rxi_FlushWrite(call);
2137 MUTEX_ENTER(&call->lock);
2139 rxi_calltrace(RX_CALL_END, call);
2140 /* Call goes to hold state until reply packets are acknowledged */
2141 if (call->tfirst + call->nSoftAcked < call->tnext) {
2142 call->state = RX_STATE_HOLD;
2144 call->state = RX_STATE_DALLY;
2145 rxi_ClearTransmitQueue(call, 0);
2146 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2147 rxevent_Cancel(call->keepAliveEvent, call,
2148 RX_CALL_REFCOUNT_ALIVE);
2150 } else { /* Client connection */
2152 /* Make sure server receives input packets, in the case where
2153 * no reply arguments are expected */
2154 if ((call->mode == RX_MODE_SENDING)
2155 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2156 MUTEX_EXIT(&call->lock);
2157 (void)rxi_ReadProc(call, &dummy, 1);
2158 MUTEX_ENTER(&call->lock);
2161 /* If we had an outstanding delayed ack, be nice to the server
2162 * and force-send it now.
2164 if (call->delayedAckEvent) {
2165 rxevent_Cancel(call->delayedAckEvent, call,
2166 RX_CALL_REFCOUNT_DELAY);
2167 call->delayedAckEvent = NULL;
2168 rxi_SendDelayedAck(NULL, call, NULL);
2171 /* We need to release the call lock since it's lower than the
2172 * conn_call_lock and we don't want to hold the conn_call_lock
2173 * over the rx_ReadProc call. The conn_call_lock needs to be held
2174 * here for the case where rx_NewCall is perusing the calls on
2175 * the connection structure. We don't want to signal until
2176 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2177 * have checked this call, found it active and by the time it
2178 * goes to sleep, will have missed the signal.
2180 MUTEX_EXIT(&call->lock);
2181 MUTEX_ENTER(&conn->conn_call_lock);
2182 MUTEX_ENTER(&call->lock);
2183 MUTEX_ENTER(&conn->conn_data_lock);
2184 conn->flags |= RX_CONN_BUSY;
2185 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2186 MUTEX_EXIT(&conn->conn_data_lock);
2187 #ifdef RX_ENABLE_LOCKS
2188 CV_BROADCAST(&conn->conn_call_cv);
2193 #ifdef RX_ENABLE_LOCKS
2195 MUTEX_EXIT(&conn->conn_data_lock);
2197 #endif /* RX_ENABLE_LOCKS */
2198 call->state = RX_STATE_DALLY;
2200 error = call->error;
2202 /* currentPacket, nLeft, and NFree must be zeroed here, because
2203 * ResetCall cannot: ResetCall may be called at splnet(), in the
2204 * kernel version, and may interrupt the macros rx_Read or
2205 * rx_Write, which run at normal priority for efficiency. */
2206 if (call->currentPacket) {
2207 #ifdef RX_TRACK_PACKETS
2208 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2210 rxi_FreePacket(call->currentPacket);
2211 call->currentPacket = (struct rx_packet *)0;
2214 call->nLeft = call->nFree = call->curlen = 0;
2216 /* Free any packets from the last call to ReadvProc/WritevProc */
2217 #ifdef RXDEBUG_PACKET
2219 #endif /* RXDEBUG_PACKET */
2220 rxi_FreePackets(0, &call->iovq);
2221 MUTEX_EXIT(&call->lock);
2223 MUTEX_ENTER(&rx_refcnt_mutex);
2224 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2225 MUTEX_EXIT(&rx_refcnt_mutex);
2226 if (conn->type == RX_CLIENT_CONNECTION) {
2227 MUTEX_ENTER(&conn->conn_data_lock);
2228 conn->flags &= ~RX_CONN_BUSY;
2229 MUTEX_EXIT(&conn->conn_data_lock);
2230 MUTEX_EXIT(&conn->conn_call_lock);
2234 * Map errors to the local host's errno.h format.
2236 error = ntoh_syserr_conv(error);
2240 #if !defined(KERNEL)
2242 /* Call this routine when shutting down a server or client (especially
2243 * clients). This will allow Rx to gracefully garbage collect server
2244 * connections, and reduce the number of retries that a server might
2245 * make to a dead client.
2246 * This is not quite right, since some calls may still be ongoing and
2247 * we can't lock them to destroy them. */
2251 struct rx_connection **conn_ptr, **conn_end;
2255 if (rxinit_status == 1) {
2257 return; /* Already shutdown. */
2259 rxi_DeleteCachedConnections();
2260 if (rx_connHashTable) {
2261 MUTEX_ENTER(&rx_connHashTable_lock);
2262 for (conn_ptr = &rx_connHashTable[0], conn_end =
2263 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2265 struct rx_connection *conn, *next;
2266 for (conn = *conn_ptr; conn; conn = next) {
2268 if (conn->type == RX_CLIENT_CONNECTION) {
2269 MUTEX_ENTER(&rx_refcnt_mutex);
2271 MUTEX_EXIT(&rx_refcnt_mutex);
2272 #ifdef RX_ENABLE_LOCKS
2273 rxi_DestroyConnectionNoLock(conn);
2274 #else /* RX_ENABLE_LOCKS */
2275 rxi_DestroyConnection(conn);
2276 #endif /* RX_ENABLE_LOCKS */
2280 #ifdef RX_ENABLE_LOCKS
2281 while (rx_connCleanup_list) {
2282 struct rx_connection *conn;
2283 conn = rx_connCleanup_list;
2284 rx_connCleanup_list = rx_connCleanup_list->next;
2285 MUTEX_EXIT(&rx_connHashTable_lock);
2286 rxi_CleanupConnection(conn);
2287 MUTEX_ENTER(&rx_connHashTable_lock);
2289 MUTEX_EXIT(&rx_connHashTable_lock);
2290 #endif /* RX_ENABLE_LOCKS */
2295 afs_winsockCleanup();
2303 /* if we wakeup packet waiter too often, can get in loop with two
2304 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2306 rxi_PacketsUnWait(void)
2308 if (!rx_waitingForPackets) {
2312 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2313 return; /* still over quota */
2316 rx_waitingForPackets = 0;
2317 #ifdef RX_ENABLE_LOCKS
2318 CV_BROADCAST(&rx_waitingForPackets_cv);
2320 osi_rxWakeup(&rx_waitingForPackets);
2326 /* ------------------Internal interfaces------------------------- */
2328 /* Return this process's service structure for the
2329 * specified socket and service */
2331 rxi_FindService(osi_socket socket, u_short serviceId)
2333 struct rx_service **sp;
2334 for (sp = &rx_services[0]; *sp; sp++) {
2335 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2341 #ifdef RXDEBUG_PACKET
2342 #ifdef KDUMP_RX_LOCK
2343 static struct rx_call_rx_lock *rx_allCallsp = 0;
2345 static struct rx_call *rx_allCallsp = 0;
2347 #endif /* RXDEBUG_PACKET */
2349 /* Allocate a call structure, for the indicated channel of the
2350 * supplied connection. The mode and state of the call must be set by
2351 * the caller. Returns the call with mutex locked. */
2353 rxi_NewCall(struct rx_connection *conn, int channel)
2355 struct rx_call *call;
2356 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2357 struct rx_call *cp; /* Call pointer temp */
2358 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2359 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2361 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2363 /* Grab an existing call structure, or allocate a new one.
2364 * Existing call structures are assumed to have been left reset by
2366 MUTEX_ENTER(&rx_freeCallQueue_lock);
2368 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2370 * EXCEPT that the TQ might not yet be cleared out.
2371 * Skip over those with in-use TQs.
2374 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2375 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2381 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2382 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2383 call = queue_First(&rx_freeCallQueue, rx_call);
2384 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2386 if (rx_stats_active)
2387 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2388 MUTEX_EXIT(&rx_freeCallQueue_lock);
2389 MUTEX_ENTER(&call->lock);
2390 CLEAR_CALL_QUEUE_LOCK(call);
2391 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2392 /* Now, if TQ wasn't cleared earlier, do it now. */
2393 rxi_WaitforTQBusy(call);
2394 if (call->flags & RX_CALL_TQ_CLEARME) {
2395 rxi_ClearTransmitQueue(call, 1);
2396 /*queue_Init(&call->tq);*/
2398 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2399 /* Bind the call to its connection structure */
2401 rxi_ResetCall(call, 1);
2404 call = rxi_Alloc(sizeof(struct rx_call));
2405 #ifdef RXDEBUG_PACKET
2406 call->allNextp = rx_allCallsp;
2407 rx_allCallsp = call;
2409 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2410 #else /* RXDEBUG_PACKET */
2411 rx_atomic_inc(&rx_stats.nCallStructs);
2412 #endif /* RXDEBUG_PACKET */
2414 MUTEX_EXIT(&rx_freeCallQueue_lock);
2415 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2416 MUTEX_ENTER(&call->lock);
2417 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2418 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2419 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2421 /* Initialize once-only items */
2422 queue_Init(&call->tq);
2423 queue_Init(&call->rq);
2424 queue_Init(&call->iovq);
2425 #ifdef RXDEBUG_PACKET
2426 call->rqc = call->tqc = call->iovqc = 0;
2427 #endif /* RXDEBUG_PACKET */
2428 /* Bind the call to its connection structure (prereq for reset) */
2430 rxi_ResetCall(call, 1);
2432 call->channel = channel;
2433 call->callNumber = &conn->callNumber[channel];
2434 call->rwind = conn->rwind[channel];
2435 call->twind = conn->twind[channel];
2436 /* Note that the next expected call number is retained (in
2437 * conn->callNumber[i]), even if we reallocate the call structure
2439 conn->call[channel] = call;
2440 /* if the channel's never been used (== 0), we should start at 1, otherwise
2441 * the call number is valid from the last time this channel was used */
2442 if (*call->callNumber == 0)
2443 *call->callNumber = 1;
2448 /* A call has been inactive long enough that so we can throw away
2449 * state, including the call structure, which is placed on the call
2452 * call->lock amd rx_refcnt_mutex are held upon entry.
2453 * haveCTLock is set when called from rxi_ReapConnections.
2456 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2458 int channel = call->channel;
2459 struct rx_connection *conn = call->conn;
2462 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2463 (*call->callNumber)++;
2464 rxi_ResetCall(call, 0);
2465 call->conn->call[channel] = (struct rx_call *)0;
2466 MUTEX_EXIT(&rx_refcnt_mutex);
2468 MUTEX_ENTER(&rx_freeCallQueue_lock);
2469 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2470 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2471 /* A call may be free even though its transmit queue is still in use.
2472 * Since we search the call list from head to tail, put busy calls at
2473 * the head of the list, and idle calls at the tail.
2475 if (call->flags & RX_CALL_TQ_BUSY)
2476 queue_Prepend(&rx_freeCallQueue, call);
2478 queue_Append(&rx_freeCallQueue, call);
2479 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2480 queue_Append(&rx_freeCallQueue, call);
2481 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2482 if (rx_stats_active)
2483 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2484 MUTEX_EXIT(&rx_freeCallQueue_lock);
2486 /* Destroy the connection if it was previously slated for
2487 * destruction, i.e. the Rx client code previously called
2488 * rx_DestroyConnection (client connections), or
2489 * rxi_ReapConnections called the same routine (server
2490 * connections). Only do this, however, if there are no
2491 * outstanding calls. Note that for fine grain locking, there appears
2492 * to be a deadlock in that rxi_FreeCall has a call locked and
2493 * DestroyConnectionNoLock locks each call in the conn. But note a
2494 * few lines up where we have removed this call from the conn.
2495 * If someone else destroys a connection, they either have no
2496 * call lock held or are going through this section of code.
2498 MUTEX_ENTER(&conn->conn_data_lock);
2499 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2500 MUTEX_ENTER(&rx_refcnt_mutex);
2502 MUTEX_EXIT(&rx_refcnt_mutex);
2503 MUTEX_EXIT(&conn->conn_data_lock);
2504 #ifdef RX_ENABLE_LOCKS
2506 rxi_DestroyConnectionNoLock(conn);
2508 rxi_DestroyConnection(conn);
2509 #else /* RX_ENABLE_LOCKS */
2510 rxi_DestroyConnection(conn);
2511 #endif /* RX_ENABLE_LOCKS */
2513 MUTEX_EXIT(&conn->conn_data_lock);
2515 MUTEX_ENTER(&rx_refcnt_mutex);
2518 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2519 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2522 rxi_Alloc(size_t size)
2526 if (rx_stats_active) {
2527 rx_atomic_add(&rxi_Allocsize, (int) size);
2528 rx_atomic_inc(&rxi_Alloccnt);
2532 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2533 afs_osi_Alloc_NoSleep(size);
2538 osi_Panic("rxi_Alloc error");
2544 rxi_Free(void *addr, size_t size)
2546 if (rx_stats_active) {
2547 rx_atomic_sub(&rxi_Allocsize, (int) size);
2548 rx_atomic_dec(&rxi_Alloccnt);
2550 osi_Free(addr, size);
2554 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2556 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2557 struct rx_peer *next = NULL;
2561 MUTEX_ENTER(&rx_peerHashTable_lock);
2563 peer_ptr = &rx_peerHashTable[0];
2564 peer_end = &rx_peerHashTable[rx_hashTableSize];
2567 for ( ; peer_ptr < peer_end; peer_ptr++) {
2570 for ( ; peer; peer = next) {
2572 if (host == peer->host)
2577 hashIndex = PEER_HASH(host, port);
2578 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2579 if ((peer->host == host) && (peer->port == port))
2584 MUTEX_ENTER(&rx_peerHashTable_lock);
2589 MUTEX_EXIT(&rx_peerHashTable_lock);
2591 MUTEX_ENTER(&peer->peer_lock);
2592 /* We don't handle dropping below min, so don't */
2593 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2594 peer->ifMTU=MIN(mtu, peer->ifMTU);
2595 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2596 /* if we tweaked this down, need to tune our peer MTU too */
2597 peer->MTU = MIN(peer->MTU, peer->natMTU);
2598 /* if we discovered a sub-1500 mtu, degrade */
2599 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2600 peer->maxDgramPackets = 1;
2601 /* We no longer have valid peer packet information */
2602 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2603 peer->maxPacketSize = 0;
2604 MUTEX_EXIT(&peer->peer_lock);
2606 MUTEX_ENTER(&rx_peerHashTable_lock);
2608 if (host && !port) {
2610 /* pick up where we left off */
2614 MUTEX_EXIT(&rx_peerHashTable_lock);
2617 /* Find the peer process represented by the supplied (host,port)
2618 * combination. If there is no appropriate active peer structure, a
2619 * new one will be allocated and initialized
2620 * The origPeer, if set, is a pointer to a peer structure on which the
2621 * refcount will be be decremented. This is used to replace the peer
2622 * structure hanging off a connection structure */
2624 rxi_FindPeer(afs_uint32 host, u_short port,
2625 struct rx_peer *origPeer, int create)
2629 hashIndex = PEER_HASH(host, port);
2630 MUTEX_ENTER(&rx_peerHashTable_lock);
2631 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2632 if ((pp->host == host) && (pp->port == port))
2637 pp = rxi_AllocPeer(); /* This bzero's *pp */
2638 pp->host = host; /* set here or in InitPeerParams is zero */
2640 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2641 queue_Init(&pp->congestionQueue);
2642 queue_Init(&pp->rpcStats);
2643 pp->next = rx_peerHashTable[hashIndex];
2644 rx_peerHashTable[hashIndex] = pp;
2645 rxi_InitPeerParams(pp);
2646 if (rx_stats_active)
2647 rx_atomic_inc(&rx_stats.nPeerStructs);
2654 origPeer->refCount--;
2655 MUTEX_EXIT(&rx_peerHashTable_lock);
2660 /* Find the connection at (host, port) started at epoch, and with the
2661 * given connection id. Creates the server connection if necessary.
2662 * The type specifies whether a client connection or a server
2663 * connection is desired. In both cases, (host, port) specify the
2664 * peer's (host, pair) pair. Client connections are not made
2665 * automatically by this routine. The parameter socket gives the
2666 * socket descriptor on which the packet was received. This is used,
2667 * in the case of server connections, to check that *new* connections
2668 * come via a valid (port, serviceId). Finally, the securityIndex
2669 * parameter must match the existing index for the connection. If a
2670 * server connection is created, it will be created using the supplied
2671 * index, if the index is valid for this service */
2672 struct rx_connection *
2673 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2674 u_short port, u_short serviceId, afs_uint32 cid,
2675 afs_uint32 epoch, int type, u_int securityIndex)
2677 int hashindex, flag, i;
2678 struct rx_connection *conn;
2679 hashindex = CONN_HASH(host, port, cid, epoch, type);
2680 MUTEX_ENTER(&rx_connHashTable_lock);
2681 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2682 rx_connHashTable[hashindex],
2685 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2686 && (epoch == conn->epoch)) {
2687 struct rx_peer *pp = conn->peer;
2688 if (securityIndex != conn->securityIndex) {
2689 /* this isn't supposed to happen, but someone could forge a packet
2690 * like this, and there seems to be some CM bug that makes this
2691 * happen from time to time -- in which case, the fileserver
2693 MUTEX_EXIT(&rx_connHashTable_lock);
2694 return (struct rx_connection *)0;
2696 if (pp->host == host && pp->port == port)
2698 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2700 /* So what happens when it's a callback connection? */
2701 if ( /*type == RX_CLIENT_CONNECTION && */
2702 (conn->epoch & 0x80000000))
2706 /* the connection rxLastConn that was used the last time is not the
2707 ** one we are looking for now. Hence, start searching in the hash */
2709 conn = rx_connHashTable[hashindex];
2714 struct rx_service *service;
2715 if (type == RX_CLIENT_CONNECTION) {
2716 MUTEX_EXIT(&rx_connHashTable_lock);
2717 return (struct rx_connection *)0;
2719 service = rxi_FindService(socket, serviceId);
2720 if (!service || (securityIndex >= service->nSecurityObjects)
2721 || (service->securityObjects[securityIndex] == 0)) {
2722 MUTEX_EXIT(&rx_connHashTable_lock);
2723 return (struct rx_connection *)0;
2725 conn = rxi_AllocConnection(); /* This bzero's the connection */
2726 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2727 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2728 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2729 conn->next = rx_connHashTable[hashindex];
2730 rx_connHashTable[hashindex] = conn;
2731 conn->peer = rxi_FindPeer(host, port, 0, 1);
2732 conn->type = RX_SERVER_CONNECTION;
2733 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2734 conn->epoch = epoch;
2735 conn->cid = cid & RX_CIDMASK;
2736 /* conn->serial = conn->lastSerial = 0; */
2737 /* conn->timeout = 0; */
2738 conn->ackRate = RX_FAST_ACK_RATE;
2739 conn->service = service;
2740 conn->serviceId = serviceId;
2741 conn->securityIndex = securityIndex;
2742 conn->securityObject = service->securityObjects[securityIndex];
2743 conn->nSpecific = 0;
2744 conn->specific = NULL;
2745 rx_SetConnDeadTime(conn, service->connDeadTime);
2746 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2747 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2748 for (i = 0; i < RX_MAXCALLS; i++) {
2749 conn->twind[i] = rx_initSendWindow;
2750 conn->rwind[i] = rx_initReceiveWindow;
2752 /* Notify security object of the new connection */
2753 RXS_NewConnection(conn->securityObject, conn);
2754 /* XXXX Connection timeout? */
2755 if (service->newConnProc)
2756 (*service->newConnProc) (conn);
2757 if (rx_stats_active)
2758 rx_atomic_inc(&rx_stats.nServerConns);
2761 MUTEX_ENTER(&rx_refcnt_mutex);
2763 MUTEX_EXIT(&rx_refcnt_mutex);
2765 rxLastConn = conn; /* store this connection as the last conn used */
2766 MUTEX_EXIT(&rx_connHashTable_lock);
2770 /* There are two packet tracing routines available for testing and monitoring
2771 * Rx. One is called just after every packet is received and the other is
2772 * called just before every packet is sent. Received packets, have had their
2773 * headers decoded, and packets to be sent have not yet had their headers
2774 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2775 * containing the network address. Both can be modified. The return value, if
2776 * non-zero, indicates that the packet should be dropped. */
2778 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2779 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2781 /* A packet has been received off the interface. Np is the packet, socket is
2782 * the socket number it was received from (useful in determining which service
2783 * this packet corresponds to), and (host, port) reflect the host,port of the
2784 * sender. This call returns the packet to the caller if it is finished with
2785 * it, rather than de-allocating it, just as a small performance hack */
2788 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2789 afs_uint32 host, u_short port, int *tnop,
2790 struct rx_call **newcallp)
2792 struct rx_call *call;
2793 struct rx_connection *conn;
2795 afs_uint32 currentCallNumber;
2801 struct rx_packet *tnp;
2804 /* We don't print out the packet until now because (1) the time may not be
2805 * accurate enough until now in the lwp implementation (rx_Listener only gets
2806 * the time after the packet is read) and (2) from a protocol point of view,
2807 * this is the first time the packet has been seen */
2808 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2809 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2810 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2811 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2812 np->header.epoch, np->header.cid, np->header.callNumber,
2813 np->header.seq, np->header.flags, np));
2816 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2817 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2820 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2821 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2824 /* If an input tracer function is defined, call it with the packet and
2825 * network address. Note this function may modify its arguments. */
2826 if (rx_justReceived) {
2827 struct sockaddr_in addr;
2829 addr.sin_family = AF_INET;
2830 addr.sin_port = port;
2831 addr.sin_addr.s_addr = host;
2832 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2833 addr.sin_len = sizeof(addr);
2834 #endif /* AFS_OSF_ENV */
2835 drop = (*rx_justReceived) (np, &addr);
2836 /* drop packet if return value is non-zero */
2839 port = addr.sin_port; /* in case fcn changed addr */
2840 host = addr.sin_addr.s_addr;
2844 /* If packet was not sent by the client, then *we* must be the client */
2845 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2846 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2848 /* Find the connection (or fabricate one, if we're the server & if
2849 * necessary) associated with this packet */
2851 rxi_FindConnection(socket, host, port, np->header.serviceId,
2852 np->header.cid, np->header.epoch, type,
2853 np->header.securityIndex);
2856 /* If no connection found or fabricated, just ignore the packet.
2857 * (An argument could be made for sending an abort packet for
2862 MUTEX_ENTER(&conn->conn_data_lock);
2863 if (conn->maxSerial < np->header.serial)
2864 conn->maxSerial = np->header.serial;
2865 MUTEX_EXIT(&conn->conn_data_lock);
2867 /* If the connection is in an error state, send an abort packet and ignore
2868 * the incoming packet */
2870 /* Don't respond to an abort packet--we don't want loops! */
2871 MUTEX_ENTER(&conn->conn_data_lock);
2872 if (np->header.type != RX_PACKET_TYPE_ABORT)
2873 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2874 MUTEX_ENTER(&rx_refcnt_mutex);
2876 MUTEX_EXIT(&rx_refcnt_mutex);
2877 MUTEX_EXIT(&conn->conn_data_lock);
2881 /* Check for connection-only requests (i.e. not call specific). */
2882 if (np->header.callNumber == 0) {
2883 switch (np->header.type) {
2884 case RX_PACKET_TYPE_ABORT: {
2885 /* What if the supplied error is zero? */
2886 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2887 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2888 rxi_ConnectionError(conn, errcode);
2889 MUTEX_ENTER(&rx_refcnt_mutex);
2891 MUTEX_EXIT(&rx_refcnt_mutex);
2894 case RX_PACKET_TYPE_CHALLENGE:
2895 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2896 MUTEX_ENTER(&rx_refcnt_mutex);
2898 MUTEX_EXIT(&rx_refcnt_mutex);
2900 case RX_PACKET_TYPE_RESPONSE:
2901 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2902 MUTEX_ENTER(&rx_refcnt_mutex);
2904 MUTEX_EXIT(&rx_refcnt_mutex);
2906 case RX_PACKET_TYPE_PARAMS:
2907 case RX_PACKET_TYPE_PARAMS + 1:
2908 case RX_PACKET_TYPE_PARAMS + 2:
2909 /* ignore these packet types for now */
2910 MUTEX_ENTER(&rx_refcnt_mutex);
2912 MUTEX_EXIT(&rx_refcnt_mutex);
2917 /* Should not reach here, unless the peer is broken: send an
2919 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2920 MUTEX_ENTER(&conn->conn_data_lock);
2921 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2922 MUTEX_ENTER(&rx_refcnt_mutex);
2924 MUTEX_EXIT(&rx_refcnt_mutex);
2925 MUTEX_EXIT(&conn->conn_data_lock);
2930 channel = np->header.cid & RX_CHANNELMASK;
2931 call = conn->call[channel];
2932 #ifdef RX_ENABLE_LOCKS
2934 MUTEX_ENTER(&call->lock);
2935 /* Test to see if call struct is still attached to conn. */
2936 if (call != conn->call[channel]) {
2938 MUTEX_EXIT(&call->lock);
2939 if (type == RX_SERVER_CONNECTION) {
2940 call = conn->call[channel];
2941 /* If we started with no call attached and there is one now,
2942 * another thread is also running this routine and has gotten
2943 * the connection channel. We should drop this packet in the tests
2944 * below. If there was a call on this connection and it's now
2945 * gone, then we'll be making a new call below.
2946 * If there was previously a call and it's now different then
2947 * the old call was freed and another thread running this routine
2948 * has created a call on this channel. One of these two threads
2949 * has a packet for the old call and the code below handles those
2953 MUTEX_ENTER(&call->lock);
2955 /* This packet can't be for this call. If the new call address is
2956 * 0 then no call is running on this channel. If there is a call
2957 * then, since this is a client connection we're getting data for
2958 * it must be for the previous call.
2960 if (rx_stats_active)
2961 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2962 MUTEX_ENTER(&rx_refcnt_mutex);
2964 MUTEX_EXIT(&rx_refcnt_mutex);
2969 currentCallNumber = conn->callNumber[channel];
2971 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2972 if (np->header.callNumber < currentCallNumber) {
2973 if (rx_stats_active)
2974 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2975 #ifdef RX_ENABLE_LOCKS
2977 MUTEX_EXIT(&call->lock);
2979 MUTEX_ENTER(&rx_refcnt_mutex);
2981 MUTEX_EXIT(&rx_refcnt_mutex);
2985 MUTEX_ENTER(&conn->conn_call_lock);
2986 call = rxi_NewCall(conn, channel);
2987 MUTEX_EXIT(&conn->conn_call_lock);
2988 *call->callNumber = np->header.callNumber;
2990 if (np->header.callNumber == 0)
2991 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d",
2992 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2993 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2994 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2996 call->state = RX_STATE_PRECALL;
2997 clock_GetTime(&call->queueTime);
2998 hzero(call->bytesSent);
2999 hzero(call->bytesRcvd);
3001 * If the number of queued calls exceeds the overload
3002 * threshold then abort this call.
3004 if ((rx_BusyThreshold > 0) &&
3005 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3006 struct rx_packet *tp;
3008 rxi_CallError(call, rx_BusyError);
3009 tp = rxi_SendCallAbort(call, np, 1, 0);
3010 MUTEX_EXIT(&call->lock);
3011 MUTEX_ENTER(&rx_refcnt_mutex);
3013 MUTEX_EXIT(&rx_refcnt_mutex);
3014 if (rx_stats_active)
3015 rx_atomic_inc(&rx_stats.nBusies);
3018 rxi_KeepAliveOn(call);
3019 } else if (np->header.callNumber != currentCallNumber) {
3020 /* Wait until the transmit queue is idle before deciding
3021 * whether to reset the current call. Chances are that the
3022 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3025 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3026 while ((call->state == RX_STATE_ACTIVE)
3027 && (call->flags & RX_CALL_TQ_BUSY)) {
3028 call->flags |= RX_CALL_TQ_WAIT;
3030 #ifdef RX_ENABLE_LOCKS
3031 osirx_AssertMine(&call->lock, "rxi_Start lock3");
3032 CV_WAIT(&call->cv_tq, &call->lock);
3033 #else /* RX_ENABLE_LOCKS */
3034 osi_rxSleep(&call->tq);
3035 #endif /* RX_ENABLE_LOCKS */
3037 if (call->tqWaiters == 0)
3038 call->flags &= ~RX_CALL_TQ_WAIT;
3040 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3041 /* If the new call cannot be taken right now send a busy and set
3042 * the error condition in this call, so that it terminates as
3043 * quickly as possible */
3044 if (call->state == RX_STATE_ACTIVE) {
3045 struct rx_packet *tp;
3047 rxi_CallError(call, RX_CALL_DEAD);
3048 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3050 MUTEX_EXIT(&call->lock);
3051 MUTEX_ENTER(&rx_refcnt_mutex);
3053 MUTEX_EXIT(&rx_refcnt_mutex);
3056 rxi_ResetCall(call, 0);
3057 *call->callNumber = np->header.callNumber;
3059 if (np->header.callNumber == 0)
3060 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
3061 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3062 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3063 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3065 call->state = RX_STATE_PRECALL;
3066 clock_GetTime(&call->queueTime);
3067 hzero(call->bytesSent);
3068 hzero(call->bytesRcvd);
3070 * If the number of queued calls exceeds the overload
3071 * threshold then abort this call.
3073 if ((rx_BusyThreshold > 0) &&
3074 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3075 struct rx_packet *tp;
3077 rxi_CallError(call, rx_BusyError);
3078 tp = rxi_SendCallAbort(call, np, 1, 0);
3079 MUTEX_EXIT(&call->lock);
3080 MUTEX_ENTER(&rx_refcnt_mutex);
3082 MUTEX_EXIT(&rx_refcnt_mutex);
3083 if (rx_stats_active)
3084 rx_atomic_inc(&rx_stats.nBusies);
3087 rxi_KeepAliveOn(call);
3089 /* Continuing call; do nothing here. */
3091 } else { /* we're the client */
3092 /* Ignore all incoming acknowledgements for calls in DALLY state */
3093 if (call && (call->state == RX_STATE_DALLY)
3094 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3095 if (rx_stats_active)
3096 rx_atomic_inc(&rx_stats.ignorePacketDally);
3097 #ifdef RX_ENABLE_LOCKS
3099 MUTEX_EXIT(&call->lock);
3102 MUTEX_ENTER(&rx_refcnt_mutex);
3104 MUTEX_EXIT(&rx_refcnt_mutex);
3108 /* Ignore anything that's not relevant to the current call. If there
3109 * isn't a current call, then no packet is relevant. */
3110 if (!call || (np->header.callNumber != currentCallNumber)) {
3111 if (rx_stats_active)
3112 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3113 #ifdef RX_ENABLE_LOCKS
3115 MUTEX_EXIT(&call->lock);
3118 MUTEX_ENTER(&rx_refcnt_mutex);
3120 MUTEX_EXIT(&rx_refcnt_mutex);
3123 /* If the service security object index stamped in the packet does not
3124 * match the connection's security index, ignore the packet */
3125 if (np->header.securityIndex != conn->securityIndex) {
3126 #ifdef RX_ENABLE_LOCKS
3127 MUTEX_EXIT(&call->lock);
3129 MUTEX_ENTER(&rx_refcnt_mutex);
3131 MUTEX_EXIT(&rx_refcnt_mutex);
3135 /* If we're receiving the response, then all transmit packets are
3136 * implicitly acknowledged. Get rid of them. */
3137 if (np->header.type == RX_PACKET_TYPE_DATA) {
3138 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3139 /* XXX Hack. Because we must release the global rx lock when
3140 * sending packets (osi_NetSend) we drop all acks while we're
3141 * traversing the tq in rxi_Start sending packets out because
3142 * packets may move to the freePacketQueue as result of being here!
3143 * So we drop these packets until we're safely out of the
3144 * traversing. Really ugly!
3145 * For fine grain RX locking, we set the acked field in the
3146 * packets and let rxi_Start remove them from the transmit queue.
3148 if (call->flags & RX_CALL_TQ_BUSY) {
3149 #ifdef RX_ENABLE_LOCKS
3150 rxi_SetAcksInTransmitQueue(call);
3152 MUTEX_ENTER(&rx_refcnt_mutex);
3154 MUTEX_EXIT(&rx_refcnt_mutex);
3155 return np; /* xmitting; drop packet */
3158 rxi_ClearTransmitQueue(call, 0);
3160 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3161 rxi_ClearTransmitQueue(call, 0);
3162 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3164 if (np->header.type == RX_PACKET_TYPE_ACK) {
3165 /* now check to see if this is an ack packet acknowledging that the
3166 * server actually *lost* some hard-acked data. If this happens we
3167 * ignore this packet, as it may indicate that the server restarted in
3168 * the middle of a call. It is also possible that this is an old ack
3169 * packet. We don't abort the connection in this case, because this
3170 * *might* just be an old ack packet. The right way to detect a server
3171 * restart in the midst of a call is to notice that the server epoch
3173 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3174 * XXX unacknowledged. I think that this is off-by-one, but
3175 * XXX I don't dare change it just yet, since it will
3176 * XXX interact badly with the server-restart detection
3177 * XXX code in receiveackpacket. */
3178 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3179 if (rx_stats_active)
3180 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3181 MUTEX_EXIT(&call->lock);
3182 MUTEX_ENTER(&rx_refcnt_mutex);
3184 MUTEX_EXIT(&rx_refcnt_mutex);
3188 } /* else not a data packet */
3191 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3192 /* Set remote user defined status from packet */
3193 call->remoteStatus = np->header.userStatus;
3195 /* Note the gap between the expected next packet and the actual
3196 * packet that arrived, when the new packet has a smaller serial number
3197 * than expected. Rioses frequently reorder packets all by themselves,
3198 * so this will be quite important with very large window sizes.
3199 * Skew is checked against 0 here to avoid any dependence on the type of
3200 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3202 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3203 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3204 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3206 MUTEX_ENTER(&conn->conn_data_lock);
3207 skew = conn->lastSerial - np->header.serial;
3208 conn->lastSerial = np->header.serial;
3209 MUTEX_EXIT(&conn->conn_data_lock);
3211 struct rx_peer *peer;
3213 if (skew > peer->inPacketSkew) {
3214 dpf(("*** In skew changed from %d to %d\n",
3215 peer->inPacketSkew, skew));
3216 peer->inPacketSkew = skew;
3220 /* Now do packet type-specific processing */
3221 switch (np->header.type) {
3222 case RX_PACKET_TYPE_DATA:
3223 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3226 case RX_PACKET_TYPE_ACK:
3227 /* Respond immediately to ack packets requesting acknowledgement
3229 if (np->header.flags & RX_REQUEST_ACK) {
3231 (void)rxi_SendCallAbort(call, 0, 1, 0);
3233 (void)rxi_SendAck(call, 0, np->header.serial,
3234 RX_ACK_PING_RESPONSE, 1);
3236 np = rxi_ReceiveAckPacket(call, np, 1);
3238 case RX_PACKET_TYPE_ABORT: {
3239 /* An abort packet: reset the call, passing the error up to the user. */
3240 /* What if error is zero? */
3241 /* What if the error is -1? the application will treat it as a timeout. */
3242 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3243 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3244 rxi_CallError(call, errdata);
3245 MUTEX_EXIT(&call->lock);
3246 MUTEX_ENTER(&rx_refcnt_mutex);
3248 MUTEX_EXIT(&rx_refcnt_mutex);
3249 return np; /* xmitting; drop packet */
3251 case RX_PACKET_TYPE_BUSY:
3254 case RX_PACKET_TYPE_ACKALL:
3255 /* All packets acknowledged, so we can drop all packets previously
3256 * readied for sending */
3257 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3258 /* XXX Hack. We because we can't release the global rx lock when
3259 * sending packets (osi_NetSend) we drop all ack pkts while we're
3260 * traversing the tq in rxi_Start sending packets out because
3261 * packets may move to the freePacketQueue as result of being
3262 * here! So we drop these packets until we're safely out of the
3263 * traversing. Really ugly!
3264 * For fine grain RX locking, we set the acked field in the packets
3265 * and let rxi_Start remove the packets from the transmit queue.
3267 if (call->flags & RX_CALL_TQ_BUSY) {
3268 #ifdef RX_ENABLE_LOCKS
3269 rxi_SetAcksInTransmitQueue(call);
3271 #else /* RX_ENABLE_LOCKS */
3272 MUTEX_EXIT(&call->lock);
3273 MUTEX_ENTER(&rx_refcnt_mutex);
3275 MUTEX_EXIT(&rx_refcnt_mutex);
3276 return np; /* xmitting; drop packet */
3277 #endif /* RX_ENABLE_LOCKS */
3279 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3280 rxi_ClearTransmitQueue(call, 0);
3281 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3284 /* Should not reach here, unless the peer is broken: send an abort
3286 rxi_CallError(call, RX_PROTOCOL_ERROR);
3287 np = rxi_SendCallAbort(call, np, 1, 0);
3290 /* Note when this last legitimate packet was received, for keep-alive
3291 * processing. Note, we delay getting the time until now in the hope that
3292 * the packet will be delivered to the user before any get time is required
3293 * (if not, then the time won't actually be re-evaluated here). */
3294 call->lastReceiveTime = clock_Sec();
3295 MUTEX_EXIT(&call->lock);
3296 MUTEX_ENTER(&rx_refcnt_mutex);
3298 MUTEX_EXIT(&rx_refcnt_mutex);
3302 /* return true if this is an "interesting" connection from the point of view
3303 of someone trying to debug the system */
3305 rxi_IsConnInteresting(struct rx_connection *aconn)
3308 struct rx_call *tcall;
3310 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3313 for (i = 0; i < RX_MAXCALLS; i++) {
3314 tcall = aconn->call[i];
3316 if ((tcall->state == RX_STATE_PRECALL)
3317 || (tcall->state == RX_STATE_ACTIVE))
3319 if ((tcall->mode == RX_MODE_SENDING)
3320 || (tcall->mode == RX_MODE_RECEIVING))
3328 /* if this is one of the last few packets AND it wouldn't be used by the
3329 receiving call to immediately satisfy a read request, then drop it on
3330 the floor, since accepting it might prevent a lock-holding thread from
3331 making progress in its reading. If a call has been cleared while in
3332 the precall state then ignore all subsequent packets until the call
3333 is assigned to a thread. */
3336 TooLow(struct rx_packet *ap, struct rx_call *acall)
3340 MUTEX_ENTER(&rx_quota_mutex);
3341 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3342 && (acall->state == RX_STATE_PRECALL))
3343 || ((rx_nFreePackets < rxi_dataQuota + 2)
3344 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3345 && (acall->flags & RX_CALL_READER_WAIT)))) {
3348 MUTEX_EXIT(&rx_quota_mutex);
3354 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3356 struct rx_connection *conn = arg1;
3357 struct rx_call *acall = arg2;
3358 struct rx_call *call = acall;
3359 struct clock when, now;
3362 MUTEX_ENTER(&conn->conn_data_lock);
3363 conn->checkReachEvent = NULL;
3364 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3366 MUTEX_ENTER(&rx_refcnt_mutex);
3368 MUTEX_EXIT(&rx_refcnt_mutex);
3370 MUTEX_EXIT(&conn->conn_data_lock);
3374 MUTEX_ENTER(&conn->conn_call_lock);
3375 MUTEX_ENTER(&conn->conn_data_lock);
3376 for (i = 0; i < RX_MAXCALLS; i++) {
3377 struct rx_call *tc = conn->call[i];
3378 if (tc && tc->state == RX_STATE_PRECALL) {
3384 /* Indicate that rxi_CheckReachEvent is no longer running by
3385 * clearing the flag. Must be atomic under conn_data_lock to
3386 * avoid a new call slipping by: rxi_CheckConnReach holds
3387 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3389 conn->flags &= ~RX_CONN_ATTACHWAIT;
3390 MUTEX_EXIT(&conn->conn_data_lock);
3391 MUTEX_EXIT(&conn->conn_call_lock);
3396 MUTEX_ENTER(&call->lock);
3397 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3399 MUTEX_EXIT(&call->lock);
3401 clock_GetTime(&now);
3403 when.sec += RX_CHECKREACH_TIMEOUT;
3404 MUTEX_ENTER(&conn->conn_data_lock);
3405 if (!conn->checkReachEvent) {
3406 MUTEX_ENTER(&rx_refcnt_mutex);
3408 MUTEX_EXIT(&rx_refcnt_mutex);
3409 conn->checkReachEvent =
3410 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3413 MUTEX_EXIT(&conn->conn_data_lock);
3419 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3421 struct rx_service *service = conn->service;
3422 struct rx_peer *peer = conn->peer;
3423 afs_uint32 now, lastReach;
3425 if (service->checkReach == 0)
3429 MUTEX_ENTER(&peer->peer_lock);
3430 lastReach = peer->lastReachTime;
3431 MUTEX_EXIT(&peer->peer_lock);
3432 if (now - lastReach < RX_CHECKREACH_TTL)
3435 MUTEX_ENTER(&conn->conn_data_lock);
3436 if (conn->flags & RX_CONN_ATTACHWAIT) {
3437 MUTEX_EXIT(&conn->conn_data_lock);
3440 conn->flags |= RX_CONN_ATTACHWAIT;
3441 MUTEX_EXIT(&conn->conn_data_lock);
3442 if (!conn->checkReachEvent)
3443 rxi_CheckReachEvent(NULL, conn, call);
3448 /* try to attach call, if authentication is complete */
3450 TryAttach(struct rx_call *acall, osi_socket socket,
3451 int *tnop, struct rx_call **newcallp,
3454 struct rx_connection *conn = acall->conn;
3456 if (conn->type == RX_SERVER_CONNECTION
3457 && acall->state == RX_STATE_PRECALL) {
3458 /* Don't attach until we have any req'd. authentication. */
3459 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3460 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3461 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3462 /* Note: this does not necessarily succeed; there
3463 * may not any proc available
3466 rxi_ChallengeOn(acall->conn);
3471 /* A data packet has been received off the interface. This packet is
3472 * appropriate to the call (the call is in the right state, etc.). This
3473 * routine can return a packet to the caller, for re-use */
3476 rxi_ReceiveDataPacket(struct rx_call *call,
3477 struct rx_packet *np, int istack,
3478 osi_socket socket, afs_uint32 host, u_short port,
3479 int *tnop, struct rx_call **newcallp)
3481 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3486 afs_uint32 serial=0, flags=0;
3488 struct rx_packet *tnp;
3489 struct clock when, now;
3490 if (rx_stats_active)
3491 rx_atomic_inc(&rx_stats.dataPacketsRead);
3494 /* If there are no packet buffers, drop this new packet, unless we can find
3495 * packet buffers from inactive calls */
3497 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3498 MUTEX_ENTER(&rx_freePktQ_lock);
3499 rxi_NeedMorePackets = TRUE;
3500 MUTEX_EXIT(&rx_freePktQ_lock);
3501 if (rx_stats_active)
3502 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3503 call->rprev = np->header.serial;
3504 rxi_calltrace(RX_TRACE_DROP, call);
3505 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3507 rxi_ClearReceiveQueue(call);
3508 clock_GetTime(&now);
3510 clock_Add(&when, &rx_softAckDelay);
3511 if (!call->delayedAckEvent
3512 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3513 rxevent_Cancel(call->delayedAckEvent, call,
3514 RX_CALL_REFCOUNT_DELAY);
3515 MUTEX_ENTER(&rx_refcnt_mutex);
3516 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3517 MUTEX_EXIT(&rx_refcnt_mutex);
3519 call->delayedAckEvent =
3520 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3522 /* we've damaged this call already, might as well do it in. */
3528 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3529 * packet is one of several packets transmitted as a single
3530 * datagram. Do not send any soft or hard acks until all packets
3531 * in a jumbogram have been processed. Send negative acks right away.
3533 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3534 /* tnp is non-null when there are more packets in the
3535 * current jumbo gram */
3542 seq = np->header.seq;
3543 serial = np->header.serial;
3544 flags = np->header.flags;
3546 /* If the call is in an error state, send an abort message */
3548 return rxi_SendCallAbort(call, np, istack, 0);
3550 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3551 * AFS 3.5 jumbogram. */
3552 if (flags & RX_JUMBO_PACKET) {
3553 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3558 if (np->header.spare != 0) {
3559 MUTEX_ENTER(&call->conn->conn_data_lock);
3560 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3561 MUTEX_EXIT(&call->conn->conn_data_lock);
3564 /* The usual case is that this is the expected next packet */
3565 if (seq == call->rnext) {
3567 /* Check to make sure it is not a duplicate of one already queued */
3568 if (queue_IsNotEmpty(&call->rq)
3569 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3570 if (rx_stats_active)
3571 rx_atomic_inc(&rx_stats.dupPacketsRead);
3572 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3573 rxevent_Cancel(call->delayedAckEvent, call,
3574 RX_CALL_REFCOUNT_DELAY);
3575 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3581 /* It's the next packet. Stick it on the receive queue
3582 * for this call. Set newPackets to make sure we wake
3583 * the reader once all packets have been processed */
3584 #ifdef RX_TRACK_PACKETS
3585 np->flags |= RX_PKTFLAG_RQ;
3587 queue_Prepend(&call->rq, np);
3588 #ifdef RXDEBUG_PACKET
3590 #endif /* RXDEBUG_PACKET */
3592 np = NULL; /* We can't use this anymore */
3595 /* If an ack is requested then set a flag to make sure we
3596 * send an acknowledgement for this packet */
3597 if (flags & RX_REQUEST_ACK) {
3598 ackNeeded = RX_ACK_REQUESTED;
3601 /* Keep track of whether we have received the last packet */
3602 if (flags & RX_LAST_PACKET) {
3603 call->flags |= RX_CALL_HAVE_LAST;
3607 /* Check whether we have all of the packets for this call */
3608 if (call->flags & RX_CALL_HAVE_LAST) {
3609 afs_uint32 tseq; /* temporary sequence number */
3610 struct rx_packet *tp; /* Temporary packet pointer */
3611 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3613 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3614 if (tseq != tp->header.seq)
3616 if (tp->header.flags & RX_LAST_PACKET) {
3617 call->flags |= RX_CALL_RECEIVE_DONE;
3624 /* Provide asynchronous notification for those who want it
3625 * (e.g. multi rx) */
3626 if (call->arrivalProc) {
3627 (*call->arrivalProc) (call, call->arrivalProcHandle,
3628 call->arrivalProcArg);
3629 call->arrivalProc = (void (*)())0;
3632 /* Update last packet received */
3635 /* If there is no server process serving this call, grab
3636 * one, if available. We only need to do this once. If a
3637 * server thread is available, this thread becomes a server
3638 * thread and the server thread becomes a listener thread. */
3640 TryAttach(call, socket, tnop, newcallp, 0);
3643 /* This is not the expected next packet. */
3645 /* Determine whether this is a new or old packet, and if it's
3646 * a new one, whether it fits into the current receive window.
3647 * Also figure out whether the packet was delivered in sequence.
3648 * We use the prev variable to determine whether the new packet
3649 * is the successor of its immediate predecessor in the
3650 * receive queue, and the missing flag to determine whether
3651 * any of this packets predecessors are missing. */
3653 afs_uint32 prev; /* "Previous packet" sequence number */
3654 struct rx_packet *tp; /* Temporary packet pointer */
3655 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3656 int missing; /* Are any predecessors missing? */
3658 /* If the new packet's sequence number has been sent to the
3659 * application already, then this is a duplicate */
3660 if (seq < call->rnext) {
3661 if (rx_stats_active)
3662 rx_atomic_inc(&rx_stats.dupPacketsRead);
3663 rxevent_Cancel(call->delayedAckEvent, call,
3664 RX_CALL_REFCOUNT_DELAY);
3665 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3671 /* If the sequence number is greater than what can be
3672 * accomodated by the current window, then send a negative
3673 * acknowledge and drop the packet */
3674 if ((call->rnext + call->rwind) <= seq) {
3675 rxevent_Cancel(call->delayedAckEvent, call,
3676 RX_CALL_REFCOUNT_DELAY);
3677 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3684 /* Look for the packet in the queue of old received packets */
3685 for (prev = call->rnext - 1, missing =
3686 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3687 /*Check for duplicate packet */
3688 if (seq == tp->header.seq) {
3689 if (rx_stats_active)
3690 rx_atomic_inc(&rx_stats.dupPacketsRead);
3691 rxevent_Cancel(call->delayedAckEvent, call,
3692 RX_CALL_REFCOUNT_DELAY);
3693 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3699 /* If we find a higher sequence packet, break out and
3700 * insert the new packet here. */
3701 if (seq < tp->header.seq)
3703 /* Check for missing packet */
3704 if (tp->header.seq != prev + 1) {
3708 prev = tp->header.seq;
3711 /* Keep track of whether we have received the last packet. */
3712 if (flags & RX_LAST_PACKET) {
3713 call->flags |= RX_CALL_HAVE_LAST;
3716 /* It's within the window: add it to the the receive queue.
3717 * tp is left by the previous loop either pointing at the
3718 * packet before which to insert the new packet, or at the
3719 * queue head if the queue is empty or the packet should be
3721 #ifdef RX_TRACK_PACKETS
3722 np->flags |= RX_PKTFLAG_RQ;
3724 #ifdef RXDEBUG_PACKET
3726 #endif /* RXDEBUG_PACKET */
3727 queue_InsertBefore(tp, np);
3731 /* Check whether we have all of the packets for this call */
3732 if ((call->flags & RX_CALL_HAVE_LAST)
3733 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3734 afs_uint32 tseq; /* temporary sequence number */
3737 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3738 if (tseq != tp->header.seq)
3740 if (tp->header.flags & RX_LAST_PACKET) {
3741 call->flags |= RX_CALL_RECEIVE_DONE;
3748 /* We need to send an ack of the packet is out of sequence,
3749 * or if an ack was requested by the peer. */
3750 if (seq != prev + 1 || missing) {
3751 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3752 } else if (flags & RX_REQUEST_ACK) {
3753 ackNeeded = RX_ACK_REQUESTED;
3756 /* Acknowledge the last packet for each call */
3757 if (flags & RX_LAST_PACKET) {
3768 * If the receiver is waiting for an iovec, fill the iovec
3769 * using the data from the receive queue */
3770 if (call->flags & RX_CALL_IOVEC_WAIT) {
3771 didHardAck = rxi_FillReadVec(call, serial);
3772 /* the call may have been aborted */
3781 /* Wakeup the reader if any */
3782 if ((call->flags & RX_CALL_READER_WAIT)
3783 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3784 || (call->iovNext >= call->iovMax)
3785 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3786 call->flags &= ~RX_CALL_READER_WAIT;
3787 #ifdef RX_ENABLE_LOCKS
3788 CV_BROADCAST(&call->cv_rq);
3790 osi_rxWakeup(&call->rq);
3796 * Send an ack when requested by the peer, or once every
3797 * rxi_SoftAckRate packets until the last packet has been
3798 * received. Always send a soft ack for the last packet in
3799 * the server's reply.
3801 * If we have received all of the packets for the call
3802 * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3803 * the peer can empty its packet queue and cancel all resend
3806 if (call->flags & RX_CALL_RECEIVE_DONE) {
3807 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3808 rxi_AckAll(NULL, call, 0);
3809 } else if (ackNeeded) {
3810 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3811 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3812 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3813 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3814 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3815 } else if (call->nSoftAcks) {
3816 clock_GetTime(&now);
3818 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3819 clock_Add(&when, &rx_lastAckDelay);
3821 clock_Add(&when, &rx_softAckDelay);
3823 if (!call->delayedAckEvent
3824 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3825 rxevent_Cancel(call->delayedAckEvent, call,
3826 RX_CALL_REFCOUNT_DELAY);
3827 MUTEX_ENTER(&rx_refcnt_mutex);
3828 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3829 MUTEX_EXIT(&rx_refcnt_mutex);
3830 call->delayedAckEvent =
3831 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3839 static void rxi_ComputeRate();
3843 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3845 struct rx_peer *peer = conn->peer;
3847 MUTEX_ENTER(&peer->peer_lock);
3848 peer->lastReachTime = clock_Sec();
3849 MUTEX_EXIT(&peer->peer_lock);
3851 MUTEX_ENTER(&conn->conn_data_lock);
3852 if (conn->flags & RX_CONN_ATTACHWAIT) {
3855 conn->flags &= ~RX_CONN_ATTACHWAIT;
3856 MUTEX_EXIT(&conn->conn_data_lock);
3858 for (i = 0; i < RX_MAXCALLS; i++) {
3859 struct rx_call *call = conn->call[i];
3862 MUTEX_ENTER(&call->lock);
3863 /* tnop can be null if newcallp is null */
3864 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3866 MUTEX_EXIT(&call->lock);
3870 MUTEX_EXIT(&conn->conn_data_lock);
3873 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3875 rx_ack_reason(int reason)
3878 case RX_ACK_REQUESTED:
3880 case RX_ACK_DUPLICATE:
3882 case RX_ACK_OUT_OF_SEQUENCE:
3884 case RX_ACK_EXCEEDS_WINDOW:
3886 case RX_ACK_NOSPACE:
3890 case RX_ACK_PING_RESPONSE:
3903 /* rxi_ComputePeerNetStats
3905 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3906 * estimates (like RTT and throughput) based on ack packets. Caller
3907 * must ensure that the packet in question is the right one (i.e.
3908 * serial number matches).
3911 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3912 struct rx_ackPacket *ap, struct rx_packet *np,
3915 struct rx_peer *peer = call->conn->peer;
3917 /* Use RTT if not delayed by client and
3918 * ignore packets that were retransmitted. */
3919 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3920 ap->reason != RX_ACK_DELAY &&
3921 clock_Eq(&p->timeSent, &p->firstSent))
3922 rxi_ComputeRoundTripTime(p, &p->timeSent, peer, now);
3924 rxi_ComputeRate(peer, call, p, np, ap->reason);
3928 /* The real smarts of the whole thing. */
3930 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3933 struct rx_ackPacket *ap;
3935 struct rx_packet *tp;
3936 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3937 struct rx_connection *conn = call->conn;
3938 struct rx_peer *peer = conn->peer;
3939 struct clock now; /* Current time, for RTT calculations */
3942 /* because there are CM's that are bogus, sending weird values for this. */
3943 afs_uint32 skew = 0;
3948 int newAckCount = 0;
3949 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3950 int pktsize = 0; /* Set if we need to update the peer mtu */
3951 int conn_data_locked = 0;
3953 if (rx_stats_active)
3954 rx_atomic_inc(&rx_stats.ackPacketsRead);
3955 ap = (struct rx_ackPacket *)rx_DataOf(np);
3956 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3958 return np; /* truncated ack packet */
3960 /* depends on ack packet struct */
3961 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3962 first = ntohl(ap->firstPacket);
3963 serial = ntohl(ap->serial);
3964 /* temporarily disabled -- needs to degrade over time
3965 * skew = ntohs(ap->maxSkew); */
3967 /* Ignore ack packets received out of order */
3968 if (first < call->tfirst) {
3972 if (np->header.flags & RX_SLOW_START_OK) {
3973 call->flags |= RX_CALL_SLOW_START_OK;
3976 if (ap->reason == RX_ACK_PING_RESPONSE)
3977 rxi_UpdatePeerReach(conn, call);
3979 if (conn->lastPacketSizeSeq) {
3980 MUTEX_ENTER(&conn->conn_data_lock);
3981 conn_data_locked = 1;
3982 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
3983 pktsize = conn->lastPacketSize;
3984 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
3987 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
3988 if (!conn_data_locked) {
3989 MUTEX_ENTER(&conn->conn_data_lock);
3990 conn_data_locked = 1;
3992 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
3993 /* process mtu ping ack */
3994 pktsize = conn->lastPingSize;
3995 conn->lastPingSizeSer = conn->lastPingSize = 0;
3999 if (conn_data_locked) {
4000 MUTEX_EXIT(&conn->conn_data_lock);
4001 conn_data_locked = 0;
4005 if (rxdebug_active) {
4009 len = _snprintf(msg, sizeof(msg),
4010 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4011 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4012 ntohl(ap->serial), ntohl(ap->previousPacket),
4013 (unsigned int)np->header.seq, (unsigned int)skew,
4014 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4018 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4019 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4023 OutputDebugString(msg);
4025 #else /* AFS_NT40_ENV */
4028 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4029 ap->reason, ntohl(ap->previousPacket),
4030 (unsigned int)np->header.seq, (unsigned int)serial,
4031 (unsigned int)skew, ntohl(ap->firstPacket));
4034 for (offset = 0; offset < nAcks; offset++)
4035 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4040 #endif /* AFS_NT40_ENV */
4043 MUTEX_ENTER(&peer->peer_lock);
4046 * Start somewhere. Can't assume we can send what we can receive,
4047 * but we are clearly receiving.
4049 if (!peer->maxPacketSize)
4050 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4052 if (pktsize > peer->maxPacketSize) {
4053 peer->maxPacketSize = pktsize;
4054 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4055 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4056 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4057 rxi_ScheduleGrowMTUEvent(call, 1);
4062 /* Update the outgoing packet skew value to the latest value of
4063 * the peer's incoming packet skew value. The ack packet, of
4064 * course, could arrive out of order, but that won't affect things
4066 peer->outPacketSkew = skew;
4068 /* Check for packets that no longer need to be transmitted, and
4069 * discard them. This only applies to packets positively
4070 * acknowledged as having been sent to the peer's upper level.
4071 * All other packets must be retained. So only packets with
4072 * sequence numbers < ap->firstPacket are candidates. */
4074 clock_GetTime(&now);
4076 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4077 if (tp->header.seq >= first)
4079 call->tfirst = tp->header.seq + 1;
4080 rxi_ComputePeerNetStats(call, tp, ap, np, &now);
4081 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4084 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4085 /* XXX Hack. Because we have to release the global rx lock when sending
4086 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4087 * in rxi_Start sending packets out because packets may move to the
4088 * freePacketQueue as result of being here! So we drop these packets until
4089 * we're safely out of the traversing. Really ugly!
4090 * To make it even uglier, if we're using fine grain locking, we can
4091 * set the ack bits in the packets and have rxi_Start remove the packets
4092 * when it's done transmitting.
4094 if (call->flags & RX_CALL_TQ_BUSY) {
4095 #ifdef RX_ENABLE_LOCKS
4096 tp->flags |= RX_PKTFLAG_ACKED;
4097 call->flags |= RX_CALL_TQ_SOME_ACKED;
4098 #else /* RX_ENABLE_LOCKS */
4100 #endif /* RX_ENABLE_LOCKS */
4102 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4105 #ifdef RX_TRACK_PACKETS
4106 tp->flags &= ~RX_PKTFLAG_TQ;
4108 #ifdef RXDEBUG_PACKET
4110 #endif /* RXDEBUG_PACKET */
4111 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4116 /* Give rate detector a chance to respond to ping requests */
4117 if (ap->reason == RX_ACK_PING_RESPONSE) {
4118 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4122 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4124 /* Now go through explicit acks/nacks and record the results in
4125 * the waiting packets. These are packets that can't be released
4126 * yet, even with a positive acknowledge. This positive
4127 * acknowledge only means the packet has been received by the
4128 * peer, not that it will be retained long enough to be sent to
4129 * the peer's upper level. In addition, reset the transmit timers
4130 * of any missing packets (those packets that must be missing
4131 * because this packet was out of sequence) */
4133 call->nSoftAcked = 0;
4134 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4135 /* Update round trip time if the ack was stimulated on receipt
4137 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4138 #ifdef RX_ENABLE_LOCKS
4139 if (tp->header.seq >= first)
4140 #endif /* RX_ENABLE_LOCKS */
4141 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4142 rxi_ComputePeerNetStats(call, tp, ap, np, &now);
4144 /* Set the acknowledge flag per packet based on the
4145 * information in the ack packet. An acknowlegded packet can
4146 * be downgraded when the server has discarded a packet it
4147 * soacked previously, or when an ack packet is received
4148 * out of sequence. */
4149 if (tp->header.seq < first) {
4150 /* Implicit ack information */
4151 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4154 tp->flags |= RX_PKTFLAG_ACKED;
4155 } else if (tp->header.seq < first + nAcks) {
4156 /* Explicit ack information: set it in the packet appropriately */
4157 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4158 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4160 tp->flags |= RX_PKTFLAG_ACKED;
4167 } else /* RX_ACK_TYPE_NACK */ {
4168 tp->flags &= ~RX_PKTFLAG_ACKED;
4172 tp->flags &= ~RX_PKTFLAG_ACKED;
4177 * Following the suggestion of Phil Kern, we back off the peer's
4178 * timeout value for future packets until a successful response
4179 * is received for an initial transmission.
4181 if (missing && !peer->backedOff) {
4182 struct clock c = peer->timeout;
4183 struct clock max_to = {3, 0};
4185 clock_Add(&peer->timeout, &c);
4186 if (clock_Gt(&peer->timeout, &max_to))
4187 peer->timeout = max_to;
4188 peer->backedOff = 1;
4191 /* If packet isn't yet acked, and it has been transmitted at least
4192 * once, reset retransmit time using latest timeout
4193 * ie, this should readjust the retransmit timer for all outstanding
4194 * packets... So we don't just retransmit when we should know better*/
4196 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4197 tp->retryTime = tp->timeSent;
4198 clock_Add(&tp->retryTime, &peer->timeout);
4199 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4200 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4204 /* If the window has been extended by this acknowledge packet,
4205 * then wakeup a sender waiting in alloc for window space, or try
4206 * sending packets now, if he's been sitting on packets due to
4207 * lack of window space */
4208 if (call->tnext < (call->tfirst + call->twind)) {
4209 #ifdef RX_ENABLE_LOCKS
4210 CV_SIGNAL(&call->cv_twind);
4212 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4213 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4214 osi_rxWakeup(&call->twind);
4217 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4218 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4222 /* if the ack packet has a receivelen field hanging off it,
4223 * update our state */
4224 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4227 /* If the ack packet has a "recommended" size that is less than
4228 * what I am using now, reduce my size to match */
4229 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4230 (int)sizeof(afs_int32), &tSize);
4231 tSize = (afs_uint32) ntohl(tSize);
4232 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4234 /* Get the maximum packet size to send to this peer */
4235 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4237 tSize = (afs_uint32) ntohl(tSize);
4238 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4239 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4241 /* sanity check - peer might have restarted with different params.
4242 * If peer says "send less", dammit, send less... Peer should never
4243 * be unable to accept packets of the size that prior AFS versions would
4244 * send without asking. */
4245 if (peer->maxMTU != tSize) {
4246 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4248 peer->maxMTU = tSize;
4249 peer->MTU = MIN(tSize, peer->MTU);
4250 call->MTU = MIN(call->MTU, tSize);
4253 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4256 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4257 (int)sizeof(afs_int32), &tSize);
4258 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4259 if (tSize < call->twind) { /* smaller than our send */
4260 call->twind = tSize; /* window, we must send less... */
4261 call->ssthresh = MIN(call->twind, call->ssthresh);
4262 call->conn->twind[call->channel] = call->twind;
4265 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4266 * network MTU confused with the loopback MTU. Calculate the
4267 * maximum MTU here for use in the slow start code below.
4269 /* Did peer restart with older RX version? */
4270 if (peer->maxDgramPackets > 1) {
4271 peer->maxDgramPackets = 1;
4273 } else if (np->length >=
4274 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4277 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4278 sizeof(afs_int32), &tSize);
4279 tSize = (afs_uint32) ntohl(tSize);
4281 * As of AFS 3.5 we set the send window to match the receive window.
4283 if (tSize < call->twind) {
4284 call->twind = tSize;
4285 call->conn->twind[call->channel] = call->twind;
4286 call->ssthresh = MIN(call->twind, call->ssthresh);
4287 } else if (tSize > call->twind) {
4288 call->twind = tSize;
4289 call->conn->twind[call->channel] = call->twind;
4293 * As of AFS 3.5, a jumbogram is more than one fixed size
4294 * packet transmitted in a single UDP datagram. If the remote
4295 * MTU is smaller than our local MTU then never send a datagram
4296 * larger than the natural MTU.
4299 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4300 (int)sizeof(afs_int32), &tSize);
4301 maxDgramPackets = (afs_uint32) ntohl(tSize);
4302 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4304 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4305 maxDgramPackets = MIN(maxDgramPackets, tSize);
4306 if (maxDgramPackets > 1) {
4307 peer->maxDgramPackets = maxDgramPackets;
4308 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4310 peer->maxDgramPackets = 1;
4311 call->MTU = peer->natMTU;
4313 } else if (peer->maxDgramPackets > 1) {
4314 /* Restarted with lower version of RX */
4315 peer->maxDgramPackets = 1;
4317 } else if (peer->maxDgramPackets > 1
4318 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4319 /* Restarted with lower version of RX */
4320 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4321 peer->natMTU = OLD_MAX_PACKET_SIZE;
4322 peer->MTU = OLD_MAX_PACKET_SIZE;
4323 peer->maxDgramPackets = 1;
4324 peer->nDgramPackets = 1;
4326 call->MTU = OLD_MAX_PACKET_SIZE;
4331 * Calculate how many datagrams were successfully received after
4332 * the first missing packet and adjust the negative ack counter
4337 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4338 if (call->nNacks < nNacked) {
4339 call->nNacks = nNacked;
4342 call->nAcks += newAckCount;
4346 if (call->flags & RX_CALL_FAST_RECOVER) {
4348 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4350 call->flags &= ~RX_CALL_FAST_RECOVER;
4351 call->cwind = call->nextCwind;
4352 call->nextCwind = 0;
4355 call->nCwindAcks = 0;
4356 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4357 /* Three negative acks in a row trigger congestion recovery */
4358 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4359 MUTEX_EXIT(&peer->peer_lock);
4360 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4361 /* someone else is waiting to start recovery */
4364 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4365 rxi_WaitforTQBusy(call);
4366 MUTEX_ENTER(&peer->peer_lock);
4367 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4368 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4369 call->flags |= RX_CALL_FAST_RECOVER;
4370 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4372 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4373 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4374 call->nextCwind = call->ssthresh;
4377 peer->MTU = call->MTU;
4378 peer->cwind = call->nextCwind;
4379 peer->nDgramPackets = call->nDgramPackets;
4381 call->congestSeq = peer->congestSeq;
4382 /* Reset the resend times on the packets that were nacked
4383 * so we will retransmit as soon as the window permits*/
4384 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4386 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4387 clock_Zero(&tp->retryTime);
4389 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4394 /* If cwind is smaller than ssthresh, then increase
4395 * the window one packet for each ack we receive (exponential
4397 * If cwind is greater than or equal to ssthresh then increase
4398 * the congestion window by one packet for each cwind acks we
4399 * receive (linear growth). */
4400 if (call->cwind < call->ssthresh) {
4402 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4403 call->nCwindAcks = 0;
4405 call->nCwindAcks += newAckCount;
4406 if (call->nCwindAcks >= call->cwind) {
4407 call->nCwindAcks = 0;
4408 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4412 * If we have received several acknowledgements in a row then
4413 * it is time to increase the size of our datagrams
4415 if ((int)call->nAcks > rx_nDgramThreshold) {
4416 if (peer->maxDgramPackets > 1) {
4417 if (call->nDgramPackets < peer->maxDgramPackets) {
4418 call->nDgramPackets++;
4420 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4421 } else if (call->MTU < peer->maxMTU) {
4422 /* don't upgrade if we can't handle it */
4423 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4424 call->MTU = peer->ifMTU;
4426 call->MTU += peer->natMTU;
4427 call->MTU = MIN(call->MTU, peer->maxMTU);
4434 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4436 /* Servers need to hold the call until all response packets have
4437 * been acknowledged. Soft acks are good enough since clients
4438 * are not allowed to clear their receive queues. */
4439 if (call->state == RX_STATE_HOLD
4440 && call->tfirst + call->nSoftAcked >= call->tnext) {
4441 call->state = RX_STATE_DALLY;
4442 rxi_ClearTransmitQueue(call, 0);
4443 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4444 } else if (!queue_IsEmpty(&call->tq)) {
4445 rxi_Start(0, call, 0, istack);
4450 /* Received a response to a challenge packet */
4452 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4453 struct rx_packet *np, int istack)
4457 /* Ignore the packet if we're the client */
4458 if (conn->type == RX_CLIENT_CONNECTION)
4461 /* If already authenticated, ignore the packet (it's probably a retry) */
4462 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4465 /* Otherwise, have the security object evaluate the response packet */
4466 error = RXS_CheckResponse(conn->securityObject, conn, np);
4468 /* If the response is invalid, reset the connection, sending
4469 * an abort to the peer */
4473 rxi_ConnectionError(conn, error);
4474 MUTEX_ENTER(&conn->conn_data_lock);
4475 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4476 MUTEX_EXIT(&conn->conn_data_lock);
4479 /* If the response is valid, any calls waiting to attach
4480 * servers can now do so */
4483 for (i = 0; i < RX_MAXCALLS; i++) {
4484 struct rx_call *call = conn->call[i];
4486 MUTEX_ENTER(&call->lock);
4487 if (call->state == RX_STATE_PRECALL)
4488 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4489 /* tnop can be null if newcallp is null */
4490 MUTEX_EXIT(&call->lock);
4494 /* Update the peer reachability information, just in case
4495 * some calls went into attach-wait while we were waiting
4496 * for authentication..
4498 rxi_UpdatePeerReach(conn, NULL);
4503 /* A client has received an authentication challenge: the security
4504 * object is asked to cough up a respectable response packet to send
4505 * back to the server. The server is responsible for retrying the
4506 * challenge if it fails to get a response. */
4509 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4510 struct rx_packet *np, int istack)
4514 /* Ignore the challenge if we're the server */
4515 if (conn->type == RX_SERVER_CONNECTION)
4518 /* Ignore the challenge if the connection is otherwise idle; someone's
4519 * trying to use us as an oracle. */
4520 if (!rxi_HasActiveCalls(conn))
4523 /* Send the security object the challenge packet. It is expected to fill
4524 * in the response. */
4525 error = RXS_GetResponse(conn->securityObject, conn, np);
4527 /* If the security object is unable to return a valid response, reset the
4528 * connection and send an abort to the peer. Otherwise send the response
4529 * packet to the peer connection. */
4531 rxi_ConnectionError(conn, error);
4532 MUTEX_ENTER(&conn->conn_data_lock);
4533 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4534 MUTEX_EXIT(&conn->conn_data_lock);
4536 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4537 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4543 /* Find an available server process to service the current request in
4544 * the given call structure. If one isn't available, queue up this
4545 * call so it eventually gets one */
4547 rxi_AttachServerProc(struct rx_call *call,
4548 osi_socket socket, int *tnop,
4549 struct rx_call **newcallp)
4551 struct rx_serverQueueEntry *sq;
4552 struct rx_service *service = call->conn->service;
4555 /* May already be attached */
4556 if (call->state == RX_STATE_ACTIVE)
4559 MUTEX_ENTER(&rx_serverPool_lock);
4561 haveQuota = QuotaOK(service);
4562 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4563 /* If there are no processes available to service this call,
4564 * put the call on the incoming call queue (unless it's
4565 * already on the queue).
4567 #ifdef RX_ENABLE_LOCKS
4569 ReturnToServerPool(service);
4570 #endif /* RX_ENABLE_LOCKS */
4572 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4573 call->flags |= RX_CALL_WAIT_PROC;
4574 rx_atomic_inc(&rx_nWaiting);
4575 rx_atomic_inc(&rx_nWaited);
4576 rxi_calltrace(RX_CALL_ARRIVAL, call);
4577 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4578 queue_Append(&rx_incomingCallQueue, call);
4581 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4583 /* If hot threads are enabled, and both newcallp and sq->socketp
4584 * are non-null, then this thread will process the call, and the
4585 * idle server thread will start listening on this threads socket.
4588 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4591 *sq->socketp = socket;
4592 clock_GetTime(&call->startTime);
4593 MUTEX_ENTER(&rx_refcnt_mutex);
4594 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4595 MUTEX_EXIT(&rx_refcnt_mutex);
4599 if (call->flags & RX_CALL_WAIT_PROC) {
4600 /* Conservative: I don't think this should happen */
4601 call->flags &= ~RX_CALL_WAIT_PROC;
4602 if (queue_IsOnQueue(call)) {
4605 rx_atomic_dec(&rx_nWaiting);
4608 call->state = RX_STATE_ACTIVE;
4609 call->mode = RX_MODE_RECEIVING;
4610 #ifdef RX_KERNEL_TRACE
4612 int glockOwner = ISAFS_GLOCK();
4615 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4616 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4622 if (call->flags & RX_CALL_CLEARED) {
4623 /* send an ack now to start the packet flow up again */
4624 call->flags &= ~RX_CALL_CLEARED;
4625 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4627 #ifdef RX_ENABLE_LOCKS
4630 service->nRequestsRunning++;
4631 MUTEX_ENTER(&rx_quota_mutex);
4632 if (service->nRequestsRunning <= service->minProcs)
4635 MUTEX_EXIT(&rx_quota_mutex);
4639 MUTEX_EXIT(&rx_serverPool_lock);
4642 /* Delay the sending of an acknowledge event for a short while, while
4643 * a new call is being prepared (in the case of a client) or a reply
4644 * is being prepared (in the case of a server). Rather than sending
4645 * an ack packet, an ACKALL packet is sent. */
4647 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4649 #ifdef RX_ENABLE_LOCKS
4651 MUTEX_ENTER(&call->lock);
4652 call->delayedAckEvent = NULL;
4653 MUTEX_ENTER(&rx_refcnt_mutex);
4654 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4655 MUTEX_EXIT(&rx_refcnt_mutex);
4657 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4658 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4660 MUTEX_EXIT(&call->lock);
4661 #else /* RX_ENABLE_LOCKS */
4663 call->delayedAckEvent = NULL;
4664 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4665 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4666 #endif /* RX_ENABLE_LOCKS */
4670 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4672 struct rx_call *call = arg1;
4673 #ifdef RX_ENABLE_LOCKS
4675 MUTEX_ENTER(&call->lock);
4676 if (event == call->delayedAckEvent)
4677 call->delayedAckEvent = NULL;
4678 MUTEX_ENTER(&rx_refcnt_mutex);
4679 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4680 MUTEX_EXIT(&rx_refcnt_mutex);
4682 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4684 MUTEX_EXIT(&call->lock);
4685 #else /* RX_ENABLE_LOCKS */
4687 call->delayedAckEvent = NULL;
4688 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4689 #endif /* RX_ENABLE_LOCKS */
4693 #ifdef RX_ENABLE_LOCKS
4694 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4695 * clearing them out.
4698 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4700 struct rx_packet *p, *tp;
4703 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4704 p->flags |= RX_PKTFLAG_ACKED;
4708 call->flags |= RX_CALL_TQ_CLEARME;
4709 call->flags |= RX_CALL_TQ_SOME_ACKED;
4712 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4713 call->tfirst = call->tnext;
4714 call->nSoftAcked = 0;
4716 if (call->flags & RX_CALL_FAST_RECOVER) {
4717 call->flags &= ~RX_CALL_FAST_RECOVER;
4718 call->cwind = call->nextCwind;
4719 call->nextCwind = 0;
4722 CV_SIGNAL(&call->cv_twind);
4724 #endif /* RX_ENABLE_LOCKS */
4726 /* Clear out the transmit queue for the current call (all packets have
4727 * been received by peer) */
4729 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4731 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4732 struct rx_packet *p, *tp;
4734 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4736 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4737 p->flags |= RX_PKTFLAG_ACKED;
4741 call->flags |= RX_CALL_TQ_CLEARME;
4742 call->flags |= RX_CALL_TQ_SOME_ACKED;
4745 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4746 #ifdef RXDEBUG_PACKET
4748 #endif /* RXDEBUG_PACKET */
4749 rxi_FreePackets(0, &call->tq);
4750 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
4751 #ifdef RX_ENABLE_LOCKS
4752 CV_BROADCAST(&call->cv_tq);
4753 #else /* RX_ENABLE_LOCKS */
4754 osi_rxWakeup(&call->tq);
4755 #endif /* RX_ENABLE_LOCKS */
4757 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4758 call->flags &= ~RX_CALL_TQ_CLEARME;
4760 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4762 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4763 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4764 call->nSoftAcked = 0;
4766 if (call->flags & RX_CALL_FAST_RECOVER) {
4767 call->flags &= ~RX_CALL_FAST_RECOVER;
4768 call->cwind = call->nextCwind;
4770 #ifdef RX_ENABLE_LOCKS
4771 CV_SIGNAL(&call->cv_twind);
4773 osi_rxWakeup(&call->twind);
4778 rxi_ClearReceiveQueue(struct rx_call *call)
4780 if (queue_IsNotEmpty(&call->rq)) {
4783 count = rxi_FreePackets(0, &call->rq);
4784 rx_packetReclaims += count;
4785 #ifdef RXDEBUG_PACKET
4787 if ( call->rqc != 0 )
4788 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0", call, call->rqc));
4790 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4792 if (call->state == RX_STATE_PRECALL) {
4793 call->flags |= RX_CALL_CLEARED;
4797 /* Send an abort packet for the specified call */
4799 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4800 int istack, int force)
4803 struct clock when, now;
4808 /* Clients should never delay abort messages */
4809 if (rx_IsClientConn(call->conn))
4812 if (call->abortCode != call->error) {
4813 call->abortCode = call->error;
4814 call->abortCount = 0;
4817 if (force || rxi_callAbortThreshhold == 0
4818 || call->abortCount < rxi_callAbortThreshhold) {
4819 if (call->delayedAbortEvent) {
4820 rxevent_Cancel(call->delayedAbortEvent, call,
4821 RX_CALL_REFCOUNT_ABORT);
4823 error = htonl(call->error);
4826 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4827 (char *)&error, sizeof(error), istack);
4828 } else if (!call->delayedAbortEvent) {
4829 clock_GetTime(&now);
4831 clock_Addmsec(&when, rxi_callAbortDelay);
4832 MUTEX_ENTER(&rx_refcnt_mutex);
4833 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4834 MUTEX_EXIT(&rx_refcnt_mutex);
4835 call->delayedAbortEvent =
4836 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4841 /* Send an abort packet for the specified connection. Packet is an
4842 * optional pointer to a packet that can be used to send the abort.
4843 * Once the number of abort messages reaches the threshhold, an
4844 * event is scheduled to send the abort. Setting the force flag
4845 * overrides sending delayed abort messages.
4847 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4848 * to send the abort packet.
4851 rxi_SendConnectionAbort(struct rx_connection *conn,
4852 struct rx_packet *packet, int istack, int force)
4855 struct clock when, now;
4860 /* Clients should never delay abort messages */
4861 if (rx_IsClientConn(conn))
4864 if (force || rxi_connAbortThreshhold == 0
4865 || conn->abortCount < rxi_connAbortThreshhold) {
4866 if (conn->delayedAbortEvent) {
4867 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4869 error = htonl(conn->error);
4871 MUTEX_EXIT(&conn->conn_data_lock);
4873 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4874 RX_PACKET_TYPE_ABORT, (char *)&error,
4875 sizeof(error), istack);
4876 MUTEX_ENTER(&conn->conn_data_lock);
4877 } else if (!conn->delayedAbortEvent) {
4878 clock_GetTime(&now);
4880 clock_Addmsec(&when, rxi_connAbortDelay);
4881 conn->delayedAbortEvent =
4882 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4887 /* Associate an error all of the calls owned by a connection. Called
4888 * with error non-zero. This is only for really fatal things, like
4889 * bad authentication responses. The connection itself is set in
4890 * error at this point, so that future packets received will be
4893 rxi_ConnectionError(struct rx_connection *conn,
4899 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d", conn, error));
4901 MUTEX_ENTER(&conn->conn_data_lock);
4902 if (conn->challengeEvent)
4903 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4904 if (conn->natKeepAliveEvent)
4905 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
4906 if (conn->checkReachEvent) {
4907 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4908 conn->checkReachEvent = 0;
4909 conn->flags &= ~RX_CONN_ATTACHWAIT;
4910 MUTEX_ENTER(&rx_refcnt_mutex);
4912 MUTEX_EXIT(&rx_refcnt_mutex);
4914 MUTEX_EXIT(&conn->conn_data_lock);
4915 for (i = 0; i < RX_MAXCALLS; i++) {
4916 struct rx_call *call = conn->call[i];
4918 MUTEX_ENTER(&call->lock);
4919 rxi_CallError(call, error);
4920 MUTEX_EXIT(&call->lock);
4923 conn->error = error;
4924 if (rx_stats_active)
4925 rx_atomic_inc(&rx_stats.fatalErrors);
4930 rxi_CallError(struct rx_call *call, afs_int32 error)
4933 osirx_AssertMine(&call->lock, "rxi_CallError");
4935 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d", call, error, call->error));
4937 error = call->error;
4939 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4940 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4941 rxi_ResetCall(call, 0);
4944 rxi_ResetCall(call, 0);
4946 call->error = error;
4949 /* Reset various fields in a call structure, and wakeup waiting
4950 * processes. Some fields aren't changed: state & mode are not
4951 * touched (these must be set by the caller), and bufptr, nLeft, and
4952 * nFree are not reset, since these fields are manipulated by
4953 * unprotected macros, and may only be reset by non-interrupting code.
4956 /* this code requires that call->conn be set properly as a pre-condition. */
4957 #endif /* ADAPT_WINDOW */
4960 rxi_ResetCall(struct rx_call *call, int newcall)
4963 struct rx_peer *peer;
4964 struct rx_packet *packet;
4966 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4968 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
4970 /* Notify anyone who is waiting for asynchronous packet arrival */
4971 if (call->arrivalProc) {
4972 (*call->arrivalProc) (call, call->arrivalProcHandle,
4973 call->arrivalProcArg);
4974 call->arrivalProc = (void (*)())0;
4977 if (call->delayedAbortEvent) {
4978 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4979 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4981 rxi_SendCallAbort(call, packet, 0, 1);
4982 rxi_FreePacket(packet);
4987 * Update the peer with the congestion information in this call
4988 * so other calls on this connection can pick up where this call
4989 * left off. If the congestion sequence numbers don't match then
4990 * another call experienced a retransmission.
4992 peer = call->conn->peer;
4993 MUTEX_ENTER(&peer->peer_lock);
4995 if (call->congestSeq == peer->congestSeq) {
4996 peer->cwind = MAX(peer->cwind, call->cwind);
4997 peer->MTU = MAX(peer->MTU, call->MTU);
4998 peer->nDgramPackets =
4999 MAX(peer->nDgramPackets, call->nDgramPackets);
5002 call->abortCode = 0;
5003 call->abortCount = 0;
5005 if (peer->maxDgramPackets > 1) {
5006 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5008 call->MTU = peer->MTU;
5010 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5011 call->ssthresh = rx_maxSendWindow;
5012 call->nDgramPackets = peer->nDgramPackets;
5013 call->congestSeq = peer->congestSeq;
5014 MUTEX_EXIT(&peer->peer_lock);
5016 flags = call->flags;
5017 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5018 rxi_WaitforTQBusy(call);
5019 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5021 rxi_ClearTransmitQueue(call, 1);
5022 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5023 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5027 rxi_ClearReceiveQueue(call);
5028 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5032 call->twind = call->conn->twind[call->channel];
5033 call->rwind = call->conn->rwind[call->channel];
5034 call->nSoftAcked = 0;
5035 call->nextCwind = 0;
5038 call->nCwindAcks = 0;
5039 call->nSoftAcks = 0;
5040 call->nHardAcks = 0;
5042 call->tfirst = call->rnext = call->tnext = 1;
5044 call->lastAcked = 0;
5045 call->localStatus = call->remoteStatus = 0;
5047 if (flags & RX_CALL_READER_WAIT) {
5048 #ifdef RX_ENABLE_LOCKS
5049 CV_BROADCAST(&call->cv_rq);
5051 osi_rxWakeup(&call->rq);
5054 if (flags & RX_CALL_WAIT_PACKETS) {
5055 MUTEX_ENTER(&rx_freePktQ_lock);
5056 rxi_PacketsUnWait(); /* XXX */
5057 MUTEX_EXIT(&rx_freePktQ_lock);
5059 #ifdef RX_ENABLE_LOCKS
5060 CV_SIGNAL(&call->cv_twind);
5062 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5063 osi_rxWakeup(&call->twind);
5066 #ifdef RX_ENABLE_LOCKS
5067 /* The following ensures that we don't mess with any queue while some
5068 * other thread might also be doing so. The call_queue_lock field is
5069 * is only modified under the call lock. If the call is in the process
5070 * of being removed from a queue, the call is not locked until the
5071 * the queue lock is dropped and only then is the call_queue_lock field
5072 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5073 * Note that any other routine which removes a call from a queue has to
5074 * obtain the queue lock before examing the queue and removing the call.
5076 if (call->call_queue_lock) {
5077 MUTEX_ENTER(call->call_queue_lock);
5078 if (queue_IsOnQueue(call)) {
5080 if (flags & RX_CALL_WAIT_PROC) {
5081 rx_atomic_dec(&rx_nWaiting);
5084 MUTEX_EXIT(call->call_queue_lock);
5085 CLEAR_CALL_QUEUE_LOCK(call);
5087 #else /* RX_ENABLE_LOCKS */
5088 if (queue_IsOnQueue(call)) {
5090 if (flags & RX_CALL_WAIT_PROC)
5091 rx_atomic_dec(&rx_nWaiting);
5093 #endif /* RX_ENABLE_LOCKS */
5095 rxi_KeepAliveOff(call);
5096 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5099 /* Send an acknowledge for the indicated packet (seq,serial) of the
5100 * indicated call, for the indicated reason (reason). This
5101 * acknowledge will specifically acknowledge receiving the packet, and
5102 * will also specify which other packets for this call have been
5103 * received. This routine returns the packet that was used to the
5104 * caller. The caller is responsible for freeing it or re-using it.
5105 * This acknowledgement also returns the highest sequence number
5106 * actually read out by the higher level to the sender; the sender
5107 * promises to keep around packets that have not been read by the
5108 * higher level yet (unless, of course, the sender decides to abort
5109 * the call altogether). Any of p, seq, serial, pflags, or reason may
5110 * be set to zero without ill effect. That is, if they are zero, they
5111 * will not convey any information.
5112 * NOW there is a trailer field, after the ack where it will safely be
5113 * ignored by mundanes, which indicates the maximum size packet this
5114 * host can swallow. */
5116 struct rx_packet *optionalPacket; use to send ack (or null)
5117 int seq; Sequence number of the packet we are acking
5118 int serial; Serial number of the packet
5119 int pflags; Flags field from packet header
5120 int reason; Reason an acknowledge was prompted
5124 rxi_SendAck(struct rx_call *call,
5125 struct rx_packet *optionalPacket, int serial, int reason,
5128 struct rx_ackPacket *ap;
5129 struct rx_packet *rqp;
5130 struct rx_packet *nxp; /* For queue_Scan */
5131 struct rx_packet *p;
5134 afs_uint32 padbytes = 0;
5135 #ifdef RX_ENABLE_TSFPQ
5136 struct rx_ts_info_t * rx_ts_info;
5140 * Open the receive window once a thread starts reading packets
5142 if (call->rnext > 1) {
5143 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5146 /* Don't attempt to grow MTU if this is a critical ping */
5147 if (reason == RX_ACK_MTU) {
5148 /* keep track of per-call attempts, if we're over max, do in small
5149 * otherwise in larger? set a size to increment by, decrease
5152 if (call->conn->peer->maxPacketSize &&
5153 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5155 padbytes = call->conn->peer->maxPacketSize+16;
5157 padbytes = call->conn->peer->maxMTU + 128;
5159 /* do always try a minimum size ping */
5160 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5162 /* subtract the ack payload */
5163 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5164 reason = RX_ACK_PING;
5167 call->nHardAcks = 0;
5168 call->nSoftAcks = 0;
5169 if (call->rnext > call->lastAcked)
5170 call->lastAcked = call->rnext;
5174 rx_computelen(p, p->length); /* reset length, you never know */
5175 } /* where that's been... */
5176 #ifdef RX_ENABLE_TSFPQ
5178 RX_TS_INFO_GET(rx_ts_info);
5179 if ((p = rx_ts_info->local_special_packet)) {
5180 rx_computelen(p, p->length);
5181 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5182 rx_ts_info->local_special_packet = p;
5183 } else { /* We won't send the ack, but don't panic. */
5184 return optionalPacket;
5188 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5189 /* We won't send the ack, but don't panic. */
5190 return optionalPacket;
5195 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5198 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5199 #ifndef RX_ENABLE_TSFPQ
5200 if (!optionalPacket)
5203 return optionalPacket;
5205 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5206 if (rx_Contiguous(p) < templ) {
5207 #ifndef RX_ENABLE_TSFPQ
5208 if (!optionalPacket)
5211 return optionalPacket;
5216 /* MTUXXX failing to send an ack is very serious. We should */
5217 /* try as hard as possible to send even a partial ack; it's */
5218 /* better than nothing. */
5219 ap = (struct rx_ackPacket *)rx_DataOf(p);
5220 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5221 ap->reason = reason;
5223 /* The skew computation used to be bogus, I think it's better now. */
5224 /* We should start paying attention to skew. XXX */
5225 ap->serial = htonl(serial);
5226 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5228 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
5229 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5231 /* No fear of running out of ack packet here because there can only be at most
5232 * one window full of unacknowledged packets. The window size must be constrained
5233 * to be less than the maximum ack size, of course. Also, an ack should always
5234 * fit into a single packet -- it should not ever be fragmented. */
5235 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5236 if (!rqp || !call->rq.next
5237 || (rqp->header.seq > (call->rnext + call->rwind))) {
5238 #ifndef RX_ENABLE_TSFPQ
5239 if (!optionalPacket)
5242 rxi_CallError(call, RX_CALL_DEAD);
5243 return optionalPacket;
5246 while (rqp->header.seq > call->rnext + offset)
5247 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5248 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5250 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5251 #ifndef RX_ENABLE_TSFPQ
5252 if (!optionalPacket)
5255 rxi_CallError(call, RX_CALL_DEAD);
5256 return optionalPacket;
5261 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5263 /* these are new for AFS 3.3 */
5264 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5265 templ = htonl(templ);
5266 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5267 templ = htonl(call->conn->peer->ifMTU);
5268 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5269 sizeof(afs_int32), &templ);
5271 /* new for AFS 3.4 */
5272 templ = htonl(call->rwind);
5273 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5274 sizeof(afs_int32), &templ);
5276 /* new for AFS 3.5 */
5277 templ = htonl(call->conn->peer->ifDgramPackets);
5278 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5279 sizeof(afs_int32), &templ);
5281 p->header.serviceId = call->conn->serviceId;
5282 p->header.cid = (call->conn->cid | call->channel);
5283 p->header.callNumber = *call->callNumber;
5285 p->header.securityIndex = call->conn->securityIndex;
5286 p->header.epoch = call->conn->epoch;
5287 p->header.type = RX_PACKET_TYPE_ACK;
5288 p->header.flags = RX_SLOW_START_OK;
5289 if (reason == RX_ACK_PING) {
5290 p->header.flags |= RX_REQUEST_ACK;
5292 clock_GetTime(&call->pingRequestTime);
5295 p->length = padbytes +
5296 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5299 /* not fast but we can potentially use this if truncated
5300 * fragments are delivered to figure out the mtu.
5302 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5303 sizeof(afs_int32), sizeof(afs_int32),
5307 if (call->conn->type == RX_CLIENT_CONNECTION)
5308 p->header.flags |= RX_CLIENT_INITIATED;
5312 if (rxdebug_active) {
5316 len = _snprintf(msg, sizeof(msg),
5317 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5318 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5319 ntohl(ap->serial), ntohl(ap->previousPacket),
5320 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5321 ap->nAcks, ntohs(ap->bufferSpace) );
5325 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5326 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5330 OutputDebugString(msg);
5332 #else /* AFS_NT40_ENV */
5334 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5335 ap->reason, ntohl(ap->previousPacket),
5336 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5338 for (offset = 0; offset < ap->nAcks; offset++)
5339 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5344 #endif /* AFS_NT40_ENV */
5347 int i, nbytes = p->length;
5349 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5350 if (nbytes <= p->wirevec[i].iov_len) {
5353 savelen = p->wirevec[i].iov_len;
5355 p->wirevec[i].iov_len = nbytes;
5357 rxi_Send(call, p, istack);
5358 p->wirevec[i].iov_len = savelen;
5362 nbytes -= p->wirevec[i].iov_len;
5365 if (rx_stats_active)
5366 rx_atomic_inc(&rx_stats.ackPacketsSent);
5367 #ifndef RX_ENABLE_TSFPQ
5368 if (!optionalPacket)
5371 return optionalPacket; /* Return packet for re-use by caller */
5374 /* Send all of the packets in the list in single datagram */
5376 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5377 int istack, int moreFlag, struct clock *now,
5378 struct clock *retryTime, int resending)
5383 struct rx_connection *conn = call->conn;
5384 struct rx_peer *peer = conn->peer;
5386 MUTEX_ENTER(&peer->peer_lock);
5389 peer->reSends += len;
5390 MUTEX_EXIT(&peer->peer_lock);
5392 if (rx_stats_active) {
5394 rx_atomic_add(&rx_stats.dataPacketsReSent, len);
5396 rx_atomic_add(&rx_stats.dataPacketsSent, len);
5399 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5403 /* Set the packet flags and schedule the resend events */
5404 /* Only request an ack for the last packet in the list */
5405 for (i = 0; i < len; i++) {
5406 list[i]->retryTime = *retryTime;
5407 if (list[i]->header.serial) {
5408 /* Exponentially backoff retry times */
5409 if (list[i]->backoff < MAXBACKOFF) {
5410 /* so it can't stay == 0 */
5411 list[i]->backoff = (list[i]->backoff << 1) + 1;
5414 clock_Addmsec(&(list[i]->retryTime),
5415 ((afs_uint32) list[i]->backoff) << 8);
5418 /* Wait a little extra for the ack on the last packet */
5419 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5420 clock_Addmsec(&(list[i]->retryTime), 400);
5423 /* Record the time sent */
5424 list[i]->timeSent = *now;
5426 /* Ask for an ack on retransmitted packets, on every other packet
5427 * if the peer doesn't support slow start. Ask for an ack on every
5428 * packet until the congestion window reaches the ack rate. */
5429 if (list[i]->header.serial) {
5432 /* improved RTO calculation- not Karn */
5433 list[i]->firstSent = *now;
5434 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5435 || (!(call->flags & RX_CALL_SLOW_START_OK)
5436 && (list[i]->header.seq & 1)))) {
5441 /* Tag this packet as not being the last in this group,
5442 * for the receiver's benefit */
5443 if (i < len - 1 || moreFlag) {
5444 list[i]->header.flags |= RX_MORE_PACKETS;
5447 /* Install the new retransmit time for the packet, and
5448 * record the time sent */
5449 list[i]->timeSent = *now;
5453 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5456 /* Since we're about to send a data packet to the peer, it's
5457 * safe to nuke any scheduled end-of-packets ack */
5458 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5460 MUTEX_EXIT(&call->lock);
5461 MUTEX_ENTER(&rx_refcnt_mutex);
5462 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5463 MUTEX_EXIT(&rx_refcnt_mutex);
5465 rxi_SendPacketList(call, conn, list, len, istack);
5467 rxi_SendPacket(call, conn, list[0], istack);
5469 MUTEX_ENTER(&call->lock);
5470 MUTEX_ENTER(&rx_refcnt_mutex);
5471 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5472 MUTEX_EXIT(&rx_refcnt_mutex);
5474 /* Update last send time for this call (for keep-alive
5475 * processing), and for the connection (so that we can discover
5476 * idle connections) */
5477 conn->lastSendTime = call->lastSendTime = clock_Sec();
5478 /* Let a set of retransmits trigger an idle timeout */
5480 call->lastSendData = call->lastSendTime;
5483 /* When sending packets we need to follow these rules:
5484 * 1. Never send more than maxDgramPackets in a jumbogram.
5485 * 2. Never send a packet with more than two iovecs in a jumbogram.
5486 * 3. Never send a retransmitted packet in a jumbogram.
5487 * 4. Never send more than cwind/4 packets in a jumbogram
5488 * We always keep the last list we should have sent so we
5489 * can set the RX_MORE_PACKETS flags correctly.
5492 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5493 int istack, struct clock *now, struct clock *retryTime,
5496 int i, cnt, lastCnt = 0;
5497 struct rx_packet **listP, **lastP = 0;
5498 struct rx_peer *peer = call->conn->peer;
5499 int morePackets = 0;
5501 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5502 /* Does the current packet force us to flush the current list? */
5504 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5505 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5507 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5509 /* If the call enters an error state stop sending, or if
5510 * we entered congestion recovery mode, stop sending */
5511 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5519 /* Add the current packet to the list if it hasn't been acked.
5520 * Otherwise adjust the list pointer to skip the current packet. */
5521 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5523 /* Do we need to flush the list? */
5524 if (cnt >= (int)peer->maxDgramPackets
5525 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5526 || list[i]->header.serial
5527 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5529 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5530 retryTime, resending);
5531 /* If the call enters an error state stop sending, or if
5532 * we entered congestion recovery mode, stop sending */
5534 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5539 listP = &list[i + 1];
5544 osi_Panic("rxi_SendList error");
5546 listP = &list[i + 1];
5550 /* Send the whole list when the call is in receive mode, when
5551 * the call is in eof mode, when we are in fast recovery mode,
5552 * and when we have the last packet */
5553 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5554 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5555 || (call->flags & RX_CALL_FAST_RECOVER)) {
5556 /* Check for the case where the current list contains
5557 * an acked packet. Since we always send retransmissions
5558 * in a separate packet, we only need to check the first
5559 * packet in the list */
5560 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5564 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5565 retryTime, resending);
5566 /* If the call enters an error state stop sending, or if
5567 * we entered congestion recovery mode, stop sending */
5568 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5572 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5575 } else if (lastCnt > 0) {
5576 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5581 #ifdef RX_ENABLE_LOCKS
5582 /* Call rxi_Start, below, but with the call lock held. */
5584 rxi_StartUnlocked(struct rxevent *event,
5585 void *arg0, void *arg1, int istack)
5587 struct rx_call *call = arg0;
5589 MUTEX_ENTER(&call->lock);
5590 rxi_Start(event, call, arg1, istack);
5591 MUTEX_EXIT(&call->lock);
5593 #endif /* RX_ENABLE_LOCKS */
5595 /* This routine is called when new packets are readied for
5596 * transmission and when retransmission may be necessary, or when the
5597 * transmission window or burst count are favourable. This should be
5598 * better optimized for new packets, the usual case, now that we've
5599 * got rid of queues of send packets. XXXXXXXXXXX */
5601 rxi_Start(struct rxevent *event,
5602 void *arg0, void *arg1, int istack)
5604 struct rx_call *call = arg0;
5606 struct rx_packet *p;
5607 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5608 struct rx_peer *peer = call->conn->peer;
5609 struct clock now, usenow, retryTime;
5615 /* If rxi_Start is being called as a result of a resend event,
5616 * then make sure that the event pointer is removed from the call
5617 * structure, since there is no longer a per-call retransmission
5619 if (event && event == call->resendEvent) {
5620 MUTEX_ENTER(&rx_refcnt_mutex);
5621 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5622 MUTEX_EXIT(&rx_refcnt_mutex);
5623 call->resendEvent = NULL;
5625 if (queue_IsEmpty(&call->tq)) {
5629 /* Timeouts trigger congestion recovery */
5630 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5631 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5632 /* someone else is waiting to start recovery */
5635 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5636 rxi_WaitforTQBusy(call);
5637 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5638 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5639 call->flags |= RX_CALL_FAST_RECOVER;
5640 if (peer->maxDgramPackets > 1) {
5641 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5643 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5645 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5646 call->nDgramPackets = 1;
5648 call->nextCwind = 1;
5651 MUTEX_ENTER(&peer->peer_lock);
5652 peer->MTU = call->MTU;
5653 peer->cwind = call->cwind;
5654 peer->nDgramPackets = 1;
5656 call->congestSeq = peer->congestSeq;
5657 MUTEX_EXIT(&peer->peer_lock);
5658 /* Clear retry times on packets. Otherwise, it's possible for
5659 * some packets in the queue to force resends at rates faster
5660 * than recovery rates.
5662 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5663 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5664 clock_Zero(&p->retryTime);
5669 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5670 if (rx_stats_active)
5671 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5676 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5677 /* Get clock to compute the re-transmit time for any packets
5678 * in this burst. Note, if we back off, it's reasonable to
5679 * back off all of the packets in the same manner, even if
5680 * some of them have been retransmitted more times than more
5682 * Do a dance to avoid blocking after setting now. */
5683 MUTEX_ENTER(&peer->peer_lock);
5684 retryTime = peer->timeout;
5685 MUTEX_EXIT(&peer->peer_lock);
5687 clock_GetTime(&now);
5688 clock_Add(&retryTime, &now);
5690 /* Send (or resend) any packets that need it, subject to
5691 * window restrictions and congestion burst control
5692 * restrictions. Ask for an ack on the last packet sent in
5693 * this burst. For now, we're relying upon the window being
5694 * considerably bigger than the largest number of packets that
5695 * are typically sent at once by one initial call to
5696 * rxi_Start. This is probably bogus (perhaps we should ask
5697 * for an ack when we're half way through the current
5698 * window?). Also, for non file transfer applications, this
5699 * may end up asking for an ack for every packet. Bogus. XXXX
5702 * But check whether we're here recursively, and let the other guy
5705 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5706 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5707 call->flags |= RX_CALL_TQ_BUSY;
5709 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5711 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5712 call->flags &= ~RX_CALL_NEED_START;
5713 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5715 maxXmitPackets = MIN(call->twind, call->cwind);
5716 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5717 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5718 /* We shouldn't be sending packets if a thread is waiting
5719 * to initiate congestion recovery */
5720 dpf(("call %d waiting to initiate fast recovery\n",
5721 *(call->callNumber)));
5725 && (call->flags & RX_CALL_FAST_RECOVER)) {
5726 /* Only send one packet during fast recovery */
5727 dpf(("call %d restricted to one packet per send during fast recovery\n",
5728 *(call->callNumber)));
5731 #ifdef RX_TRACK_PACKETS
5732 if ((p->flags & RX_PKTFLAG_FREE)
5733 || (!queue_IsEnd(&call->tq, nxp)
5734 && (nxp->flags & RX_PKTFLAG_FREE))
5735 || (p == (struct rx_packet *)&rx_freePacketQueue)
5736 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5737 osi_Panic("rxi_Start: xmit queue clobbered");
5740 if (p->flags & RX_PKTFLAG_ACKED) {
5741 /* Since we may block, don't trust this */
5742 usenow.sec = usenow.usec = 0;
5743 if (rx_stats_active)
5744 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
5745 continue; /* Ignore this packet if it has been acknowledged */
5748 /* Turn off all flags except these ones, which are the same
5749 * on each transmission */
5750 p->header.flags &= RX_PRESET_FLAGS;
5752 if (p->header.seq >=
5753 call->tfirst + MIN((int)call->twind,
5754 (int)(call->nSoftAcked +
5756 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5757 /* Note: if we're waiting for more window space, we can
5758 * still send retransmits; hence we don't return here, but
5759 * break out to schedule a retransmit event */
5760 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
5761 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
5766 /* Transmit the packet if it needs to be sent. */
5767 if (!clock_Lt(&now, &p->retryTime)) {
5768 if (nXmitPackets == maxXmitPackets) {
5769 rxi_SendXmitList(call, call->xmitList,
5770 nXmitPackets, istack, &now,
5771 &retryTime, resending);
5774 dpf(("call %d xmit packet %"AFS_PTR_FMT" now %u.%06u retryTime %u.%06u nextRetry %u.%06u\n",
5775 *(call->callNumber), p,
5777 p->retryTime.sec, p->retryTime.usec,
5778 retryTime.sec, retryTime.usec));
5779 call->xmitList[nXmitPackets++] = p;
5783 /* xmitList now hold pointers to all of the packets that are
5784 * ready to send. Now we loop to send the packets */
5785 if (nXmitPackets > 0) {
5786 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
5787 istack, &now, &retryTime, resending);
5790 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5792 * TQ references no longer protected by this flag; they must remain
5793 * protected by the global lock.
5795 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5796 call->flags &= ~RX_CALL_TQ_BUSY;
5797 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5798 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5799 call, call->tqWaiters, call->flags));
5800 #ifdef RX_ENABLE_LOCKS
5801 osirx_AssertMine(&call->lock, "rxi_Start start");
5802 CV_BROADCAST(&call->cv_tq);
5803 #else /* RX_ENABLE_LOCKS */
5804 osi_rxWakeup(&call->tq);
5805 #endif /* RX_ENABLE_LOCKS */
5810 /* We went into the error state while sending packets. Now is
5811 * the time to reset the call. This will also inform the using
5812 * process that the call is in an error state.
5814 if (rx_stats_active)
5815 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
5816 call->flags &= ~RX_CALL_TQ_BUSY;
5817 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5818 dpf(("call error %d while xmit %p has %d waiters and flags %d\n",
5819 call->error, call, call->tqWaiters, call->flags));
5820 #ifdef RX_ENABLE_LOCKS
5821 osirx_AssertMine(&call->lock, "rxi_Start middle");
5822 CV_BROADCAST(&call->cv_tq);
5823 #else /* RX_ENABLE_LOCKS */
5824 osi_rxWakeup(&call->tq);
5825 #endif /* RX_ENABLE_LOCKS */
5827 rxi_CallError(call, call->error);
5830 #ifdef RX_ENABLE_LOCKS
5831 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5833 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5834 /* Some packets have received acks. If they all have, we can clear
5835 * the transmit queue.
5838 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5839 if (p->header.seq < call->tfirst
5840 && (p->flags & RX_PKTFLAG_ACKED)) {
5842 #ifdef RX_TRACK_PACKETS
5843 p->flags &= ~RX_PKTFLAG_TQ;
5845 #ifdef RXDEBUG_PACKET
5853 call->flags |= RX_CALL_TQ_CLEARME;
5855 #endif /* RX_ENABLE_LOCKS */
5856 /* Don't bother doing retransmits if the TQ is cleared. */
5857 if (call->flags & RX_CALL_TQ_CLEARME) {
5858 rxi_ClearTransmitQueue(call, 1);
5860 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5863 /* Always post a resend event, if there is anything in the
5864 * queue, and resend is possible. There should be at least
5865 * one unacknowledged packet in the queue ... otherwise none
5866 * of these packets should be on the queue in the first place.
5868 if (call->resendEvent) {
5869 /* Cancel the existing event and post a new one */
5870 rxevent_Cancel(call->resendEvent, call,
5871 RX_CALL_REFCOUNT_RESEND);
5874 /* The retry time is the retry time on the first unacknowledged
5875 * packet inside the current window */
5877 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5878 /* Don't set timers for packets outside the window */
5879 if (p->header.seq >= call->tfirst + call->twind) {
5883 if (!(p->flags & RX_PKTFLAG_ACKED)
5884 && !clock_IsZero(&p->retryTime)) {
5886 retryTime = p->retryTime;
5891 /* Post a new event to re-run rxi_Start when retries may be needed */
5892 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5893 #ifdef RX_ENABLE_LOCKS
5894 MUTEX_ENTER(&rx_refcnt_mutex);
5895 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5896 MUTEX_EXIT(&rx_refcnt_mutex);
5898 rxevent_PostNow2(&retryTime, &usenow,
5900 (void *)call, 0, istack);
5901 #else /* RX_ENABLE_LOCKS */
5903 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5904 (void *)call, 0, istack);
5905 #endif /* RX_ENABLE_LOCKS */
5908 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5909 } while (call->flags & RX_CALL_NEED_START);
5911 * TQ references no longer protected by this flag; they must remain
5912 * protected by the global lock.
5914 call->flags &= ~RX_CALL_TQ_BUSY;
5915 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5916 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
5917 call, call->tqWaiters, call->flags));
5918 #ifdef RX_ENABLE_LOCKS
5919 osirx_AssertMine(&call->lock, "rxi_Start end");
5920 CV_BROADCAST(&call->cv_tq);
5921 #else /* RX_ENABLE_LOCKS */
5922 osi_rxWakeup(&call->tq);
5923 #endif /* RX_ENABLE_LOCKS */
5926 call->flags |= RX_CALL_NEED_START;
5928 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5930 if (call->resendEvent) {
5931 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5936 /* Also adjusts the keep alive parameters for the call, to reflect
5937 * that we have just sent a packet (so keep alives aren't sent
5940 rxi_Send(struct rx_call *call, struct rx_packet *p,
5943 struct rx_connection *conn = call->conn;
5945 /* Stamp each packet with the user supplied status */
5946 p->header.userStatus = call->localStatus;
5948 /* Allow the security object controlling this call's security to
5949 * make any last-minute changes to the packet */
5950 RXS_SendPacket(conn->securityObject, call, p);
5952 /* Since we're about to send SOME sort of packet to the peer, it's
5953 * safe to nuke any scheduled end-of-packets ack */
5954 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5956 /* Actually send the packet, filling in more connection-specific fields */
5957 MUTEX_EXIT(&call->lock);
5958 MUTEX_ENTER(&rx_refcnt_mutex);
5959 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5960 MUTEX_EXIT(&rx_refcnt_mutex);
5961 rxi_SendPacket(call, conn, p, istack);
5962 MUTEX_ENTER(&rx_refcnt_mutex);
5963 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5964 MUTEX_EXIT(&rx_refcnt_mutex);
5965 MUTEX_ENTER(&call->lock);
5967 /* Update last send time for this call (for keep-alive
5968 * processing), and for the connection (so that we can discover
5969 * idle connections) */
5970 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5971 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
5972 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
5974 conn->lastSendTime = call->lastSendTime = clock_Sec();
5975 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
5976 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
5977 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
5978 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
5979 RX_ACK_PING_RESPONSE)))
5980 call->lastSendData = call->lastSendTime;
5984 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5985 * that things are fine. Also called periodically to guarantee that nothing
5986 * falls through the cracks (e.g. (error + dally) connections have keepalive
5987 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5989 * haveCTLock Set if calling from rxi_ReapConnections
5991 #ifdef RX_ENABLE_LOCKS
5993 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5994 #else /* RX_ENABLE_LOCKS */
5996 rxi_CheckCall(struct rx_call *call)
5997 #endif /* RX_ENABLE_LOCKS */
5999 struct rx_connection *conn = call->conn;
6001 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6002 afs_uint32 fudgeFactor;
6006 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6007 if (call->flags & RX_CALL_TQ_BUSY) {
6008 /* Call is active and will be reset by rxi_Start if it's
6009 * in an error state.
6014 /* RTT + 8*MDEV, rounded up to the next second. */
6015 fudgeFactor = (((afs_uint32) conn->peer->rtt >> 3) +
6016 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
6018 deadTime = conn->secondsUntilDead + fudgeFactor;
6020 /* These are computed to the second (+- 1 second). But that's
6021 * good enough for these values, which should be a significant
6022 * number of seconds. */
6023 if (now > (call->lastReceiveTime + deadTime)) {
6024 if (call->state == RX_STATE_ACTIVE) {
6026 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
6028 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6029 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6030 ip_stack_t *ipst = ns->netstack_ip;
6032 ire = ire_cache_lookup(conn->peer->host
6033 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6035 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6037 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6044 if (ire && ire->ire_max_frag > 0)
6045 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6047 #if defined(GLOBAL_NETSTACKID)
6051 #endif /* ADAPT_PMTU */
6052 cerror = RX_CALL_DEAD;
6055 #ifdef RX_ENABLE_LOCKS
6056 /* Cancel pending events */
6057 rxevent_Cancel(call->delayedAckEvent, call,
6058 RX_CALL_REFCOUNT_DELAY);
6059 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
6060 rxevent_Cancel(call->keepAliveEvent, call,
6061 RX_CALL_REFCOUNT_ALIVE);
6062 MUTEX_ENTER(&rx_refcnt_mutex);
6063 if (call->refCount == 0) {
6064 rxi_FreeCall(call, haveCTLock);
6065 MUTEX_EXIT(&rx_refcnt_mutex);
6068 MUTEX_EXIT(&rx_refcnt_mutex);
6070 #else /* RX_ENABLE_LOCKS */
6071 rxi_FreeCall(call, 0);
6073 #endif /* RX_ENABLE_LOCKS */
6075 /* Non-active calls are destroyed if they are not responding
6076 * to pings; active calls are simply flagged in error, so the
6077 * attached process can die reasonably gracefully. */
6080 if (conn->idleDeadTime) {
6081 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6084 /* see if we have a non-activity timeout */
6085 if (call->startWait && idleDeadTime
6086 && ((call->startWait + idleDeadTime) < now) &&
6087 (call->flags & RX_CALL_READER_WAIT)) {
6088 if (call->state == RX_STATE_ACTIVE) {
6089 cerror = RX_CALL_TIMEOUT;
6093 if (call->lastSendData && idleDeadTime && (conn->idleDeadErr != 0)
6094 && ((call->lastSendData + idleDeadTime) < now)) {
6095 if (call->state == RX_STATE_ACTIVE) {
6096 cerror = conn->idleDeadErr;
6102 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6105 /* see if we have a hard timeout */
6107 && (now > (hardDeadTime + call->startTime.sec))) {
6108 if (call->state == RX_STATE_ACTIVE)
6109 rxi_CallError(call, RX_CALL_TIMEOUT);
6114 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT
6115 && call->lastReceiveTime) {
6116 int oldMTU = conn->peer->ifMTU;
6118 /* if we thought we could send more, perhaps things got worse */
6119 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6120 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6121 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6122 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6124 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6126 /* minimum capped in SetPeerMtu */
6127 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6130 conn->lastPacketSize = 0;
6132 /* needed so ResetCall doesn't clobber us. */
6133 call->MTU = conn->peer->ifMTU;
6135 /* if we never succeeded, let the error pass out as-is */
6136 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6137 cerror = conn->msgsizeRetryErr;
6140 rxi_CallError(call, cerror);
6145 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6147 struct rx_connection *conn = arg1;
6148 struct rx_header theader;
6150 struct sockaddr_in taddr;
6153 struct iovec tmpiov[2];
6156 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6159 tp = &tbuffer[sizeof(struct rx_header)];
6160 taddr.sin_family = AF_INET;
6161 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6162 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6163 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6164 taddr.sin_len = sizeof(struct sockaddr_in);
6166 memset(&theader, 0, sizeof(theader));
6167 theader.epoch = htonl(999);
6169 theader.callNumber = 0;
6172 theader.type = RX_PACKET_TYPE_VERSION;
6173 theader.flags = RX_LAST_PACKET;
6174 theader.serviceId = 0;
6176 memcpy(tbuffer, &theader, sizeof(theader));
6177 memcpy(tp, &a, sizeof(a));
6178 tmpiov[0].iov_base = tbuffer;
6179 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6181 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6183 MUTEX_ENTER(&conn->conn_data_lock);
6184 MUTEX_ENTER(&rx_refcnt_mutex);
6185 /* Only reschedule ourselves if the connection would not be destroyed */
6186 if (conn->refCount <= 1) {
6187 conn->natKeepAliveEvent = NULL;
6188 MUTEX_EXIT(&rx_refcnt_mutex);
6189 MUTEX_EXIT(&conn->conn_data_lock);
6190 rx_DestroyConnection(conn); /* drop the reference for this */
6192 conn->refCount--; /* drop the reference for this */
6193 MUTEX_EXIT(&rx_refcnt_mutex);
6194 conn->natKeepAliveEvent = NULL;
6195 rxi_ScheduleNatKeepAliveEvent(conn);
6196 MUTEX_EXIT(&conn->conn_data_lock);
6201 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6203 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6204 struct clock when, now;
6205 clock_GetTime(&now);
6207 when.sec += conn->secondsUntilNatPing;
6208 MUTEX_ENTER(&rx_refcnt_mutex);
6209 conn->refCount++; /* hold a reference for this */
6210 MUTEX_EXIT(&rx_refcnt_mutex);
6211 conn->natKeepAliveEvent =
6212 rxevent_PostNow(&when, &now, rxi_NatKeepAliveEvent, conn, 0);
6217 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6219 MUTEX_ENTER(&conn->conn_data_lock);
6220 conn->secondsUntilNatPing = seconds;
6222 rxi_ScheduleNatKeepAliveEvent(conn);
6223 MUTEX_EXIT(&conn->conn_data_lock);
6227 rxi_NatKeepAliveOn(struct rx_connection *conn)
6229 MUTEX_ENTER(&conn->conn_data_lock);
6230 rxi_ScheduleNatKeepAliveEvent(conn);
6231 MUTEX_EXIT(&conn->conn_data_lock);
6234 /* When a call is in progress, this routine is called occasionally to
6235 * make sure that some traffic has arrived (or been sent to) the peer.
6236 * If nothing has arrived in a reasonable amount of time, the call is
6237 * declared dead; if nothing has been sent for a while, we send a
6238 * keep-alive packet (if we're actually trying to keep the call alive)
6241 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
6243 struct rx_call *call = arg1;
6244 struct rx_connection *conn;
6247 MUTEX_ENTER(&rx_refcnt_mutex);
6248 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6249 MUTEX_EXIT(&rx_refcnt_mutex);
6250 MUTEX_ENTER(&call->lock);
6251 if (event == call->keepAliveEvent)
6252 call->keepAliveEvent = NULL;
6255 #ifdef RX_ENABLE_LOCKS
6256 if (rxi_CheckCall(call, 0)) {
6257 MUTEX_EXIT(&call->lock);
6260 #else /* RX_ENABLE_LOCKS */
6261 if (rxi_CheckCall(call))
6263 #endif /* RX_ENABLE_LOCKS */
6265 /* Don't try to keep alive dallying calls */
6266 if (call->state == RX_STATE_DALLY) {
6267 MUTEX_EXIT(&call->lock);
6272 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6273 /* Don't try to send keepalives if there is unacknowledged data */
6274 /* the rexmit code should be good enough, this little hack
6275 * doesn't quite work XXX */
6276 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6278 rxi_ScheduleKeepAliveEvent(call);
6279 MUTEX_EXIT(&call->lock);
6282 /* Does what's on the nameplate. */
6284 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy)
6286 struct rx_call *call = arg1;
6287 struct rx_connection *conn;
6289 MUTEX_ENTER(&rx_refcnt_mutex);
6290 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6291 MUTEX_EXIT(&rx_refcnt_mutex);
6292 MUTEX_ENTER(&call->lock);
6294 if (event == call->growMTUEvent)
6295 call->growMTUEvent = NULL;
6297 #ifdef RX_ENABLE_LOCKS
6298 if (rxi_CheckCall(call, 0)) {
6299 MUTEX_EXIT(&call->lock);
6302 #else /* RX_ENABLE_LOCKS */
6303 if (rxi_CheckCall(call))
6305 #endif /* RX_ENABLE_LOCKS */
6307 /* Don't bother with dallying calls */
6308 if (call->state == RX_STATE_DALLY) {
6309 MUTEX_EXIT(&call->lock);
6316 * keep being scheduled, just don't do anything if we're at peak,
6317 * or we're not set up to be properly handled (idle timeout required)
6319 if ((conn->peer->maxPacketSize != 0) &&
6320 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6321 (conn->idleDeadErr))
6322 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6323 rxi_ScheduleGrowMTUEvent(call, 0);
6324 MUTEX_EXIT(&call->lock);
6328 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6330 if (!call->keepAliveEvent) {
6331 struct clock when, now;
6332 clock_GetTime(&now);
6334 when.sec += call->conn->secondsUntilPing;
6335 MUTEX_ENTER(&rx_refcnt_mutex);
6336 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6337 MUTEX_EXIT(&rx_refcnt_mutex);
6338 call->keepAliveEvent =
6339 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
6344 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6346 if (!call->growMTUEvent) {
6347 struct clock when, now;
6349 clock_GetTime(&now);
6352 if (call->conn->secondsUntilPing)
6353 secs = (6*call->conn->secondsUntilPing)-1;
6355 if (call->conn->secondsUntilDead)
6356 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6360 MUTEX_ENTER(&rx_refcnt_mutex);
6361 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6362 MUTEX_EXIT(&rx_refcnt_mutex);
6363 call->growMTUEvent =
6364 rxevent_PostNow(&when, &now, rxi_GrowMTUEvent, call, 0);
6368 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6370 rxi_KeepAliveOn(struct rx_call *call)
6372 /* Pretend last packet received was received now--i.e. if another
6373 * packet isn't received within the keep alive time, then the call
6374 * will die; Initialize last send time to the current time--even
6375 * if a packet hasn't been sent yet. This will guarantee that a
6376 * keep-alive is sent within the ping time */
6377 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6378 rxi_ScheduleKeepAliveEvent(call);
6382 rxi_GrowMTUOn(struct rx_call *call)
6384 struct rx_connection *conn = call->conn;
6385 MUTEX_ENTER(&conn->conn_data_lock);
6386 conn->lastPingSizeSer = conn->lastPingSize = 0;
6387 MUTEX_EXIT(&conn->conn_data_lock);
6388 rxi_ScheduleGrowMTUEvent(call, 1);
6391 /* This routine is called to send connection abort messages
6392 * that have been delayed to throttle looping clients. */
6394 rxi_SendDelayedConnAbort(struct rxevent *event,
6395 void *arg1, void *unused)
6397 struct rx_connection *conn = arg1;
6400 struct rx_packet *packet;
6402 MUTEX_ENTER(&conn->conn_data_lock);
6403 conn->delayedAbortEvent = NULL;
6404 error = htonl(conn->error);
6406 MUTEX_EXIT(&conn->conn_data_lock);
6407 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6410 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6411 RX_PACKET_TYPE_ABORT, (char *)&error,
6413 rxi_FreePacket(packet);
6417 /* This routine is called to send call abort messages
6418 * that have been delayed to throttle looping clients. */
6420 rxi_SendDelayedCallAbort(struct rxevent *event,
6421 void *arg1, void *dummy)
6423 struct rx_call *call = arg1;
6426 struct rx_packet *packet;
6428 MUTEX_ENTER(&call->lock);
6429 call->delayedAbortEvent = NULL;
6430 error = htonl(call->error);
6432 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6435 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6436 (char *)&error, sizeof(error), 0);
6437 rxi_FreePacket(packet);
6439 MUTEX_EXIT(&call->lock);
6440 MUTEX_ENTER(&rx_refcnt_mutex);
6441 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6442 MUTEX_EXIT(&rx_refcnt_mutex);
6445 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6446 * seconds) to ask the client to authenticate itself. The routine
6447 * issues a challenge to the client, which is obtained from the
6448 * security object associated with the connection */
6450 rxi_ChallengeEvent(struct rxevent *event,
6451 void *arg0, void *arg1, int tries)
6453 struct rx_connection *conn = arg0;
6455 conn->challengeEvent = NULL;
6456 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6457 struct rx_packet *packet;
6458 struct clock when, now;
6461 /* We've failed to authenticate for too long.
6462 * Reset any calls waiting for authentication;
6463 * they are all in RX_STATE_PRECALL.
6467 MUTEX_ENTER(&conn->conn_call_lock);
6468 for (i = 0; i < RX_MAXCALLS; i++) {
6469 struct rx_call *call = conn->call[i];
6471 MUTEX_ENTER(&call->lock);
6472 if (call->state == RX_STATE_PRECALL) {
6473 rxi_CallError(call, RX_CALL_DEAD);
6474 rxi_SendCallAbort(call, NULL, 0, 0);
6476 MUTEX_EXIT(&call->lock);
6479 MUTEX_EXIT(&conn->conn_call_lock);
6483 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6485 /* If there's no packet available, do this later. */
6486 RXS_GetChallenge(conn->securityObject, conn, packet);
6487 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6488 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6489 rxi_FreePacket(packet);
6491 clock_GetTime(&now);
6493 when.sec += RX_CHALLENGE_TIMEOUT;
6494 conn->challengeEvent =
6495 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
6500 /* Call this routine to start requesting the client to authenticate
6501 * itself. This will continue until authentication is established,
6502 * the call times out, or an invalid response is returned. The
6503 * security object associated with the connection is asked to create
6504 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6505 * defined earlier. */
6507 rxi_ChallengeOn(struct rx_connection *conn)
6509 if (!conn->challengeEvent) {
6510 RXS_CreateChallenge(conn->securityObject, conn);
6511 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6516 /* Compute round trip time of the packet provided, in *rttp.
6519 /* rxi_ComputeRoundTripTime is called with peer locked. */
6520 /* sentp and/or peer may be null */
6522 rxi_ComputeRoundTripTime(struct rx_packet *p,
6523 struct clock *sentp,
6524 struct rx_peer *peer,
6527 struct clock thisRtt, *rttp = &thisRtt;
6532 if (clock_Lt(rttp, sentp))
6533 return; /* somebody set the clock back, don't count this time. */
6535 clock_Sub(rttp, sentp);
6536 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6537 p->header.callNumber, p, rttp->sec, rttp->usec));
6539 if (rttp->sec == 0 && rttp->usec == 0) {
6541 * The actual round trip time is shorter than the
6542 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6543 * Since we can't tell which at the moment we will assume 1ms.
6548 if (rx_stats_active) {
6549 MUTEX_ENTER(&rx_stats_mutex);
6550 if (clock_Lt(rttp, &rx_stats.minRtt))
6551 rx_stats.minRtt = *rttp;
6552 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
6553 if (rttp->sec > 60) {
6554 MUTEX_EXIT(&rx_stats_mutex);
6555 return; /* somebody set the clock ahead */
6557 rx_stats.maxRtt = *rttp;
6559 clock_Add(&rx_stats.totalRtt, rttp);
6560 rx_atomic_inc(&rx_stats.nRttSamples);
6561 MUTEX_EXIT(&rx_stats_mutex);
6564 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6566 /* Apply VanJacobson round-trip estimations */
6571 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6572 * srtt is stored as fixed point with 3 bits after the binary
6573 * point (i.e., scaled by 8). The following magic is
6574 * equivalent to the smoothing algorithm in rfc793 with an
6575 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6576 * srtt'*8 = rtt + srtt*7
6577 * srtt'*8 = srtt*8 + rtt - srtt
6578 * srtt' = srtt + rtt/8 - srtt/8
6579 * srtt' = srtt + (rtt - srtt)/8
6582 delta = _8THMSEC(rttp) - peer->rtt;
6583 peer->rtt += (delta >> 3);
6586 * We accumulate a smoothed rtt variance (actually, a smoothed
6587 * mean difference), then set the retransmit timer to smoothed
6588 * rtt + 4 times the smoothed variance (was 2x in van's original
6589 * paper, but 4x works better for me, and apparently for him as
6591 * rttvar is stored as
6592 * fixed point with 2 bits after the binary point (scaled by
6593 * 4). The following is equivalent to rfc793 smoothing with
6594 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6595 * rttvar'*4 = rttvar*3 + |delta|
6596 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6597 * rttvar' = rttvar + |delta|/4 - rttvar/4
6598 * rttvar' = rttvar + (|delta| - rttvar)/4
6599 * This replaces rfc793's wired-in beta.
6600 * dev*4 = dev*4 + (|actual - expected| - dev)
6606 delta -= (peer->rtt_dev << 1);
6607 peer->rtt_dev += (delta >> 3);
6609 /* I don't have a stored RTT so I start with this value. Since I'm
6610 * probably just starting a call, and will be pushing more data down
6611 * this, I expect congestion to increase rapidly. So I fudge a
6612 * little, and I set deviance to half the rtt. In practice,
6613 * deviance tends to approach something a little less than
6614 * half the smoothed rtt. */
6615 peer->rtt = _8THMSEC(rttp) + 8;
6616 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6618 /* the timeout is RTT + 4*MDEV but no less than rx_minPeerTimeout msec.
6619 * This is because one end or the other of these connections is usually
6620 * in a user process, and can be switched and/or swapped out. So on fast,
6621 * reliable networks, the timeout would otherwise be too short. */
6622 rtt_timeout = MAX(((peer->rtt >> 3) + peer->rtt_dev), rx_minPeerTimeout);
6623 clock_Zero(&(peer->timeout));
6624 clock_Addmsec(&(peer->timeout), rtt_timeout);
6626 /* Reset the backedOff flag since we just computed a new timeout value */
6627 peer->backedOff = 0;
6629 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6630 p->header.callNumber, p, MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6634 /* Find all server connections that have not been active for a long time, and
6637 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6639 struct clock now, when;
6640 clock_GetTime(&now);
6642 /* Find server connection structures that haven't been used for
6643 * greater than rx_idleConnectionTime */
6645 struct rx_connection **conn_ptr, **conn_end;
6646 int i, havecalls = 0;
6647 MUTEX_ENTER(&rx_connHashTable_lock);
6648 for (conn_ptr = &rx_connHashTable[0], conn_end =
6649 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6651 struct rx_connection *conn, *next;
6652 struct rx_call *call;
6656 for (conn = *conn_ptr; conn; conn = next) {
6657 /* XXX -- Shouldn't the connection be locked? */
6660 for (i = 0; i < RX_MAXCALLS; i++) {
6661 call = conn->call[i];
6665 code = MUTEX_TRYENTER(&call->lock);
6668 #ifdef RX_ENABLE_LOCKS
6669 result = rxi_CheckCall(call, 1);
6670 #else /* RX_ENABLE_LOCKS */
6671 result = rxi_CheckCall(call);
6672 #endif /* RX_ENABLE_LOCKS */
6673 MUTEX_EXIT(&call->lock);
6675 /* If CheckCall freed the call, it might
6676 * have destroyed the connection as well,
6677 * which screws up the linked lists.
6683 if (conn->type == RX_SERVER_CONNECTION) {
6684 /* This only actually destroys the connection if
6685 * there are no outstanding calls */
6686 MUTEX_ENTER(&conn->conn_data_lock);
6687 MUTEX_ENTER(&rx_refcnt_mutex);
6688 if (!havecalls && !conn->refCount
6689 && ((conn->lastSendTime + rx_idleConnectionTime) <
6691 conn->refCount++; /* it will be decr in rx_DestroyConn */
6692 MUTEX_EXIT(&rx_refcnt_mutex);
6693 MUTEX_EXIT(&conn->conn_data_lock);
6694 #ifdef RX_ENABLE_LOCKS
6695 rxi_DestroyConnectionNoLock(conn);
6696 #else /* RX_ENABLE_LOCKS */
6697 rxi_DestroyConnection(conn);
6698 #endif /* RX_ENABLE_LOCKS */
6700 #ifdef RX_ENABLE_LOCKS
6702 MUTEX_EXIT(&rx_refcnt_mutex);
6703 MUTEX_EXIT(&conn->conn_data_lock);
6705 #endif /* RX_ENABLE_LOCKS */
6709 #ifdef RX_ENABLE_LOCKS
6710 while (rx_connCleanup_list) {
6711 struct rx_connection *conn;
6712 conn = rx_connCleanup_list;
6713 rx_connCleanup_list = rx_connCleanup_list->next;
6714 MUTEX_EXIT(&rx_connHashTable_lock);
6715 rxi_CleanupConnection(conn);
6716 MUTEX_ENTER(&rx_connHashTable_lock);
6718 MUTEX_EXIT(&rx_connHashTable_lock);
6719 #endif /* RX_ENABLE_LOCKS */
6722 /* Find any peer structures that haven't been used (haven't had an
6723 * associated connection) for greater than rx_idlePeerTime */
6725 struct rx_peer **peer_ptr, **peer_end;
6729 * Why do we need to hold the rx_peerHashTable_lock across
6730 * the incrementing of peer_ptr since the rx_peerHashTable
6731 * array is not changing? We don't.
6733 * By dropping the lock periodically we can permit other
6734 * activities to be performed while a rxi_ReapConnections
6735 * call is in progress. The goal of reap connections
6736 * is to clean up quickly without causing large amounts
6737 * of contention. Therefore, it is important that global
6738 * mutexes not be held for extended periods of time.
6740 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6741 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6743 struct rx_peer *peer, *next, *prev;
6745 MUTEX_ENTER(&rx_peerHashTable_lock);
6746 for (prev = peer = *peer_ptr; peer; peer = next) {
6748 code = MUTEX_TRYENTER(&peer->peer_lock);
6749 if ((code) && (peer->refCount == 0)
6750 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6751 rx_interface_stat_p rpc_stat, nrpc_stat;
6755 * now know that this peer object is one to be
6756 * removed from the hash table. Once it is removed
6757 * it can't be referenced by other threads.
6758 * Lets remove it first and decrement the struct
6759 * nPeerStructs count.
6761 if (peer == *peer_ptr) {
6767 if (rx_stats_active)
6768 rx_atomic_dec(&rx_stats.nPeerStructs);
6771 * Now if we hold references on 'prev' and 'next'
6772 * we can safely drop the rx_peerHashTable_lock
6773 * while we destroy this 'peer' object.
6779 MUTEX_EXIT(&rx_peerHashTable_lock);
6781 MUTEX_EXIT(&peer->peer_lock);
6782 MUTEX_DESTROY(&peer->peer_lock);
6784 (&peer->rpcStats, rpc_stat, nrpc_stat,
6785 rx_interface_stat)) {
6786 unsigned int num_funcs;
6789 queue_Remove(&rpc_stat->queue_header);
6790 queue_Remove(&rpc_stat->all_peers);
6791 num_funcs = rpc_stat->stats[0].func_total;
6793 sizeof(rx_interface_stat_t) +
6794 rpc_stat->stats[0].func_total *
6795 sizeof(rx_function_entry_v1_t);
6797 rxi_Free(rpc_stat, space);
6799 MUTEX_ENTER(&rx_rpc_stats);
6800 rxi_rpc_peer_stat_cnt -= num_funcs;
6801 MUTEX_EXIT(&rx_rpc_stats);
6806 * Regain the rx_peerHashTable_lock and
6807 * decrement the reference count on 'prev'
6810 MUTEX_ENTER(&rx_peerHashTable_lock);
6817 MUTEX_EXIT(&peer->peer_lock);
6822 MUTEX_EXIT(&rx_peerHashTable_lock);
6826 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6827 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6828 * GC, just below. Really, we shouldn't have to keep moving packets from
6829 * one place to another, but instead ought to always know if we can
6830 * afford to hold onto a packet in its particular use. */
6831 MUTEX_ENTER(&rx_freePktQ_lock);
6832 if (rx_waitingForPackets) {
6833 rx_waitingForPackets = 0;
6834 #ifdef RX_ENABLE_LOCKS
6835 CV_BROADCAST(&rx_waitingForPackets_cv);
6837 osi_rxWakeup(&rx_waitingForPackets);
6840 MUTEX_EXIT(&rx_freePktQ_lock);
6843 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6844 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6848 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6849 * rx.h is sort of strange this is better. This is called with a security
6850 * object before it is discarded. Each connection using a security object has
6851 * its own refcount to the object so it won't actually be freed until the last
6852 * connection is destroyed.
6854 * This is the only rxs module call. A hold could also be written but no one
6858 rxs_Release(struct rx_securityClass *aobj)
6860 return RXS_Close(aobj);
6864 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6865 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6866 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6867 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6869 /* Adjust our estimate of the transmission rate to this peer, given
6870 * that the packet p was just acked. We can adjust peer->timeout and
6871 * call->twind. Pragmatically, this is called
6872 * only with packets of maximal length.
6873 * Called with peer and call locked.
6877 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6878 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6880 afs_int32 xferSize, xferMs;
6884 /* Count down packets */
6885 if (peer->rateFlag > 0)
6887 /* Do nothing until we're enabled */
6888 if (peer->rateFlag != 0)
6893 /* Count only when the ack seems legitimate */
6894 switch (ackReason) {
6895 case RX_ACK_REQUESTED:
6897 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6901 case RX_ACK_PING_RESPONSE:
6902 if (p) /* want the response to ping-request, not data send */
6904 clock_GetTime(&newTO);
6905 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6906 clock_Sub(&newTO, &call->pingRequestTime);
6907 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6911 xferSize = rx_AckDataSize(rx_maxSendWindow) + RX_HEADER_SIZE;
6918 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %d.%06d, rtt %u, ps %u)",
6919 ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"),
6920 xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6922 /* Track only packets that are big enough. */
6923 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6927 /* absorb RTT data (in milliseconds) for these big packets */
6928 if (peer->smRtt == 0) {
6929 peer->smRtt = xferMs;
6931 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6936 if (peer->countDown) {
6940 peer->countDown = 10; /* recalculate only every so often */
6942 /* In practice, we can measure only the RTT for full packets,
6943 * because of the way Rx acks the data that it receives. (If it's
6944 * smaller than a full packet, it often gets implicitly acked
6945 * either by the call response (from a server) or by the next call
6946 * (from a client), and either case confuses transmission times
6947 * with processing times.) Therefore, replace the above
6948 * more-sophisticated processing with a simpler version, where the
6949 * smoothed RTT is kept for full-size packets, and the time to
6950 * transmit a windowful of full-size packets is simply RTT *
6951 * windowSize. Again, we take two steps:
6952 - ensure the timeout is large enough for a single packet's RTT;
6953 - ensure that the window is small enough to fit in the desired timeout.*/
6955 /* First, the timeout check. */
6956 minTime = peer->smRtt;
6957 /* Get a reasonable estimate for a timeout period */
6959 newTO.sec = minTime / 1000;
6960 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6962 /* Increase the timeout period so that we can always do at least
6963 * one packet exchange */
6964 if (clock_Gt(&newTO, &peer->timeout)) {
6966 dpf(("CONG peer %lx/%u: timeout %d.%06d ==> %ld.%06d (rtt %u)",
6967 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec,
6968 newTO.sec, newTO.usec, peer->smRtt));
6970 peer->timeout = newTO;
6973 /* Now, get an estimate for the transmit window size. */
6974 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6975 /* Now, convert to the number of full packets that could fit in a
6976 * reasonable fraction of that interval */
6977 minTime /= (peer->smRtt << 1);
6978 minTime = MAX(minTime, rx_minPeerTimeout);
6979 xferSize = minTime; /* (make a copy) */
6981 /* Now clamp the size to reasonable bounds. */
6984 else if (minTime > rx_maxSendWindow)
6985 minTime = rx_maxSendWindow;
6986 /* if (minTime != peer->maxWindow) {
6987 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u)",
6988 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6989 peer->timeout.sec, peer->timeout.usec, peer->smRtt));
6990 peer->maxWindow = minTime;
6991 elide... call->twind = minTime;
6995 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6996 * Discern this by calculating the timeout necessary for rx_Window
6998 if ((xferSize > rx_maxSendWindow) && (peer->timeout.sec >= 3)) {
6999 /* calculate estimate for transmission interval in milliseconds */
7000 minTime = rx_maxSendWindow * peer->smRtt;
7001 if (minTime < 1000) {
7002 dpf(("CONG peer %lx/%u: cut TO %d.%06d by 0.5 (rtt %u)",
7003 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
7004 peer->timeout.usec, peer->smRtt));
7006 newTO.sec = 0; /* cut back on timeout by half a second */
7007 newTO.usec = 500000;
7008 clock_Sub(&peer->timeout, &newTO);
7013 } /* end of rxi_ComputeRate */
7014 #endif /* ADAPT_WINDOW */
7022 #define TRACE_OPTION_RX_DEBUG 16
7030 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7031 0, KEY_QUERY_VALUE, &parmKey);
7032 if (code != ERROR_SUCCESS)
7035 dummyLen = sizeof(TraceOption);
7036 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7037 (BYTE *) &TraceOption, &dummyLen);
7038 if (code == ERROR_SUCCESS) {
7039 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7041 RegCloseKey (parmKey);
7042 #endif /* AFS_NT40_ENV */
7047 rx_DebugOnOff(int on)
7051 rxdebug_active = on;
7057 rx_StatsOnOff(int on)
7060 rx_stats_active = on;
7065 /* Don't call this debugging routine directly; use dpf */
7067 rxi_DebugPrint(char *format, ...)
7076 va_start(ap, format);
7078 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7081 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7083 if (msg[len-1] != '\n') {
7087 OutputDebugString(msg);
7094 va_start(ap, format);
7096 clock_GetTime(&now);
7097 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7098 (unsigned int)now.usec);
7099 vfprintf(rx_Log, format, ap);
7108 * This function is used to process the rx_stats structure that is local
7109 * to a process as well as an rx_stats structure received from a remote
7110 * process (via rxdebug). Therefore, it needs to do minimal version
7114 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7115 afs_int32 freePackets, char version)
7119 if (size != sizeof(struct rx_statistics)) {
7121 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7122 size, sizeof(struct rx_statistics));
7125 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7128 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7129 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7130 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7131 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7132 s->specialPktAllocFailures);
7134 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7135 s->receivePktAllocFailures, s->sendPktAllocFailures,
7136 s->specialPktAllocFailures);
7140 " greedy %u, " "bogusReads %u (last from host %x), "
7141 "noPackets %u, " "noBuffers %u, " "selects %u, "
7142 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7143 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7144 s->selects, s->sendSelects);
7146 fprintf(file, " packets read: ");
7147 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7148 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7150 fprintf(file, "\n");
7153 " other read counters: data %u, " "ack %u, " "dup %u "
7154 "spurious %u " "dally %u\n", s->dataPacketsRead,
7155 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7156 s->ignorePacketDally);
7158 fprintf(file, " packets sent: ");
7159 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7160 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7162 fprintf(file, "\n");
7165 " other send counters: ack %u, " "data %u (not resends), "
7166 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7167 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7168 s->dataPacketsPushed, s->ignoreAckedPacket);
7171 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7172 s->netSendFailures, (int)s->fatalErrors);
7174 if (s->nRttSamples) {
7175 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7176 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7178 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7179 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7183 " %d server connections, " "%d client connections, "
7184 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7185 s->nServerConns, s->nClientConns, s->nPeerStructs,
7186 s->nCallStructs, s->nFreeCallStructs);
7188 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7189 fprintf(file, " %d clock updates\n", clock_nUpdates);
7193 /* for backward compatibility */
7195 rx_PrintStats(FILE * file)
7197 MUTEX_ENTER(&rx_stats_mutex);
7198 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7199 sizeof(rx_stats), rx_nFreePackets,
7201 MUTEX_EXIT(&rx_stats_mutex);
7205 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7207 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7208 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7209 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7212 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
7213 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
7214 (int)peer->timeout.usec, peer->nSent, peer->reSends);
7217 " Packet size %d, " "max in packet skew %d, "
7218 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7219 (int)peer->outPacketSkew);
7223 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7225 * This mutex protects the following static variables:
7229 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7230 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7232 #define LOCK_RX_DEBUG
7233 #define UNLOCK_RX_DEBUG
7234 #endif /* AFS_PTHREAD_ENV */
7236 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7238 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7239 u_char type, void *inputData, size_t inputLength,
7240 void *outputData, size_t outputLength)
7242 static afs_int32 counter = 100;
7243 time_t waitTime, waitCount;
7244 struct rx_header theader;
7247 struct timeval tv_now, tv_wake, tv_delta;
7248 struct sockaddr_in taddr, faddr;
7262 tp = &tbuffer[sizeof(struct rx_header)];
7263 taddr.sin_family = AF_INET;
7264 taddr.sin_port = remotePort;
7265 taddr.sin_addr.s_addr = remoteAddr;
7266 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7267 taddr.sin_len = sizeof(struct sockaddr_in);
7270 memset(&theader, 0, sizeof(theader));
7271 theader.epoch = htonl(999);
7273 theader.callNumber = htonl(counter);
7276 theader.type = type;
7277 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7278 theader.serviceId = 0;
7280 memcpy(tbuffer, &theader, sizeof(theader));
7281 memcpy(tp, inputData, inputLength);
7283 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7284 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7286 /* see if there's a packet available */
7287 gettimeofday(&tv_wake,0);
7288 tv_wake.tv_sec += waitTime;
7291 FD_SET(socket, &imask);
7292 tv_delta.tv_sec = tv_wake.tv_sec;
7293 tv_delta.tv_usec = tv_wake.tv_usec;
7294 gettimeofday(&tv_now, 0);
7296 if (tv_delta.tv_usec < tv_now.tv_usec) {
7298 tv_delta.tv_usec += 1000000;
7301 tv_delta.tv_usec -= tv_now.tv_usec;
7303 if (tv_delta.tv_sec < tv_now.tv_sec) {
7307 tv_delta.tv_sec -= tv_now.tv_sec;
7310 code = select(0, &imask, 0, 0, &tv_delta);
7311 #else /* AFS_NT40_ENV */
7312 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7313 #endif /* AFS_NT40_ENV */
7314 if (code == 1 && FD_ISSET(socket, &imask)) {
7315 /* now receive a packet */
7316 faddrLen = sizeof(struct sockaddr_in);
7318 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7319 (struct sockaddr *)&faddr, &faddrLen);
7322 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7323 if (counter == ntohl(theader.callNumber))
7331 /* see if we've timed out */
7339 code -= sizeof(struct rx_header);
7340 if (code > outputLength)
7341 code = outputLength;
7342 memcpy(outputData, tp, code);
7345 #endif /* RXDEBUG */
7348 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7349 afs_uint16 remotePort, struct rx_debugStats * stat,
7350 afs_uint32 * supportedValues)
7352 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7354 struct rx_debugIn in;
7356 *supportedValues = 0;
7357 in.type = htonl(RX_DEBUGI_GETSTATS);
7360 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7361 &in, sizeof(in), stat, sizeof(*stat));
7364 * If the call was successful, fixup the version and indicate
7365 * what contents of the stat structure are valid.
7366 * Also do net to host conversion of fields here.
7370 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7371 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7373 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7374 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7376 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7377 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7379 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7380 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7382 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7383 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7385 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7386 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7388 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7389 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7391 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7392 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7394 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7395 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7397 stat->nFreePackets = ntohl(stat->nFreePackets);
7398 stat->packetReclaims = ntohl(stat->packetReclaims);
7399 stat->callsExecuted = ntohl(stat->callsExecuted);
7400 stat->nWaiting = ntohl(stat->nWaiting);
7401 stat->idleThreads = ntohl(stat->idleThreads);
7402 stat->nWaited = ntohl(stat->nWaited);
7403 stat->nPackets = ntohl(stat->nPackets);
7412 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7413 afs_uint16 remotePort, struct rx_statistics * stat,
7414 afs_uint32 * supportedValues)
7416 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7418 struct rx_debugIn in;
7419 afs_int32 *lp = (afs_int32 *) stat;
7423 * supportedValues is currently unused, but added to allow future
7424 * versioning of this function.
7427 *supportedValues = 0;
7428 in.type = htonl(RX_DEBUGI_RXSTATS);
7430 memset(stat, 0, sizeof(*stat));
7432 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7433 &in, sizeof(in), stat, sizeof(*stat));
7438 * Do net to host conversion here
7441 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7452 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7453 afs_uint16 remotePort, size_t version_length,
7456 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7458 return MakeDebugCall(socket, remoteAddr, remotePort,
7459 RX_PACKET_TYPE_VERSION, a, 1, version,
7467 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7468 afs_uint16 remotePort, afs_int32 * nextConnection,
7469 int allConnections, afs_uint32 debugSupportedValues,
7470 struct rx_debugConn * conn,
7471 afs_uint32 * supportedValues)
7473 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7475 struct rx_debugIn in;
7479 * supportedValues is currently unused, but added to allow future
7480 * versioning of this function.
7483 *supportedValues = 0;
7484 if (allConnections) {
7485 in.type = htonl(RX_DEBUGI_GETALLCONN);
7487 in.type = htonl(RX_DEBUGI_GETCONN);
7489 in.index = htonl(*nextConnection);
7490 memset(conn, 0, sizeof(*conn));
7492 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7493 &in, sizeof(in), conn, sizeof(*conn));
7496 *nextConnection += 1;
7499 * Convert old connection format to new structure.
7502 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7503 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7504 #define MOVEvL(a) (conn->a = vL->a)
7506 /* any old or unrecognized version... */
7507 for (i = 0; i < RX_MAXCALLS; i++) {
7508 MOVEvL(callState[i]);
7509 MOVEvL(callMode[i]);
7510 MOVEvL(callFlags[i]);
7511 MOVEvL(callOther[i]);
7513 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7514 MOVEvL(secStats.type);
7515 MOVEvL(secStats.level);
7516 MOVEvL(secStats.flags);
7517 MOVEvL(secStats.expires);
7518 MOVEvL(secStats.packetsReceived);
7519 MOVEvL(secStats.packetsSent);
7520 MOVEvL(secStats.bytesReceived);
7521 MOVEvL(secStats.bytesSent);
7526 * Do net to host conversion here
7528 * I don't convert host or port since we are most likely
7529 * going to want these in NBO.
7531 conn->cid = ntohl(conn->cid);
7532 conn->serial = ntohl(conn->serial);
7533 for (i = 0; i < RX_MAXCALLS; i++) {
7534 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7536 conn->error = ntohl(conn->error);
7537 conn->secStats.flags = ntohl(conn->secStats.flags);
7538 conn->secStats.expires = ntohl(conn->secStats.expires);
7539 conn->secStats.packetsReceived =
7540 ntohl(conn->secStats.packetsReceived);
7541 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7542 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7543 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7544 conn->epoch = ntohl(conn->epoch);
7545 conn->natMTU = ntohl(conn->natMTU);
7554 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7555 afs_uint16 remotePort, afs_int32 * nextPeer,
7556 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7557 afs_uint32 * supportedValues)
7559 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7561 struct rx_debugIn in;
7564 * supportedValues is currently unused, but added to allow future
7565 * versioning of this function.
7568 *supportedValues = 0;
7569 in.type = htonl(RX_DEBUGI_GETPEER);
7570 in.index = htonl(*nextPeer);
7571 memset(peer, 0, sizeof(*peer));
7573 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7574 &in, sizeof(in), peer, sizeof(*peer));
7580 * Do net to host conversion here
7582 * I don't convert host or port since we are most likely
7583 * going to want these in NBO.
7585 peer->ifMTU = ntohs(peer->ifMTU);
7586 peer->idleWhen = ntohl(peer->idleWhen);
7587 peer->refCount = ntohs(peer->refCount);
7588 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7589 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7590 peer->rtt = ntohl(peer->rtt);
7591 peer->rtt_dev = ntohl(peer->rtt_dev);
7592 peer->timeout.sec = ntohl(peer->timeout.sec);
7593 peer->timeout.usec = ntohl(peer->timeout.usec);
7594 peer->nSent = ntohl(peer->nSent);
7595 peer->reSends = ntohl(peer->reSends);
7596 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7597 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7598 peer->rateFlag = ntohl(peer->rateFlag);
7599 peer->natMTU = ntohs(peer->natMTU);
7600 peer->maxMTU = ntohs(peer->maxMTU);
7601 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7602 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7603 peer->MTU = ntohs(peer->MTU);
7604 peer->cwind = ntohs(peer->cwind);
7605 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7606 peer->congestSeq = ntohs(peer->congestSeq);
7607 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7608 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7609 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7610 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7619 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7620 struct rx_debugPeer * peerStats)
7623 afs_int32 error = 1; /* default to "did not succeed" */
7624 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7626 MUTEX_ENTER(&rx_peerHashTable_lock);
7627 for(tp = rx_peerHashTable[hashValue];
7628 tp != NULL; tp = tp->next) {
7629 if (tp->host == peerHost)
7635 MUTEX_EXIT(&rx_peerHashTable_lock);
7639 MUTEX_ENTER(&tp->peer_lock);
7640 peerStats->host = tp->host;
7641 peerStats->port = tp->port;
7642 peerStats->ifMTU = tp->ifMTU;
7643 peerStats->idleWhen = tp->idleWhen;
7644 peerStats->refCount = tp->refCount;
7645 peerStats->burstSize = tp->burstSize;
7646 peerStats->burst = tp->burst;
7647 peerStats->burstWait.sec = tp->burstWait.sec;
7648 peerStats->burstWait.usec = tp->burstWait.usec;
7649 peerStats->rtt = tp->rtt;
7650 peerStats->rtt_dev = tp->rtt_dev;
7651 peerStats->timeout.sec = tp->timeout.sec;
7652 peerStats->timeout.usec = tp->timeout.usec;
7653 peerStats->nSent = tp->nSent;
7654 peerStats->reSends = tp->reSends;
7655 peerStats->inPacketSkew = tp->inPacketSkew;
7656 peerStats->outPacketSkew = tp->outPacketSkew;
7657 peerStats->rateFlag = tp->rateFlag;
7658 peerStats->natMTU = tp->natMTU;
7659 peerStats->maxMTU = tp->maxMTU;
7660 peerStats->maxDgramPackets = tp->maxDgramPackets;
7661 peerStats->ifDgramPackets = tp->ifDgramPackets;
7662 peerStats->MTU = tp->MTU;
7663 peerStats->cwind = tp->cwind;
7664 peerStats->nDgramPackets = tp->nDgramPackets;
7665 peerStats->congestSeq = tp->congestSeq;
7666 peerStats->bytesSent.high = tp->bytesSent.high;
7667 peerStats->bytesSent.low = tp->bytesSent.low;
7668 peerStats->bytesReceived.high = tp->bytesReceived.high;
7669 peerStats->bytesReceived.low = tp->bytesReceived.low;
7670 MUTEX_EXIT(&tp->peer_lock);
7672 MUTEX_ENTER(&rx_peerHashTable_lock);
7675 MUTEX_EXIT(&rx_peerHashTable_lock);
7683 struct rx_serverQueueEntry *np;
7686 struct rx_call *call;
7687 struct rx_serverQueueEntry *sq;
7691 if (rxinit_status == 1) {
7693 return; /* Already shutdown. */
7697 #ifndef AFS_PTHREAD_ENV
7698 FD_ZERO(&rx_selectMask);
7699 #endif /* AFS_PTHREAD_ENV */
7700 rxi_dataQuota = RX_MAX_QUOTA;
7701 #ifndef AFS_PTHREAD_ENV
7703 #endif /* AFS_PTHREAD_ENV */
7706 #ifndef AFS_PTHREAD_ENV
7707 #ifndef AFS_USE_GETTIMEOFDAY
7709 #endif /* AFS_USE_GETTIMEOFDAY */
7710 #endif /* AFS_PTHREAD_ENV */
7712 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7713 call = queue_First(&rx_freeCallQueue, rx_call);
7715 rxi_Free(call, sizeof(struct rx_call));
7718 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7719 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7725 struct rx_peer **peer_ptr, **peer_end;
7726 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7727 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7729 struct rx_peer *peer, *next;
7731 MUTEX_ENTER(&rx_peerHashTable_lock);
7732 for (peer = *peer_ptr; peer; peer = next) {
7733 rx_interface_stat_p rpc_stat, nrpc_stat;
7736 MUTEX_ENTER(&rx_rpc_stats);
7737 MUTEX_ENTER(&peer->peer_lock);
7739 (&peer->rpcStats, rpc_stat, nrpc_stat,
7740 rx_interface_stat)) {
7741 unsigned int num_funcs;
7744 queue_Remove(&rpc_stat->queue_header);
7745 queue_Remove(&rpc_stat->all_peers);
7746 num_funcs = rpc_stat->stats[0].func_total;
7748 sizeof(rx_interface_stat_t) +
7749 rpc_stat->stats[0].func_total *
7750 sizeof(rx_function_entry_v1_t);
7752 rxi_Free(rpc_stat, space);
7754 /* rx_rpc_stats must be held */
7755 rxi_rpc_peer_stat_cnt -= num_funcs;
7757 MUTEX_EXIT(&peer->peer_lock);
7758 MUTEX_EXIT(&rx_rpc_stats);
7762 if (rx_stats_active)
7763 rx_atomic_dec(&rx_stats.nPeerStructs);
7765 MUTEX_EXIT(&rx_peerHashTable_lock);
7768 for (i = 0; i < RX_MAX_SERVICES; i++) {
7770 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7772 for (i = 0; i < rx_hashTableSize; i++) {
7773 struct rx_connection *tc, *ntc;
7774 MUTEX_ENTER(&rx_connHashTable_lock);
7775 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7777 for (j = 0; j < RX_MAXCALLS; j++) {
7779 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7782 rxi_Free(tc, sizeof(*tc));
7784 MUTEX_EXIT(&rx_connHashTable_lock);
7787 MUTEX_ENTER(&freeSQEList_lock);
7789 while ((np = rx_FreeSQEList)) {
7790 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7791 MUTEX_DESTROY(&np->lock);
7792 rxi_Free(np, sizeof(*np));
7795 MUTEX_EXIT(&freeSQEList_lock);
7796 MUTEX_DESTROY(&freeSQEList_lock);
7797 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7798 MUTEX_DESTROY(&rx_connHashTable_lock);
7799 MUTEX_DESTROY(&rx_peerHashTable_lock);
7800 MUTEX_DESTROY(&rx_serverPool_lock);
7802 osi_Free(rx_connHashTable,
7803 rx_hashTableSize * sizeof(struct rx_connection *));
7804 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7806 UNPIN(rx_connHashTable,
7807 rx_hashTableSize * sizeof(struct rx_connection *));
7808 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7810 rxi_FreeAllPackets();
7812 MUTEX_ENTER(&rx_quota_mutex);
7813 rxi_dataQuota = RX_MAX_QUOTA;
7814 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7815 MUTEX_EXIT(&rx_quota_mutex);
7820 #ifdef RX_ENABLE_LOCKS
7822 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7824 if (!MUTEX_ISMINE(lockaddr))
7825 osi_Panic("Lock not held: %s", msg);
7827 #endif /* RX_ENABLE_LOCKS */
7832 * Routines to implement connection specific data.
7836 rx_KeyCreate(rx_destructor_t rtn)
7839 MUTEX_ENTER(&rxi_keyCreate_lock);
7840 key = rxi_keyCreate_counter++;
7841 rxi_keyCreate_destructor = (rx_destructor_t *)
7842 realloc((void *)rxi_keyCreate_destructor,
7843 (key + 1) * sizeof(rx_destructor_t));
7844 rxi_keyCreate_destructor[key] = rtn;
7845 MUTEX_EXIT(&rxi_keyCreate_lock);
7850 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7853 MUTEX_ENTER(&conn->conn_data_lock);
7854 if (!conn->specific) {
7855 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7856 for (i = 0; i < key; i++)
7857 conn->specific[i] = NULL;
7858 conn->nSpecific = key + 1;
7859 conn->specific[key] = ptr;
7860 } else if (key >= conn->nSpecific) {
7861 conn->specific = (void **)
7862 realloc(conn->specific, (key + 1) * sizeof(void *));
7863 for (i = conn->nSpecific; i < key; i++)
7864 conn->specific[i] = NULL;
7865 conn->nSpecific = key + 1;
7866 conn->specific[key] = ptr;
7868 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7869 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7870 conn->specific[key] = ptr;
7872 MUTEX_EXIT(&conn->conn_data_lock);
7876 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7879 MUTEX_ENTER(&svc->svc_data_lock);
7880 if (!svc->specific) {
7881 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7882 for (i = 0; i < key; i++)
7883 svc->specific[i] = NULL;
7884 svc->nSpecific = key + 1;
7885 svc->specific[key] = ptr;
7886 } else if (key >= svc->nSpecific) {
7887 svc->specific = (void **)
7888 realloc(svc->specific, (key + 1) * sizeof(void *));
7889 for (i = svc->nSpecific; i < key; i++)
7890 svc->specific[i] = NULL;
7891 svc->nSpecific = key + 1;
7892 svc->specific[key] = ptr;
7894 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7895 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7896 svc->specific[key] = ptr;
7898 MUTEX_EXIT(&svc->svc_data_lock);
7902 rx_GetSpecific(struct rx_connection *conn, int key)
7905 MUTEX_ENTER(&conn->conn_data_lock);
7906 if (key >= conn->nSpecific)
7909 ptr = conn->specific[key];
7910 MUTEX_EXIT(&conn->conn_data_lock);
7915 rx_GetServiceSpecific(struct rx_service *svc, int key)
7918 MUTEX_ENTER(&svc->svc_data_lock);
7919 if (key >= svc->nSpecific)
7922 ptr = svc->specific[key];
7923 MUTEX_EXIT(&svc->svc_data_lock);
7928 #endif /* !KERNEL */
7931 * processStats is a queue used to store the statistics for the local
7932 * process. Its contents are similar to the contents of the rpcStats
7933 * queue on a rx_peer structure, but the actual data stored within
7934 * this queue contains totals across the lifetime of the process (assuming
7935 * the stats have not been reset) - unlike the per peer structures
7936 * which can come and go based upon the peer lifetime.
7939 static struct rx_queue processStats = { &processStats, &processStats };
7942 * peerStats is a queue used to store the statistics for all peer structs.
7943 * Its contents are the union of all the peer rpcStats queues.
7946 static struct rx_queue peerStats = { &peerStats, &peerStats };
7949 * rxi_monitor_processStats is used to turn process wide stat collection
7953 static int rxi_monitor_processStats = 0;
7956 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7959 static int rxi_monitor_peerStats = 0;
7962 * rxi_AddRpcStat - given all of the information for a particular rpc
7963 * call, create (if needed) and update the stat totals for the rpc.
7967 * IN stats - the queue of stats that will be updated with the new value
7969 * IN rxInterface - a unique number that identifies the rpc interface
7971 * IN currentFunc - the index of the function being invoked
7973 * IN totalFunc - the total number of functions in this interface
7975 * IN queueTime - the amount of time this function waited for a thread
7977 * IN execTime - the amount of time this function invocation took to execute
7979 * IN bytesSent - the number bytes sent by this invocation
7981 * IN bytesRcvd - the number bytes received by this invocation
7983 * IN isServer - if true, this invocation was made to a server
7985 * IN remoteHost - the ip address of the remote host
7987 * IN remotePort - the port of the remote host
7989 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7991 * INOUT counter - if a new stats structure is allocated, the counter will
7992 * be updated with the new number of allocated stat structures
8000 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8001 afs_uint32 currentFunc, afs_uint32 totalFunc,
8002 struct clock *queueTime, struct clock *execTime,
8003 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8004 afs_uint32 remoteHost, afs_uint32 remotePort,
8005 int addToPeerList, unsigned int *counter)
8008 rx_interface_stat_p rpc_stat, nrpc_stat;
8011 * See if there's already a structure for this interface
8014 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8015 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8016 && (rpc_stat->stats[0].remote_is_server == isServer))
8021 * Didn't find a match so allocate a new structure and add it to the
8025 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8026 || (rpc_stat->stats[0].interfaceId != rxInterface)
8027 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8032 sizeof(rx_interface_stat_t) +
8033 totalFunc * sizeof(rx_function_entry_v1_t);
8035 rpc_stat = rxi_Alloc(space);
8036 if (rpc_stat == NULL) {
8040 *counter += totalFunc;
8041 for (i = 0; i < totalFunc; i++) {
8042 rpc_stat->stats[i].remote_peer = remoteHost;
8043 rpc_stat->stats[i].remote_port = remotePort;
8044 rpc_stat->stats[i].remote_is_server = isServer;
8045 rpc_stat->stats[i].interfaceId = rxInterface;
8046 rpc_stat->stats[i].func_total = totalFunc;
8047 rpc_stat->stats[i].func_index = i;
8048 hzero(rpc_stat->stats[i].invocations);
8049 hzero(rpc_stat->stats[i].bytes_sent);
8050 hzero(rpc_stat->stats[i].bytes_rcvd);
8051 rpc_stat->stats[i].queue_time_sum.sec = 0;
8052 rpc_stat->stats[i].queue_time_sum.usec = 0;
8053 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8054 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8055 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8056 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8057 rpc_stat->stats[i].queue_time_max.sec = 0;
8058 rpc_stat->stats[i].queue_time_max.usec = 0;
8059 rpc_stat->stats[i].execution_time_sum.sec = 0;
8060 rpc_stat->stats[i].execution_time_sum.usec = 0;
8061 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8062 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8063 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8064 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8065 rpc_stat->stats[i].execution_time_max.sec = 0;
8066 rpc_stat->stats[i].execution_time_max.usec = 0;
8068 queue_Prepend(stats, rpc_stat);
8069 if (addToPeerList) {
8070 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8075 * Increment the stats for this function
8078 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8079 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8080 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8081 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8082 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8083 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8084 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8086 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8087 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8089 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8090 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8092 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8093 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8095 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8096 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8104 * rx_IncrementTimeAndCount - increment the times and count for a particular
8109 * IN peer - the peer who invoked the rpc
8111 * IN rxInterface - a unique number that identifies the rpc interface
8113 * IN currentFunc - the index of the function being invoked
8115 * IN totalFunc - the total number of functions in this interface
8117 * IN queueTime - the amount of time this function waited for a thread
8119 * IN execTime - the amount of time this function invocation took to execute
8121 * IN bytesSent - the number bytes sent by this invocation
8123 * IN bytesRcvd - the number bytes received by this invocation
8125 * IN isServer - if true, this invocation was made to a server
8133 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8134 afs_uint32 currentFunc, afs_uint32 totalFunc,
8135 struct clock *queueTime, struct clock *execTime,
8136 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8140 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8143 MUTEX_ENTER(&rx_rpc_stats);
8145 if (rxi_monitor_peerStats) {
8146 MUTEX_ENTER(&peer->peer_lock);
8147 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8148 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8149 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8150 MUTEX_EXIT(&peer->peer_lock);
8153 if (rxi_monitor_processStats) {
8154 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8155 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8156 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8159 MUTEX_EXIT(&rx_rpc_stats);
8164 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8168 * IN callerVersion - the rpc stat version of the caller.
8170 * IN count - the number of entries to marshall.
8172 * IN stats - pointer to stats to be marshalled.
8174 * OUT ptr - Where to store the marshalled data.
8181 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8182 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8188 * We only support the first version
8190 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8191 *(ptr++) = stats->remote_peer;
8192 *(ptr++) = stats->remote_port;
8193 *(ptr++) = stats->remote_is_server;
8194 *(ptr++) = stats->interfaceId;
8195 *(ptr++) = stats->func_total;
8196 *(ptr++) = stats->func_index;
8197 *(ptr++) = hgethi(stats->invocations);
8198 *(ptr++) = hgetlo(stats->invocations);
8199 *(ptr++) = hgethi(stats->bytes_sent);
8200 *(ptr++) = hgetlo(stats->bytes_sent);
8201 *(ptr++) = hgethi(stats->bytes_rcvd);
8202 *(ptr++) = hgetlo(stats->bytes_rcvd);
8203 *(ptr++) = stats->queue_time_sum.sec;
8204 *(ptr++) = stats->queue_time_sum.usec;
8205 *(ptr++) = stats->queue_time_sum_sqr.sec;
8206 *(ptr++) = stats->queue_time_sum_sqr.usec;
8207 *(ptr++) = stats->queue_time_min.sec;
8208 *(ptr++) = stats->queue_time_min.usec;
8209 *(ptr++) = stats->queue_time_max.sec;
8210 *(ptr++) = stats->queue_time_max.usec;
8211 *(ptr++) = stats->execution_time_sum.sec;
8212 *(ptr++) = stats->execution_time_sum.usec;
8213 *(ptr++) = stats->execution_time_sum_sqr.sec;
8214 *(ptr++) = stats->execution_time_sum_sqr.usec;
8215 *(ptr++) = stats->execution_time_min.sec;
8216 *(ptr++) = stats->execution_time_min.usec;
8217 *(ptr++) = stats->execution_time_max.sec;
8218 *(ptr++) = stats->execution_time_max.usec;
8224 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8229 * IN callerVersion - the rpc stat version of the caller
8231 * OUT myVersion - the rpc stat version of this function
8233 * OUT clock_sec - local time seconds
8235 * OUT clock_usec - local time microseconds
8237 * OUT allocSize - the number of bytes allocated to contain stats
8239 * OUT statCount - the number stats retrieved from this process.
8241 * OUT stats - the actual stats retrieved from this process.
8245 * Returns void. If successful, stats will != NULL.
8249 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8250 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8251 size_t * allocSize, afs_uint32 * statCount,
8252 afs_uint32 ** stats)
8262 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8265 * Check to see if stats are enabled
8268 MUTEX_ENTER(&rx_rpc_stats);
8269 if (!rxi_monitor_processStats) {
8270 MUTEX_EXIT(&rx_rpc_stats);
8274 clock_GetTime(&now);
8275 *clock_sec = now.sec;
8276 *clock_usec = now.usec;
8279 * Allocate the space based upon the caller version
8281 * If the client is at an older version than we are,
8282 * we return the statistic data in the older data format, but
8283 * we still return our version number so the client knows we
8284 * are maintaining more data than it can retrieve.
8287 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8288 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8289 *statCount = rxi_rpc_process_stat_cnt;
8292 * This can't happen yet, but in the future version changes
8293 * can be handled by adding additional code here
8297 if (space > (size_t) 0) {
8299 ptr = *stats = rxi_Alloc(space);
8302 rx_interface_stat_p rpc_stat, nrpc_stat;
8306 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8308 * Copy the data based upon the caller version
8310 rx_MarshallProcessRPCStats(callerVersion,
8311 rpc_stat->stats[0].func_total,
8312 rpc_stat->stats, &ptr);
8318 MUTEX_EXIT(&rx_rpc_stats);
8323 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8327 * IN callerVersion - the rpc stat version of the caller
8329 * OUT myVersion - the rpc stat version of this function
8331 * OUT clock_sec - local time seconds
8333 * OUT clock_usec - local time microseconds
8335 * OUT allocSize - the number of bytes allocated to contain stats
8337 * OUT statCount - the number of stats retrieved from the individual
8340 * OUT stats - the actual stats retrieved from the individual peer structures.
8344 * Returns void. If successful, stats will != NULL.
8348 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8349 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8350 size_t * allocSize, afs_uint32 * statCount,
8351 afs_uint32 ** stats)
8361 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8364 * Check to see if stats are enabled
8367 MUTEX_ENTER(&rx_rpc_stats);
8368 if (!rxi_monitor_peerStats) {
8369 MUTEX_EXIT(&rx_rpc_stats);
8373 clock_GetTime(&now);
8374 *clock_sec = now.sec;
8375 *clock_usec = now.usec;
8378 * Allocate the space based upon the caller version
8380 * If the client is at an older version than we are,
8381 * we return the statistic data in the older data format, but
8382 * we still return our version number so the client knows we
8383 * are maintaining more data than it can retrieve.
8386 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8387 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8388 *statCount = rxi_rpc_peer_stat_cnt;
8391 * This can't happen yet, but in the future version changes
8392 * can be handled by adding additional code here
8396 if (space > (size_t) 0) {
8398 ptr = *stats = rxi_Alloc(space);
8401 rx_interface_stat_p rpc_stat, nrpc_stat;
8405 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8407 * We have to fix the offset of rpc_stat since we are
8408 * keeping this structure on two rx_queues. The rx_queue
8409 * package assumes that the rx_queue member is the first
8410 * member of the structure. That is, rx_queue assumes that
8411 * any one item is only on one queue at a time. We are
8412 * breaking that assumption and so we have to do a little
8413 * math to fix our pointers.
8416 fix_offset = (char *)rpc_stat;
8417 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8418 rpc_stat = (rx_interface_stat_p) fix_offset;
8421 * Copy the data based upon the caller version
8423 rx_MarshallProcessRPCStats(callerVersion,
8424 rpc_stat->stats[0].func_total,
8425 rpc_stat->stats, &ptr);
8431 MUTEX_EXIT(&rx_rpc_stats);
8436 * rx_FreeRPCStats - free memory allocated by
8437 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8441 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8442 * rx_RetrievePeerRPCStats
8444 * IN allocSize - the number of bytes in stats.
8452 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8454 rxi_Free(stats, allocSize);
8458 * rx_queryProcessRPCStats - see if process rpc stat collection is
8459 * currently enabled.
8465 * Returns 0 if stats are not enabled != 0 otherwise
8469 rx_queryProcessRPCStats(void)
8472 MUTEX_ENTER(&rx_rpc_stats);
8473 rc = rxi_monitor_processStats;
8474 MUTEX_EXIT(&rx_rpc_stats);
8479 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8485 * Returns 0 if stats are not enabled != 0 otherwise
8489 rx_queryPeerRPCStats(void)
8492 MUTEX_ENTER(&rx_rpc_stats);
8493 rc = rxi_monitor_peerStats;
8494 MUTEX_EXIT(&rx_rpc_stats);
8499 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8509 rx_enableProcessRPCStats(void)
8511 MUTEX_ENTER(&rx_rpc_stats);
8512 rx_enable_stats = 1;
8513 rxi_monitor_processStats = 1;
8514 MUTEX_EXIT(&rx_rpc_stats);
8518 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8528 rx_enablePeerRPCStats(void)
8530 MUTEX_ENTER(&rx_rpc_stats);
8531 rx_enable_stats = 1;
8532 rxi_monitor_peerStats = 1;
8533 MUTEX_EXIT(&rx_rpc_stats);
8537 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8547 rx_disableProcessRPCStats(void)
8549 rx_interface_stat_p rpc_stat, nrpc_stat;
8552 MUTEX_ENTER(&rx_rpc_stats);
8555 * Turn off process statistics and if peer stats is also off, turn
8559 rxi_monitor_processStats = 0;
8560 if (rxi_monitor_peerStats == 0) {
8561 rx_enable_stats = 0;
8564 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8565 unsigned int num_funcs = 0;
8568 queue_Remove(rpc_stat);
8569 num_funcs = rpc_stat->stats[0].func_total;
8571 sizeof(rx_interface_stat_t) +
8572 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8574 rxi_Free(rpc_stat, space);
8575 rxi_rpc_process_stat_cnt -= num_funcs;
8577 MUTEX_EXIT(&rx_rpc_stats);
8581 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8591 rx_disablePeerRPCStats(void)
8593 struct rx_peer **peer_ptr, **peer_end;
8597 * Turn off peer statistics and if process stats is also off, turn
8601 rxi_monitor_peerStats = 0;
8602 if (rxi_monitor_processStats == 0) {
8603 rx_enable_stats = 0;
8606 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8607 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8609 struct rx_peer *peer, *next, *prev;
8611 MUTEX_ENTER(&rx_peerHashTable_lock);
8612 MUTEX_ENTER(&rx_rpc_stats);
8613 for (prev = peer = *peer_ptr; peer; peer = next) {
8615 code = MUTEX_TRYENTER(&peer->peer_lock);
8617 rx_interface_stat_p rpc_stat, nrpc_stat;
8620 if (prev == *peer_ptr) {
8631 MUTEX_EXIT(&rx_peerHashTable_lock);
8634 (&peer->rpcStats, rpc_stat, nrpc_stat,
8635 rx_interface_stat)) {
8636 unsigned int num_funcs = 0;
8639 queue_Remove(&rpc_stat->queue_header);
8640 queue_Remove(&rpc_stat->all_peers);
8641 num_funcs = rpc_stat->stats[0].func_total;
8643 sizeof(rx_interface_stat_t) +
8644 rpc_stat->stats[0].func_total *
8645 sizeof(rx_function_entry_v1_t);
8647 rxi_Free(rpc_stat, space);
8648 rxi_rpc_peer_stat_cnt -= num_funcs;
8650 MUTEX_EXIT(&peer->peer_lock);
8652 MUTEX_ENTER(&rx_peerHashTable_lock);
8662 MUTEX_EXIT(&rx_rpc_stats);
8663 MUTEX_EXIT(&rx_peerHashTable_lock);
8668 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8673 * IN clearFlag - flag indicating which stats to clear
8681 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8683 rx_interface_stat_p rpc_stat, nrpc_stat;
8685 MUTEX_ENTER(&rx_rpc_stats);
8687 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8688 unsigned int num_funcs = 0, i;
8689 num_funcs = rpc_stat->stats[0].func_total;
8690 for (i = 0; i < num_funcs; i++) {
8691 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8692 hzero(rpc_stat->stats[i].invocations);
8694 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8695 hzero(rpc_stat->stats[i].bytes_sent);
8697 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8698 hzero(rpc_stat->stats[i].bytes_rcvd);
8700 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8701 rpc_stat->stats[i].queue_time_sum.sec = 0;
8702 rpc_stat->stats[i].queue_time_sum.usec = 0;
8704 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8705 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8706 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8708 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8709 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8710 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8712 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8713 rpc_stat->stats[i].queue_time_max.sec = 0;
8714 rpc_stat->stats[i].queue_time_max.usec = 0;
8716 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8717 rpc_stat->stats[i].execution_time_sum.sec = 0;
8718 rpc_stat->stats[i].execution_time_sum.usec = 0;
8720 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8721 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8722 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8724 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8725 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8726 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8728 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8729 rpc_stat->stats[i].execution_time_max.sec = 0;
8730 rpc_stat->stats[i].execution_time_max.usec = 0;
8735 MUTEX_EXIT(&rx_rpc_stats);
8739 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8744 * IN clearFlag - flag indicating which stats to clear
8752 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8754 rx_interface_stat_p rpc_stat, nrpc_stat;
8756 MUTEX_ENTER(&rx_rpc_stats);
8758 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8759 unsigned int num_funcs = 0, i;
8762 * We have to fix the offset of rpc_stat since we are
8763 * keeping this structure on two rx_queues. The rx_queue
8764 * package assumes that the rx_queue member is the first
8765 * member of the structure. That is, rx_queue assumes that
8766 * any one item is only on one queue at a time. We are
8767 * breaking that assumption and so we have to do a little
8768 * math to fix our pointers.
8771 fix_offset = (char *)rpc_stat;
8772 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8773 rpc_stat = (rx_interface_stat_p) fix_offset;
8775 num_funcs = rpc_stat->stats[0].func_total;
8776 for (i = 0; i < num_funcs; i++) {
8777 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8778 hzero(rpc_stat->stats[i].invocations);
8780 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8781 hzero(rpc_stat->stats[i].bytes_sent);
8783 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8784 hzero(rpc_stat->stats[i].bytes_rcvd);
8786 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8787 rpc_stat->stats[i].queue_time_sum.sec = 0;
8788 rpc_stat->stats[i].queue_time_sum.usec = 0;
8790 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8791 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8792 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8794 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8795 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8796 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8798 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8799 rpc_stat->stats[i].queue_time_max.sec = 0;
8800 rpc_stat->stats[i].queue_time_max.usec = 0;
8802 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8803 rpc_stat->stats[i].execution_time_sum.sec = 0;
8804 rpc_stat->stats[i].execution_time_sum.usec = 0;
8806 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8807 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8808 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8810 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8811 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8812 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8814 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8815 rpc_stat->stats[i].execution_time_max.sec = 0;
8816 rpc_stat->stats[i].execution_time_max.usec = 0;
8821 MUTEX_EXIT(&rx_rpc_stats);
8825 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8826 * is authorized to enable/disable/clear RX statistics.
8828 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8831 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8833 rxi_rxstat_userok = proc;
8837 rx_RxStatUserOk(struct rx_call *call)
8839 if (!rxi_rxstat_userok)
8841 return rxi_rxstat_userok(call);
8846 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8847 * function in the MSVC runtime DLL (msvcrt.dll).
8849 * Note: the system serializes calls to this function.
8852 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8853 DWORD reason, /* reason function is being called */
8854 LPVOID reserved) /* reserved for future use */
8857 case DLL_PROCESS_ATTACH:
8858 /* library is being attached to a process */
8862 case DLL_PROCESS_DETACH:
8869 #endif /* AFS_NT40_ENV */
8872 int rx_DumpCalls(FILE *outputFile, char *cookie)
8874 #ifdef RXDEBUG_PACKET
8875 #ifdef KDUMP_RX_LOCK
8876 struct rx_call_rx_lock *c;
8883 #define RXDPRINTF sprintf
8884 #define RXDPRINTOUT output
8886 #define RXDPRINTF fprintf
8887 #define RXDPRINTOUT outputFile
8890 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8892 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8895 for (c = rx_allCallsp; c; c = c->allNextp) {
8896 u_short rqc, tqc, iovqc;
8897 struct rx_packet *p, *np;
8899 MUTEX_ENTER(&c->lock);
8900 queue_Count(&c->rq, p, np, rx_packet, rqc);
8901 queue_Count(&c->tq, p, np, rx_packet, tqc);
8902 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8904 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, "
8905 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8906 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8907 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8908 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8909 #ifdef RX_ENABLE_LOCKS
8912 #ifdef RX_REFCOUNT_CHECK
8913 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8914 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8917 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,
8918 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8919 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8920 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8921 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8922 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8923 #ifdef RX_ENABLE_LOCKS
8924 , (afs_uint32)c->refCount
8926 #ifdef RX_REFCOUNT_CHECK
8927 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8930 MUTEX_EXIT(&c->lock);
8933 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8936 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
8938 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8940 #endif /* RXDEBUG_PACKET */