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>
23 #include "afs/sysincludes.h"
24 #include "afsincludes.h"
30 #include <net/net_globals.h>
31 #endif /* AFS_OSF_ENV */
32 #ifdef AFS_LINUX20_ENV
35 #include "netinet/in.h"
37 #include "inet/common.h"
39 #include "inet/ip_ire.h"
41 #include "afs/afs_args.h"
42 #include "afs/afs_osi.h"
43 #ifdef RX_KERNEL_TRACE
44 #include "rx_kcommon.h"
46 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
50 #undef RXDEBUG /* turn off debugging */
52 #if defined(AFS_SGI_ENV)
53 #include "sys/debug.h"
62 #endif /* AFS_OSF_ENV */
64 #include "afs/sysincludes.h"
65 #include "afsincludes.h"
68 #include "rx_kmutex.h"
69 #include "rx_kernel.h"
73 #include "rx_globals.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 "rxgen_consts.h"
86 # include <sys/types.h>
93 # include <afs/afsutil.h>
94 # include <WINNT\afsreg.h>
96 # include <sys/socket.h>
97 # include <sys/file.h>
99 # include <sys/stat.h>
100 # include <netinet/in.h>
101 # include <sys/time.h>
104 # include "rx_user.h"
105 # include "rx_clock.h"
106 # include "rx_queue.h"
107 # include "rx_globals.h"
108 # include "rx_trace.h"
109 # include <afs/rxgen_consts.h>
113 #ifdef AFS_PTHREAD_ENV
115 int (*registerProgram) (pid_t, char *) = 0;
116 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
119 int (*registerProgram) (PROCESS, char *) = 0;
120 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
124 /* Local static routines */
125 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
126 #ifdef RX_ENABLE_LOCKS
127 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
130 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
132 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
133 afs_int32 rxi_start_in_error;
135 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
138 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
139 * currently allocated within rx. This number is used to allocate the
140 * memory required to return the statistics when queried.
143 static unsigned int rxi_rpc_peer_stat_cnt;
146 * rxi_rpc_process_stat_cnt counts the total number of local process stat
147 * structures currently allocated within rx. The number is used to allocate
148 * the memory required to return the statistics when queried.
151 static unsigned int rxi_rpc_process_stat_cnt;
153 #if !defined(offsetof)
154 #include <stddef.h> /* for definition of offsetof() */
157 #ifdef AFS_PTHREAD_ENV
161 * Use procedural initialization of mutexes/condition variables
165 extern afs_kmutex_t rx_stats_mutex;
166 extern afs_kmutex_t rx_waiting_mutex;
167 extern afs_kmutex_t rx_quota_mutex;
168 extern afs_kmutex_t rx_pthread_mutex;
169 extern afs_kmutex_t rx_packets_mutex;
170 extern afs_kmutex_t des_init_mutex;
171 extern afs_kmutex_t des_random_mutex;
172 extern afs_kmutex_t rx_clock_mutex;
173 extern afs_kmutex_t rxi_connCacheMutex;
174 extern afs_kmutex_t rx_event_mutex;
175 extern afs_kmutex_t osi_malloc_mutex;
176 extern afs_kmutex_t event_handler_mutex;
177 extern afs_kmutex_t listener_mutex;
178 extern afs_kmutex_t rx_if_init_mutex;
179 extern afs_kmutex_t rx_if_mutex;
180 extern afs_kmutex_t rxkad_client_uid_mutex;
181 extern afs_kmutex_t rxkad_random_mutex;
183 extern afs_kcondvar_t rx_event_handler_cond;
184 extern afs_kcondvar_t rx_listener_cond;
186 static afs_kmutex_t epoch_mutex;
187 static afs_kmutex_t rx_init_mutex;
188 static afs_kmutex_t rx_debug_mutex;
189 static afs_kmutex_t rx_rpc_stats;
192 rxi_InitPthread(void)
194 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_waiting_mutex, "waiting", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
215 assert(pthread_cond_init
216 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
217 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
219 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
220 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
222 rxkad_global_stats_init();
224 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
226 #ifdef RX_ENABLE_LOCKS
229 #endif /* RX_LOCKS_DB */
230 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
231 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
233 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
235 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
237 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
239 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
240 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
241 #endif /* RX_ENABLE_LOCKS */
244 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
245 #define INIT_PTHREAD_LOCKS \
246 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
248 * The rx_stats_mutex mutex protects the following global variables:
249 * rxi_lowConnRefCount
250 * rxi_lowPeerRefCount
259 * The rx_quota_mutex mutex protects the following global variables:
267 * The rx_freePktQ_lock protects the following global variables:
272 * The rx_packets_mutex mutex protects the following global variables:
280 * The rx_pthread_mutex mutex protects the following global variables:
284 #define INIT_PTHREAD_LOCKS
288 /* Variables for handling the minProcs implementation. availProcs gives the
289 * number of threads available in the pool at this moment (not counting dudes
290 * executing right now). totalMin gives the total number of procs required
291 * for handling all minProcs requests. minDeficit is a dynamic variable
292 * tracking the # of procs required to satisfy all of the remaining minProcs
294 * For fine grain locking to work, the quota check and the reservation of
295 * a server thread has to come while rxi_availProcs and rxi_minDeficit
296 * are locked. To this end, the code has been modified under #ifdef
297 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
298 * same time. A new function, ReturnToServerPool() returns the allocation.
300 * A call can be on several queue's (but only one at a time). When
301 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
302 * that no one else is touching the queue. To this end, we store the address
303 * of the queue lock in the call structure (under the call lock) when we
304 * put the call on a queue, and we clear the call_queue_lock when the
305 * call is removed from a queue (once the call lock has been obtained).
306 * This allows rxi_ResetCall to safely synchronize with others wishing
307 * to manipulate the queue.
310 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
311 static afs_kmutex_t rx_rpc_stats;
312 void rxi_StartUnlocked(struct rxevent *event, void *call,
313 void *arg1, int istack);
316 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
317 ** pretty good that the next packet coming in is from the same connection
318 ** as the last packet, since we're send multiple packets in a transmit window.
320 struct rx_connection *rxLastConn = 0;
322 #ifdef RX_ENABLE_LOCKS
323 /* The locking hierarchy for rx fine grain locking is composed of these
326 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
327 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
328 * call->lock - locks call data fields.
329 * These are independent of each other:
330 * rx_freeCallQueue_lock
335 * serverQueueEntry->lock
337 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
338 * peer->lock - locks peer data fields.
339 * conn_data_lock - that more than one thread is not updating a conn data
340 * field at the same time.
348 * Do we need a lock to protect the peer field in the conn structure?
349 * conn->peer was previously a constant for all intents and so has no
350 * lock protecting this field. The multihomed client delta introduced
351 * a RX code change : change the peer field in the connection structure
352 * to that remote inetrface from which the last packet for this
353 * connection was sent out. This may become an issue if further changes
356 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
357 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
359 /* rxdb_fileID is used to identify the lock location, along with line#. */
360 static int rxdb_fileID = RXDB_FILE_RX;
361 #endif /* RX_LOCKS_DB */
362 #else /* RX_ENABLE_LOCKS */
363 #define SET_CALL_QUEUE_LOCK(C, L)
364 #define CLEAR_CALL_QUEUE_LOCK(C)
365 #endif /* RX_ENABLE_LOCKS */
366 struct rx_serverQueueEntry *rx_waitForPacket = 0;
367 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
369 /* ------------Exported Interfaces------------- */
371 /* This function allows rxkad to set the epoch to a suitably random number
372 * which rx_NewConnection will use in the future. The principle purpose is to
373 * get rxnull connections to use the same epoch as the rxkad connections do, at
374 * least once the first rxkad connection is established. This is important now
375 * that the host/port addresses aren't used in FindConnection: the uniqueness
376 * of epoch/cid matters and the start time won't do. */
378 #ifdef AFS_PTHREAD_ENV
380 * This mutex protects the following global variables:
384 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
385 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
389 #endif /* AFS_PTHREAD_ENV */
392 rx_SetEpoch(afs_uint32 epoch)
399 /* Initialize rx. A port number may be mentioned, in which case this
400 * becomes the default port number for any service installed later.
401 * If 0 is provided for the port number, a random port will be chosen
402 * by the kernel. Whether this will ever overlap anything in
403 * /etc/services is anybody's guess... Returns 0 on success, -1 on
408 int rxinit_status = 1;
409 #ifdef AFS_PTHREAD_ENV
411 * This mutex protects the following global variables:
415 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
416 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
419 #define UNLOCK_RX_INIT
423 rx_InitHost(u_int host, u_int port)
430 char *htable, *ptable;
433 #if defined(AFS_DJGPP_ENV) && !defined(DEBUG)
434 __djgpp_set_quiet_socket(1);
441 if (rxinit_status == 0) {
442 tmp_status = rxinit_status;
444 return tmp_status; /* Already started; return previous error code. */
450 if (afs_winsockInit() < 0)
456 * Initialize anything necessary to provide a non-premptive threading
459 rxi_InitializeThreadSupport();
462 /* Allocate and initialize a socket for client and perhaps server
465 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
466 if (rx_socket == OSI_NULLSOCKET) {
470 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
473 #endif /* RX_LOCKS_DB */
474 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&rx_waiting_mutex, "rx_waiting_mutex", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
477 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
478 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
479 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
480 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
481 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
482 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
484 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
486 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
488 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
490 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
491 #if defined(AFS_HPUX110_ENV)
493 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
494 #endif /* AFS_HPUX110_ENV */
495 #endif /* RX_ENABLE_LOCKS && KERNEL */
498 rx_connDeadTime = 12;
499 rx_tranquil = 0; /* reset flag */
500 memset((char *)&rx_stats, 0, sizeof(struct rx_statistics));
502 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
503 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
504 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
505 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
506 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
507 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
509 /* Malloc up a bunch of packets & buffers */
511 queue_Init(&rx_freePacketQueue);
512 rxi_NeedMorePackets = FALSE;
513 #ifdef RX_ENABLE_TSFPQ
514 rx_nPackets = 0; /* in TSFPQ version, rx_nPackets is managed by rxi_MorePackets* */
515 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
516 #else /* RX_ENABLE_TSFPQ */
517 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
518 rxi_MorePackets(rx_nPackets);
519 #endif /* RX_ENABLE_TSFPQ */
526 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
527 tv.tv_sec = clock_now.sec;
528 tv.tv_usec = clock_now.usec;
529 srand((unsigned int)tv.tv_usec);
536 #if defined(KERNEL) && !defined(UKERNEL)
537 /* Really, this should never happen in a real kernel */
540 struct sockaddr_in addr;
542 int addrlen = sizeof(addr);
544 socklen_t addrlen = sizeof(addr);
546 if (getsockname((int)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
550 rx_port = addr.sin_port;
553 rx_stats.minRtt.sec = 9999999;
555 rx_SetEpoch(tv.tv_sec | 0x80000000);
557 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
558 * will provide a randomer value. */
560 MUTEX_ENTER(&rx_quota_mutex);
561 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
562 MUTEX_EXIT(&rx_quota_mutex);
563 /* *Slightly* random start time for the cid. This is just to help
564 * out with the hashing function at the peer */
565 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
566 rx_connHashTable = (struct rx_connection **)htable;
567 rx_peerHashTable = (struct rx_peer **)ptable;
569 rx_lastAckDelay.sec = 0;
570 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
571 rx_hardAckDelay.sec = 0;
572 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
573 rx_softAckDelay.sec = 0;
574 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
576 rxevent_Init(20, rxi_ReScheduleEvents);
578 /* Initialize various global queues */
579 queue_Init(&rx_idleServerQueue);
580 queue_Init(&rx_incomingCallQueue);
581 queue_Init(&rx_freeCallQueue);
583 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
584 /* Initialize our list of usable IP addresses. */
588 /* Start listener process (exact function is dependent on the
589 * implementation environment--kernel or user space) */
593 tmp_status = rxinit_status = 0;
601 return rx_InitHost(htonl(INADDR_ANY), port);
604 /* called with unincremented nRequestsRunning to see if it is OK to start
605 * a new thread in this service. Could be "no" for two reasons: over the
606 * max quota, or would prevent others from reaching their min quota.
608 #ifdef RX_ENABLE_LOCKS
609 /* This verion of QuotaOK reserves quota if it's ok while the
610 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
613 QuotaOK(struct rx_service *aservice)
615 /* check if over max quota */
616 if (aservice->nRequestsRunning >= aservice->maxProcs) {
620 /* under min quota, we're OK */
621 /* otherwise, can use only if there are enough to allow everyone
622 * to go to their min quota after this guy starts.
625 MUTEX_ENTER(&rx_quota_mutex);
626 if ((aservice->nRequestsRunning < aservice->minProcs)
627 || (rxi_availProcs > rxi_minDeficit)) {
628 aservice->nRequestsRunning++;
629 /* just started call in minProcs pool, need fewer to maintain
631 if (aservice->nRequestsRunning <= aservice->minProcs)
634 MUTEX_EXIT(&rx_quota_mutex);
637 MUTEX_EXIT(&rx_quota_mutex);
643 ReturnToServerPool(struct rx_service *aservice)
645 aservice->nRequestsRunning--;
646 MUTEX_ENTER(&rx_quota_mutex);
647 if (aservice->nRequestsRunning < aservice->minProcs)
650 MUTEX_EXIT(&rx_quota_mutex);
653 #else /* RX_ENABLE_LOCKS */
655 QuotaOK(struct rx_service *aservice)
658 /* under min quota, we're OK */
659 if (aservice->nRequestsRunning < aservice->minProcs)
662 /* check if over max quota */
663 if (aservice->nRequestsRunning >= aservice->maxProcs)
666 /* otherwise, can use only if there are enough to allow everyone
667 * to go to their min quota after this guy starts.
669 if (rxi_availProcs > rxi_minDeficit)
673 #endif /* RX_ENABLE_LOCKS */
676 /* Called by rx_StartServer to start up lwp's to service calls.
677 NExistingProcs gives the number of procs already existing, and which
678 therefore needn't be created. */
680 rxi_StartServerProcs(int nExistingProcs)
682 struct rx_service *service;
687 /* For each service, reserve N processes, where N is the "minimum"
688 * number of processes that MUST be able to execute a request in parallel,
689 * at any time, for that process. Also compute the maximum difference
690 * between any service's maximum number of processes that can run
691 * (i.e. the maximum number that ever will be run, and a guarantee
692 * that this number will run if other services aren't running), and its
693 * minimum number. The result is the extra number of processes that
694 * we need in order to provide the latter guarantee */
695 for (i = 0; i < RX_MAX_SERVICES; i++) {
697 service = rx_services[i];
698 if (service == (struct rx_service *)0)
700 nProcs += service->minProcs;
701 diff = service->maxProcs - service->minProcs;
705 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
706 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
707 for (i = 0; i < nProcs; i++) {
708 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
714 /* This routine is only required on Windows */
716 rx_StartClientThread(void)
718 #ifdef AFS_PTHREAD_ENV
720 pid = pthread_self();
721 #endif /* AFS_PTHREAD_ENV */
723 #endif /* AFS_NT40_ENV */
725 /* This routine must be called if any services are exported. If the
726 * donateMe flag is set, the calling process is donated to the server
729 rx_StartServer(int donateMe)
731 struct rx_service *service;
737 /* Start server processes, if necessary (exact function is dependent
738 * on the implementation environment--kernel or user space). DonateMe
739 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
740 * case, one less new proc will be created rx_StartServerProcs.
742 rxi_StartServerProcs(donateMe);
744 /* count up the # of threads in minProcs, and add set the min deficit to
745 * be that value, too.
747 for (i = 0; i < RX_MAX_SERVICES; i++) {
748 service = rx_services[i];
749 if (service == (struct rx_service *)0)
751 MUTEX_ENTER(&rx_quota_mutex);
752 rxi_totalMin += service->minProcs;
753 /* below works even if a thread is running, since minDeficit would
754 * still have been decremented and later re-incremented.
756 rxi_minDeficit += service->minProcs;
757 MUTEX_EXIT(&rx_quota_mutex);
760 /* Turn on reaping of idle server connections */
761 rxi_ReapConnections(NULL, NULL, NULL);
770 #ifdef AFS_PTHREAD_ENV
772 pid = (pid_t) pthread_self();
773 #else /* AFS_PTHREAD_ENV */
775 LWP_CurrentProcess(&pid);
776 #endif /* AFS_PTHREAD_ENV */
778 sprintf(name, "srv_%d", ++nProcs);
780 (*registerProgram) (pid, name);
782 #endif /* AFS_NT40_ENV */
783 rx_ServerProc(NULL); /* Never returns */
785 #ifdef RX_ENABLE_TSFPQ
786 /* no use leaving packets around in this thread's local queue if
787 * it isn't getting donated to the server thread pool.
789 rxi_FlushLocalPacketsTSFPQ();
790 #endif /* RX_ENABLE_TSFPQ */
794 /* Create a new client connection to the specified service, using the
795 * specified security object to implement the security model for this
797 struct rx_connection *
798 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
799 struct rx_securityClass *securityObject,
800 int serviceSecurityIndex)
804 struct rx_connection *conn;
809 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n", ntohl(shost), ntohs(sport), sservice, securityObject, serviceSecurityIndex));
811 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
812 * the case of kmem_alloc? */
813 conn = rxi_AllocConnection();
814 #ifdef RX_ENABLE_LOCKS
815 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
816 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
817 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
820 MUTEX_ENTER(&rx_connHashTable_lock);
821 cid = (rx_nextCid += RX_MAXCALLS);
822 conn->type = RX_CLIENT_CONNECTION;
824 conn->epoch = rx_epoch;
825 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
826 conn->serviceId = sservice;
827 conn->securityObject = securityObject;
828 conn->securityData = (void *) 0;
829 conn->securityIndex = serviceSecurityIndex;
830 rx_SetConnDeadTime(conn, rx_connDeadTime);
831 conn->ackRate = RX_FAST_ACK_RATE;
833 conn->specific = NULL;
834 conn->challengeEvent = NULL;
835 conn->delayedAbortEvent = NULL;
836 conn->abortCount = 0;
838 for (i = 0; i < RX_MAXCALLS; i++) {
839 conn->twind[i] = rx_initSendWindow;
840 conn->rwind[i] = rx_initReceiveWindow;
843 RXS_NewConnection(securityObject, conn);
845 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
847 conn->refCount++; /* no lock required since only this thread knows... */
848 conn->next = rx_connHashTable[hashindex];
849 rx_connHashTable[hashindex] = conn;
851 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
852 MUTEX_EXIT(&rx_connHashTable_lock);
858 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
860 /* The idea is to set the dead time to a value that allows several
861 * keepalives to be dropped without timing out the connection. */
862 conn->secondsUntilDead = MAX(seconds, 6);
863 conn->secondsUntilPing = conn->secondsUntilDead / 6;
866 int rxi_lowPeerRefCount = 0;
867 int rxi_lowConnRefCount = 0;
870 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
871 * NOTE: must not be called with rx_connHashTable_lock held.
874 rxi_CleanupConnection(struct rx_connection *conn)
876 /* Notify the service exporter, if requested, that this connection
877 * is being destroyed */
878 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
879 (*conn->service->destroyConnProc) (conn);
881 /* Notify the security module that this connection is being destroyed */
882 RXS_DestroyConnection(conn->securityObject, conn);
884 /* If this is the last connection using the rx_peer struct, set its
885 * idle time to now. rxi_ReapConnections will reap it if it's still
886 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
888 MUTEX_ENTER(&rx_peerHashTable_lock);
889 if (conn->peer->refCount < 2) {
890 conn->peer->idleWhen = clock_Sec();
891 if (conn->peer->refCount < 1) {
892 conn->peer->refCount = 1;
893 if (rx_stats_active) {
894 MUTEX_ENTER(&rx_stats_mutex);
895 rxi_lowPeerRefCount++;
896 MUTEX_EXIT(&rx_stats_mutex);
900 conn->peer->refCount--;
901 MUTEX_EXIT(&rx_peerHashTable_lock);
905 if (conn->type == RX_SERVER_CONNECTION)
906 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
908 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
911 if (conn->specific) {
913 for (i = 0; i < conn->nSpecific; i++) {
914 if (conn->specific[i] && rxi_keyCreate_destructor[i])
915 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
916 conn->specific[i] = NULL;
918 free(conn->specific);
920 conn->specific = NULL;
924 MUTEX_DESTROY(&conn->conn_call_lock);
925 MUTEX_DESTROY(&conn->conn_data_lock);
926 CV_DESTROY(&conn->conn_call_cv);
928 rxi_FreeConnection(conn);
931 /* Destroy the specified connection */
933 rxi_DestroyConnection(struct rx_connection *conn)
935 MUTEX_ENTER(&rx_connHashTable_lock);
936 rxi_DestroyConnectionNoLock(conn);
937 /* conn should be at the head of the cleanup list */
938 if (conn == rx_connCleanup_list) {
939 rx_connCleanup_list = rx_connCleanup_list->next;
940 MUTEX_EXIT(&rx_connHashTable_lock);
941 rxi_CleanupConnection(conn);
943 #ifdef RX_ENABLE_LOCKS
945 MUTEX_EXIT(&rx_connHashTable_lock);
947 #endif /* RX_ENABLE_LOCKS */
951 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
953 struct rx_connection **conn_ptr;
955 struct rx_packet *packet;
962 MUTEX_ENTER(&conn->conn_data_lock);
963 if (conn->refCount > 0)
966 if (rx_stats_active) {
967 MUTEX_ENTER(&rx_stats_mutex);
968 rxi_lowConnRefCount++;
969 MUTEX_EXIT(&rx_stats_mutex);
973 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
974 /* Busy; wait till the last guy before proceeding */
975 MUTEX_EXIT(&conn->conn_data_lock);
980 /* If the client previously called rx_NewCall, but it is still
981 * waiting, treat this as a running call, and wait to destroy the
982 * connection later when the call completes. */
983 if ((conn->type == RX_CLIENT_CONNECTION)
984 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
985 conn->flags |= RX_CONN_DESTROY_ME;
986 MUTEX_EXIT(&conn->conn_data_lock);
990 MUTEX_EXIT(&conn->conn_data_lock);
992 /* Check for extant references to this connection */
993 for (i = 0; i < RX_MAXCALLS; i++) {
994 struct rx_call *call = conn->call[i];
997 if (conn->type == RX_CLIENT_CONNECTION) {
998 MUTEX_ENTER(&call->lock);
999 if (call->delayedAckEvent) {
1000 /* Push the final acknowledgment out now--there
1001 * won't be a subsequent call to acknowledge the
1002 * last reply packets */
1003 rxevent_Cancel(call->delayedAckEvent, call,
1004 RX_CALL_REFCOUNT_DELAY);
1005 if (call->state == RX_STATE_PRECALL
1006 || call->state == RX_STATE_ACTIVE) {
1007 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1009 rxi_AckAll(NULL, call, 0);
1012 MUTEX_EXIT(&call->lock);
1016 #ifdef RX_ENABLE_LOCKS
1018 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1019 MUTEX_EXIT(&conn->conn_data_lock);
1021 /* Someone is accessing a packet right now. */
1025 #endif /* RX_ENABLE_LOCKS */
1028 /* Don't destroy the connection if there are any call
1029 * structures still in use */
1030 MUTEX_ENTER(&conn->conn_data_lock);
1031 conn->flags |= RX_CONN_DESTROY_ME;
1032 MUTEX_EXIT(&conn->conn_data_lock);
1037 if (conn->delayedAbortEvent) {
1038 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1039 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1041 MUTEX_ENTER(&conn->conn_data_lock);
1042 rxi_SendConnectionAbort(conn, packet, 0, 1);
1043 MUTEX_EXIT(&conn->conn_data_lock);
1044 rxi_FreePacket(packet);
1048 /* Remove from connection hash table before proceeding */
1050 &rx_connHashTable[CONN_HASH
1051 (peer->host, peer->port, conn->cid, conn->epoch,
1053 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1054 if (*conn_ptr == conn) {
1055 *conn_ptr = conn->next;
1059 /* if the conn that we are destroying was the last connection, then we
1060 * clear rxLastConn as well */
1061 if (rxLastConn == conn)
1064 /* Make sure the connection is completely reset before deleting it. */
1065 /* get rid of pending events that could zap us later */
1066 if (conn->challengeEvent)
1067 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1068 if (conn->checkReachEvent)
1069 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1071 /* Add the connection to the list of destroyed connections that
1072 * need to be cleaned up. This is necessary to avoid deadlocks
1073 * in the routines we call to inform others that this connection is
1074 * being destroyed. */
1075 conn->next = rx_connCleanup_list;
1076 rx_connCleanup_list = conn;
1079 /* Externally available version */
1081 rx_DestroyConnection(struct rx_connection *conn)
1086 rxi_DestroyConnection(conn);
1091 rx_GetConnection(struct rx_connection *conn)
1096 MUTEX_ENTER(&conn->conn_data_lock);
1098 MUTEX_EXIT(&conn->conn_data_lock);
1102 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1103 /* Wait for the transmit queue to no longer be busy.
1104 * requires the call->lock to be held */
1105 static void rxi_WaitforTQBusy(struct rx_call *call) {
1106 while (call->flags & RX_CALL_TQ_BUSY) {
1107 call->flags |= RX_CALL_TQ_WAIT;
1109 #ifdef RX_ENABLE_LOCKS
1110 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1111 CV_WAIT(&call->cv_tq, &call->lock);
1112 #else /* RX_ENABLE_LOCKS */
1113 osi_rxSleep(&call->tq);
1114 #endif /* RX_ENABLE_LOCKS */
1116 if (call->tqWaiters == 0) {
1117 call->flags &= ~RX_CALL_TQ_WAIT;
1123 /* Start a new rx remote procedure call, on the specified connection.
1124 * If wait is set to 1, wait for a free call channel; otherwise return
1125 * 0. Maxtime gives the maximum number of seconds this call may take,
1126 * after rx_NewCall returns. After this time interval, a call to any
1127 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1128 * For fine grain locking, we hold the conn_call_lock in order to
1129 * to ensure that we don't get signalle after we found a call in an active
1130 * state and before we go to sleep.
1133 rx_NewCall(struct rx_connection *conn)
1136 struct rx_call *call;
1137 struct clock queueTime;
1141 dpf(("rx_NewCall(conn %x)\n", conn));
1144 clock_GetTime(&queueTime);
1145 MUTEX_ENTER(&conn->conn_call_lock);
1148 * Check if there are others waiting for a new call.
1149 * If so, let them go first to avoid starving them.
1150 * This is a fairly simple scheme, and might not be
1151 * a complete solution for large numbers of waiters.
1153 * makeCallWaiters keeps track of the number of
1154 * threads waiting to make calls and the
1155 * RX_CONN_MAKECALL_WAITING flag bit is used to
1156 * indicate that there are indeed calls waiting.
1157 * The flag is set when the waiter is incremented.
1158 * It is only cleared in rx_EndCall when
1159 * makeCallWaiters is 0. This prevents us from
1160 * accidently destroying the connection while it
1161 * is potentially about to be used.
1163 MUTEX_ENTER(&conn->conn_data_lock);
1164 if (conn->makeCallWaiters) {
1165 conn->flags |= RX_CONN_MAKECALL_WAITING;
1166 conn->makeCallWaiters++;
1167 MUTEX_EXIT(&conn->conn_data_lock);
1169 #ifdef RX_ENABLE_LOCKS
1170 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1174 MUTEX_ENTER(&conn->conn_data_lock);
1175 conn->makeCallWaiters--;
1177 MUTEX_EXIT(&conn->conn_data_lock);
1180 for (i = 0; i < RX_MAXCALLS; i++) {
1181 call = conn->call[i];
1183 MUTEX_ENTER(&call->lock);
1184 if (call->state == RX_STATE_DALLY) {
1185 rxi_ResetCall(call, 0);
1186 (*call->callNumber)++;
1189 MUTEX_EXIT(&call->lock);
1191 call = rxi_NewCall(conn, i);
1195 if (i < RX_MAXCALLS) {
1198 MUTEX_ENTER(&conn->conn_data_lock);
1199 conn->flags |= RX_CONN_MAKECALL_WAITING;
1200 conn->makeCallWaiters++;
1201 MUTEX_EXIT(&conn->conn_data_lock);
1203 #ifdef RX_ENABLE_LOCKS
1204 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1208 MUTEX_ENTER(&conn->conn_data_lock);
1209 conn->makeCallWaiters--;
1210 MUTEX_EXIT(&conn->conn_data_lock);
1213 * Wake up anyone else who might be giving us a chance to
1214 * run (see code above that avoids resource starvation).
1216 #ifdef RX_ENABLE_LOCKS
1217 CV_BROADCAST(&conn->conn_call_cv);
1222 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1224 /* Client is initially in send mode */
1225 call->state = RX_STATE_ACTIVE;
1226 call->error = conn->error;
1228 call->mode = RX_MODE_ERROR;
1230 call->mode = RX_MODE_SENDING;
1232 /* remember start time for call in case we have hard dead time limit */
1233 call->queueTime = queueTime;
1234 clock_GetTime(&call->startTime);
1235 hzero(call->bytesSent);
1236 hzero(call->bytesRcvd);
1238 /* Turn on busy protocol. */
1239 rxi_KeepAliveOn(call);
1241 MUTEX_EXIT(&call->lock);
1242 MUTEX_EXIT(&conn->conn_call_lock);
1245 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1246 /* Now, if TQ wasn't cleared earlier, do it now. */
1247 MUTEX_ENTER(&call->lock);
1248 rxi_WaitforTQBusy(call);
1249 if (call->flags & RX_CALL_TQ_CLEARME) {
1250 rxi_ClearTransmitQueue(call, 1);
1251 /*queue_Init(&call->tq);*/
1253 MUTEX_EXIT(&call->lock);
1254 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1256 dpf(("rx_NewCall(call %x)\n", call));
1261 rxi_HasActiveCalls(struct rx_connection *aconn)
1264 struct rx_call *tcall;
1268 for (i = 0; i < RX_MAXCALLS; i++) {
1269 if ((tcall = aconn->call[i])) {
1270 if ((tcall->state == RX_STATE_ACTIVE)
1271 || (tcall->state == RX_STATE_PRECALL)) {
1282 rxi_GetCallNumberVector(struct rx_connection *aconn,
1283 afs_int32 * aint32s)
1286 struct rx_call *tcall;
1290 for (i = 0; i < RX_MAXCALLS; i++) {
1291 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1292 aint32s[i] = aconn->callNumber[i] + 1;
1294 aint32s[i] = aconn->callNumber[i];
1301 rxi_SetCallNumberVector(struct rx_connection *aconn,
1302 afs_int32 * aint32s)
1305 struct rx_call *tcall;
1309 for (i = 0; i < RX_MAXCALLS; i++) {
1310 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1311 aconn->callNumber[i] = aint32s[i] - 1;
1313 aconn->callNumber[i] = aint32s[i];
1319 /* Advertise a new service. A service is named locally by a UDP port
1320 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1323 char *serviceName; Name for identification purposes (e.g. the
1324 service name might be used for probing for
1327 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1328 char *serviceName, struct rx_securityClass **securityObjects,
1329 int nSecurityObjects,
1330 afs_int32(*serviceProc) (struct rx_call * acall))
1332 osi_socket socket = OSI_NULLSOCKET;
1333 struct rx_service *tservice;
1339 if (serviceId == 0) {
1341 "rx_NewService: service id for service %s is not non-zero.\n",
1348 "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",
1356 tservice = rxi_AllocService();
1358 for (i = 0; i < RX_MAX_SERVICES; i++) {
1359 struct rx_service *service = rx_services[i];
1361 if (port == service->servicePort && host == service->serviceHost) {
1362 if (service->serviceId == serviceId) {
1363 /* The identical service has already been
1364 * installed; if the caller was intending to
1365 * change the security classes used by this
1366 * service, he/she loses. */
1368 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1369 serviceName, serviceId, service->serviceName);
1371 rxi_FreeService(tservice);
1374 /* Different service, same port: re-use the socket
1375 * which is bound to the same port */
1376 socket = service->socket;
1379 if (socket == OSI_NULLSOCKET) {
1380 /* If we don't already have a socket (from another
1381 * service on same port) get a new one */
1382 socket = rxi_GetHostUDPSocket(host, port);
1383 if (socket == OSI_NULLSOCKET) {
1385 rxi_FreeService(tservice);
1390 service->socket = socket;
1391 service->serviceHost = host;
1392 service->servicePort = port;
1393 service->serviceId = serviceId;
1394 service->serviceName = serviceName;
1395 service->nSecurityObjects = nSecurityObjects;
1396 service->securityObjects = securityObjects;
1397 service->minProcs = 0;
1398 service->maxProcs = 1;
1399 service->idleDeadTime = 60;
1400 service->idleDeadErr = 0;
1401 service->connDeadTime = rx_connDeadTime;
1402 service->executeRequestProc = serviceProc;
1403 service->checkReach = 0;
1404 rx_services[i] = service; /* not visible until now */
1410 rxi_FreeService(tservice);
1411 (osi_Msg "rx_NewService: cannot support > %d services\n",
1416 /* Set configuration options for all of a service's security objects */
1419 rx_SetSecurityConfiguration(struct rx_service *service,
1420 rx_securityConfigVariables type,
1424 for (i = 0; i<service->nSecurityObjects; i++) {
1425 if (service->securityObjects[i]) {
1426 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1434 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1435 struct rx_securityClass **securityObjects, int nSecurityObjects,
1436 afs_int32(*serviceProc) (struct rx_call * acall))
1438 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1441 /* Generic request processing loop. This routine should be called
1442 * by the implementation dependent rx_ServerProc. If socketp is
1443 * non-null, it will be set to the file descriptor that this thread
1444 * is now listening on. If socketp is null, this routine will never
1447 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1449 struct rx_call *call;
1451 struct rx_service *tservice = NULL;
1458 call = rx_GetCall(threadID, tservice, socketp);
1459 if (socketp && *socketp != OSI_NULLSOCKET) {
1460 /* We are now a listener thread */
1465 /* if server is restarting( typically smooth shutdown) then do not
1466 * allow any new calls.
1469 if (rx_tranquil && (call != NULL)) {
1473 MUTEX_ENTER(&call->lock);
1475 rxi_CallError(call, RX_RESTARTING);
1476 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1478 MUTEX_EXIT(&call->lock);
1482 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1483 #ifdef RX_ENABLE_LOCKS
1485 #endif /* RX_ENABLE_LOCKS */
1486 afs_termState = AFSOP_STOP_AFS;
1487 afs_osi_Wakeup(&afs_termState);
1488 #ifdef RX_ENABLE_LOCKS
1490 #endif /* RX_ENABLE_LOCKS */
1495 tservice = call->conn->service;
1497 if (tservice->beforeProc)
1498 (*tservice->beforeProc) (call);
1500 code = call->conn->service->executeRequestProc(call);
1502 if (tservice->afterProc)
1503 (*tservice->afterProc) (call, code);
1505 rx_EndCall(call, code);
1506 if (rx_stats_active) {
1507 MUTEX_ENTER(&rx_stats_mutex);
1509 MUTEX_EXIT(&rx_stats_mutex);
1516 rx_WakeupServerProcs(void)
1518 struct rx_serverQueueEntry *np, *tqp;
1522 MUTEX_ENTER(&rx_serverPool_lock);
1524 #ifdef RX_ENABLE_LOCKS
1525 if (rx_waitForPacket)
1526 CV_BROADCAST(&rx_waitForPacket->cv);
1527 #else /* RX_ENABLE_LOCKS */
1528 if (rx_waitForPacket)
1529 osi_rxWakeup(rx_waitForPacket);
1530 #endif /* RX_ENABLE_LOCKS */
1531 MUTEX_ENTER(&freeSQEList_lock);
1532 for (np = rx_FreeSQEList; np; np = tqp) {
1533 tqp = *(struct rx_serverQueueEntry **)np;
1534 #ifdef RX_ENABLE_LOCKS
1535 CV_BROADCAST(&np->cv);
1536 #else /* RX_ENABLE_LOCKS */
1538 #endif /* RX_ENABLE_LOCKS */
1540 MUTEX_EXIT(&freeSQEList_lock);
1541 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1542 #ifdef RX_ENABLE_LOCKS
1543 CV_BROADCAST(&np->cv);
1544 #else /* RX_ENABLE_LOCKS */
1546 #endif /* RX_ENABLE_LOCKS */
1548 MUTEX_EXIT(&rx_serverPool_lock);
1553 * One thing that seems to happen is that all the server threads get
1554 * tied up on some empty or slow call, and then a whole bunch of calls
1555 * arrive at once, using up the packet pool, so now there are more
1556 * empty calls. The most critical resources here are server threads
1557 * and the free packet pool. The "doreclaim" code seems to help in
1558 * general. I think that eventually we arrive in this state: there
1559 * are lots of pending calls which do have all their packets present,
1560 * so they won't be reclaimed, are multi-packet calls, so they won't
1561 * be scheduled until later, and thus are tying up most of the free
1562 * packet pool for a very long time.
1564 * 1. schedule multi-packet calls if all the packets are present.
1565 * Probably CPU-bound operation, useful to return packets to pool.
1566 * Do what if there is a full window, but the last packet isn't here?
1567 * 3. preserve one thread which *only* runs "best" calls, otherwise
1568 * it sleeps and waits for that type of call.
1569 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1570 * the current dataquota business is badly broken. The quota isn't adjusted
1571 * to reflect how many packets are presently queued for a running call.
1572 * So, when we schedule a queued call with a full window of packets queued
1573 * up for it, that *should* free up a window full of packets for other 2d-class
1574 * calls to be able to use from the packet pool. But it doesn't.
1576 * NB. Most of the time, this code doesn't run -- since idle server threads
1577 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1578 * as a new call arrives.
1580 /* Sleep until a call arrives. Returns a pointer to the call, ready
1581 * for an rx_Read. */
1582 #ifdef RX_ENABLE_LOCKS
1584 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1586 struct rx_serverQueueEntry *sq;
1587 struct rx_call *call = (struct rx_call *)0;
1588 struct rx_service *service = NULL;
1591 MUTEX_ENTER(&freeSQEList_lock);
1593 if ((sq = rx_FreeSQEList)) {
1594 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1595 MUTEX_EXIT(&freeSQEList_lock);
1596 } else { /* otherwise allocate a new one and return that */
1597 MUTEX_EXIT(&freeSQEList_lock);
1598 sq = (struct rx_serverQueueEntry *)
1599 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1600 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1601 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1604 MUTEX_ENTER(&rx_serverPool_lock);
1605 if (cur_service != NULL) {
1606 ReturnToServerPool(cur_service);
1609 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1610 struct rx_call *tcall, *ncall, *choice2 = NULL;
1612 /* Scan for eligible incoming calls. A call is not eligible
1613 * if the maximum number of calls for its service type are
1614 * already executing */
1615 /* One thread will process calls FCFS (to prevent starvation),
1616 * while the other threads may run ahead looking for calls which
1617 * have all their input data available immediately. This helps
1618 * keep threads from blocking, waiting for data from the client. */
1619 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1620 service = tcall->conn->service;
1621 if (!QuotaOK(service)) {
1624 MUTEX_ENTER(&rx_pthread_mutex);
1625 if (tno == rxi_fcfs_thread_num
1626 || !tcall->queue_item_header.next) {
1627 MUTEX_EXIT(&rx_pthread_mutex);
1628 /* If we're the fcfs thread , then we'll just use
1629 * this call. If we haven't been able to find an optimal
1630 * choice, and we're at the end of the list, then use a
1631 * 2d choice if one has been identified. Otherwise... */
1632 call = (choice2 ? choice2 : tcall);
1633 service = call->conn->service;
1635 MUTEX_EXIT(&rx_pthread_mutex);
1636 if (!queue_IsEmpty(&tcall->rq)) {
1637 struct rx_packet *rp;
1638 rp = queue_First(&tcall->rq, rx_packet);
1639 if (rp->header.seq == 1) {
1641 || (rp->header.flags & RX_LAST_PACKET)) {
1643 } else if (rxi_2dchoice && !choice2
1644 && !(tcall->flags & RX_CALL_CLEARED)
1645 && (tcall->rprev > rxi_HardAckRate)) {
1655 ReturnToServerPool(service);
1662 MUTEX_EXIT(&rx_serverPool_lock);
1663 MUTEX_ENTER(&call->lock);
1665 if (call->flags & RX_CALL_WAIT_PROC) {
1666 call->flags &= ~RX_CALL_WAIT_PROC;
1667 MUTEX_ENTER(&rx_waiting_mutex);
1669 MUTEX_EXIT(&rx_waiting_mutex);
1672 if (call->state != RX_STATE_PRECALL || call->error) {
1673 MUTEX_EXIT(&call->lock);
1674 MUTEX_ENTER(&rx_serverPool_lock);
1675 ReturnToServerPool(service);
1680 if (queue_IsEmpty(&call->rq)
1681 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1682 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1684 CLEAR_CALL_QUEUE_LOCK(call);
1687 /* If there are no eligible incoming calls, add this process
1688 * to the idle server queue, to wait for one */
1692 *socketp = OSI_NULLSOCKET;
1694 sq->socketp = socketp;
1695 queue_Append(&rx_idleServerQueue, sq);
1696 #ifndef AFS_AIX41_ENV
1697 rx_waitForPacket = sq;
1699 rx_waitingForPacket = sq;
1700 #endif /* AFS_AIX41_ENV */
1702 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1704 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1705 MUTEX_EXIT(&rx_serverPool_lock);
1706 return (struct rx_call *)0;
1709 } while (!(call = sq->newcall)
1710 && !(socketp && *socketp != OSI_NULLSOCKET));
1711 MUTEX_EXIT(&rx_serverPool_lock);
1713 MUTEX_ENTER(&call->lock);
1719 MUTEX_ENTER(&freeSQEList_lock);
1720 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1721 rx_FreeSQEList = sq;
1722 MUTEX_EXIT(&freeSQEList_lock);
1725 clock_GetTime(&call->startTime);
1726 call->state = RX_STATE_ACTIVE;
1727 call->mode = RX_MODE_RECEIVING;
1728 #ifdef RX_KERNEL_TRACE
1729 if (ICL_SETACTIVE(afs_iclSetp)) {
1730 int glockOwner = ISAFS_GLOCK();
1733 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1734 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1741 rxi_calltrace(RX_CALL_START, call);
1742 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1743 call->conn->service->servicePort, call->conn->service->serviceId,
1746 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1747 MUTEX_EXIT(&call->lock);
1749 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1754 #else /* RX_ENABLE_LOCKS */
1756 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1758 struct rx_serverQueueEntry *sq;
1759 struct rx_call *call = (struct rx_call *)0, *choice2;
1760 struct rx_service *service = NULL;
1764 MUTEX_ENTER(&freeSQEList_lock);
1766 if ((sq = rx_FreeSQEList)) {
1767 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1768 MUTEX_EXIT(&freeSQEList_lock);
1769 } else { /* otherwise allocate a new one and return that */
1770 MUTEX_EXIT(&freeSQEList_lock);
1771 sq = (struct rx_serverQueueEntry *)
1772 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1773 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1774 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1776 MUTEX_ENTER(&sq->lock);
1778 if (cur_service != NULL) {
1779 cur_service->nRequestsRunning--;
1780 if (cur_service->nRequestsRunning < cur_service->minProcs)
1784 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1785 struct rx_call *tcall, *ncall;
1786 /* Scan for eligible incoming calls. A call is not eligible
1787 * if the maximum number of calls for its service type are
1788 * already executing */
1789 /* One thread will process calls FCFS (to prevent starvation),
1790 * while the other threads may run ahead looking for calls which
1791 * have all their input data available immediately. This helps
1792 * keep threads from blocking, waiting for data from the client. */
1793 choice2 = (struct rx_call *)0;
1794 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1795 service = tcall->conn->service;
1796 if (QuotaOK(service)) {
1797 MUTEX_ENTER(&rx_pthread_mutex);
1798 if (tno == rxi_fcfs_thread_num
1799 || !tcall->queue_item_header.next) {
1800 MUTEX_EXIT(&rx_pthread_mutex);
1801 /* If we're the fcfs thread, then we'll just use
1802 * this call. If we haven't been able to find an optimal
1803 * choice, and we're at the end of the list, then use a
1804 * 2d choice if one has been identified. Otherwise... */
1805 call = (choice2 ? choice2 : tcall);
1806 service = call->conn->service;
1808 MUTEX_EXIT(&rx_pthread_mutex);
1809 if (!queue_IsEmpty(&tcall->rq)) {
1810 struct rx_packet *rp;
1811 rp = queue_First(&tcall->rq, rx_packet);
1812 if (rp->header.seq == 1
1814 || (rp->header.flags & RX_LAST_PACKET))) {
1816 } else if (rxi_2dchoice && !choice2
1817 && !(tcall->flags & RX_CALL_CLEARED)
1818 && (tcall->rprev > rxi_HardAckRate)) {
1832 /* we can't schedule a call if there's no data!!! */
1833 /* send an ack if there's no data, if we're missing the
1834 * first packet, or we're missing something between first
1835 * and last -- there's a "hole" in the incoming data. */
1836 if (queue_IsEmpty(&call->rq)
1837 || queue_First(&call->rq, rx_packet)->header.seq != 1
1838 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1839 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1841 call->flags &= (~RX_CALL_WAIT_PROC);
1842 service->nRequestsRunning++;
1843 /* just started call in minProcs pool, need fewer to maintain
1845 if (service->nRequestsRunning <= service->minProcs)
1849 /* MUTEX_EXIT(&call->lock); */
1851 /* If there are no eligible incoming calls, add this process
1852 * to the idle server queue, to wait for one */
1855 *socketp = OSI_NULLSOCKET;
1857 sq->socketp = socketp;
1858 queue_Append(&rx_idleServerQueue, sq);
1862 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1864 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1865 return (struct rx_call *)0;
1868 } while (!(call = sq->newcall)
1869 && !(socketp && *socketp != OSI_NULLSOCKET));
1871 MUTEX_EXIT(&sq->lock);
1873 MUTEX_ENTER(&freeSQEList_lock);
1874 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1875 rx_FreeSQEList = sq;
1876 MUTEX_EXIT(&freeSQEList_lock);
1879 clock_GetTime(&call->startTime);
1880 call->state = RX_STATE_ACTIVE;
1881 call->mode = RX_MODE_RECEIVING;
1882 #ifdef RX_KERNEL_TRACE
1883 if (ICL_SETACTIVE(afs_iclSetp)) {
1884 int glockOwner = ISAFS_GLOCK();
1887 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1888 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1895 rxi_calltrace(RX_CALL_START, call);
1896 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1897 call->conn->service->servicePort, call->conn->service->serviceId,
1900 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1907 #endif /* RX_ENABLE_LOCKS */
1911 /* Establish a procedure to be called when a packet arrives for a
1912 * call. This routine will be called at most once after each call,
1913 * and will also be called if there is an error condition on the or
1914 * the call is complete. Used by multi rx to build a selection
1915 * function which determines which of several calls is likely to be a
1916 * good one to read from.
1917 * NOTE: the way this is currently implemented it is probably only a
1918 * good idea to (1) use it immediately after a newcall (clients only)
1919 * and (2) only use it once. Other uses currently void your warranty
1922 rx_SetArrivalProc(struct rx_call *call,
1923 void (*proc) (struct rx_call * call,
1926 void * handle, int arg)
1928 call->arrivalProc = proc;
1929 call->arrivalProcHandle = handle;
1930 call->arrivalProcArg = arg;
1933 /* Call is finished (possibly prematurely). Return rc to the peer, if
1934 * appropriate, and return the final error code from the conversation
1938 rx_EndCall(struct rx_call *call, afs_int32 rc)
1940 struct rx_connection *conn = call->conn;
1941 struct rx_service *service;
1947 dpf(("rx_EndCall(call %x rc %d error %d abortCode %d)\n", call, rc, call->error, call->abortCode));
1950 MUTEX_ENTER(&call->lock);
1952 if (rc == 0 && call->error == 0) {
1953 call->abortCode = 0;
1954 call->abortCount = 0;
1957 call->arrivalProc = (void (*)())0;
1958 if (rc && call->error == 0) {
1959 rxi_CallError(call, rc);
1960 /* Send an abort message to the peer if this error code has
1961 * only just been set. If it was set previously, assume the
1962 * peer has already been sent the error code or will request it
1964 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1966 if (conn->type == RX_SERVER_CONNECTION) {
1967 /* Make sure reply or at least dummy reply is sent */
1968 if (call->mode == RX_MODE_RECEIVING) {
1969 rxi_WriteProc(call, 0, 0);
1971 if (call->mode == RX_MODE_SENDING) {
1972 rxi_FlushWrite(call);
1974 service = conn->service;
1975 rxi_calltrace(RX_CALL_END, call);
1976 /* Call goes to hold state until reply packets are acknowledged */
1977 if (call->tfirst + call->nSoftAcked < call->tnext) {
1978 call->state = RX_STATE_HOLD;
1980 call->state = RX_STATE_DALLY;
1981 rxi_ClearTransmitQueue(call, 0);
1982 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
1983 rxevent_Cancel(call->keepAliveEvent, call,
1984 RX_CALL_REFCOUNT_ALIVE);
1986 } else { /* Client connection */
1988 /* Make sure server receives input packets, in the case where
1989 * no reply arguments are expected */
1990 if ((call->mode == RX_MODE_SENDING)
1991 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
1992 (void)rxi_ReadProc(call, &dummy, 1);
1995 /* If we had an outstanding delayed ack, be nice to the server
1996 * and force-send it now.
1998 if (call->delayedAckEvent) {
1999 rxevent_Cancel(call->delayedAckEvent, call,
2000 RX_CALL_REFCOUNT_DELAY);
2001 call->delayedAckEvent = NULL;
2002 rxi_SendDelayedAck(NULL, call, NULL);
2005 /* We need to release the call lock since it's lower than the
2006 * conn_call_lock and we don't want to hold the conn_call_lock
2007 * over the rx_ReadProc call. The conn_call_lock needs to be held
2008 * here for the case where rx_NewCall is perusing the calls on
2009 * the connection structure. We don't want to signal until
2010 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2011 * have checked this call, found it active and by the time it
2012 * goes to sleep, will have missed the signal.
2014 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2015 * there are threads waiting to use the conn object.
2017 MUTEX_EXIT(&call->lock);
2018 MUTEX_ENTER(&conn->conn_call_lock);
2019 MUTEX_ENTER(&call->lock);
2020 MUTEX_ENTER(&conn->conn_data_lock);
2021 conn->flags |= RX_CONN_BUSY;
2022 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2023 if (conn->makeCallWaiters == 0)
2024 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2025 MUTEX_EXIT(&conn->conn_data_lock);
2026 #ifdef RX_ENABLE_LOCKS
2027 CV_BROADCAST(&conn->conn_call_cv);
2032 #ifdef RX_ENABLE_LOCKS
2034 MUTEX_EXIT(&conn->conn_data_lock);
2036 #endif /* RX_ENABLE_LOCKS */
2037 call->state = RX_STATE_DALLY;
2039 error = call->error;
2041 /* currentPacket, nLeft, and NFree must be zeroed here, because
2042 * ResetCall cannot: ResetCall may be called at splnet(), in the
2043 * kernel version, and may interrupt the macros rx_Read or
2044 * rx_Write, which run at normal priority for efficiency. */
2045 if (call->currentPacket) {
2046 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2047 rxi_FreePacket(call->currentPacket);
2048 call->currentPacket = (struct rx_packet *)0;
2051 call->nLeft = call->nFree = call->curlen = 0;
2053 /* Free any packets from the last call to ReadvProc/WritevProc */
2054 #ifdef RXDEBUG_PACKET
2056 #endif /* RXDEBUG_PACKET */
2057 rxi_FreePackets(0, &call->iovq);
2059 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2060 MUTEX_EXIT(&call->lock);
2061 if (conn->type == RX_CLIENT_CONNECTION) {
2062 MUTEX_EXIT(&conn->conn_call_lock);
2063 conn->flags &= ~RX_CONN_BUSY;
2067 * Map errors to the local host's errno.h format.
2069 error = ntoh_syserr_conv(error);
2073 #if !defined(KERNEL)
2075 /* Call this routine when shutting down a server or client (especially
2076 * clients). This will allow Rx to gracefully garbage collect server
2077 * connections, and reduce the number of retries that a server might
2078 * make to a dead client.
2079 * This is not quite right, since some calls may still be ongoing and
2080 * we can't lock them to destroy them. */
2084 struct rx_connection **conn_ptr, **conn_end;
2088 if (rxinit_status == 1) {
2090 return; /* Already shutdown. */
2092 rxi_DeleteCachedConnections();
2093 if (rx_connHashTable) {
2094 MUTEX_ENTER(&rx_connHashTable_lock);
2095 for (conn_ptr = &rx_connHashTable[0], conn_end =
2096 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2098 struct rx_connection *conn, *next;
2099 for (conn = *conn_ptr; conn; conn = next) {
2101 if (conn->type == RX_CLIENT_CONNECTION) {
2102 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2104 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2105 #ifdef RX_ENABLE_LOCKS
2106 rxi_DestroyConnectionNoLock(conn);
2107 #else /* RX_ENABLE_LOCKS */
2108 rxi_DestroyConnection(conn);
2109 #endif /* RX_ENABLE_LOCKS */
2113 #ifdef RX_ENABLE_LOCKS
2114 while (rx_connCleanup_list) {
2115 struct rx_connection *conn;
2116 conn = rx_connCleanup_list;
2117 rx_connCleanup_list = rx_connCleanup_list->next;
2118 MUTEX_EXIT(&rx_connHashTable_lock);
2119 rxi_CleanupConnection(conn);
2120 MUTEX_ENTER(&rx_connHashTable_lock);
2122 MUTEX_EXIT(&rx_connHashTable_lock);
2123 #endif /* RX_ENABLE_LOCKS */
2128 afs_winsockCleanup();
2136 /* if we wakeup packet waiter too often, can get in loop with two
2137 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2139 rxi_PacketsUnWait(void)
2141 if (!rx_waitingForPackets) {
2145 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2146 return; /* still over quota */
2149 rx_waitingForPackets = 0;
2150 #ifdef RX_ENABLE_LOCKS
2151 CV_BROADCAST(&rx_waitingForPackets_cv);
2153 osi_rxWakeup(&rx_waitingForPackets);
2159 /* ------------------Internal interfaces------------------------- */
2161 /* Return this process's service structure for the
2162 * specified socket and service */
2164 rxi_FindService(osi_socket socket, u_short serviceId)
2166 struct rx_service **sp;
2167 for (sp = &rx_services[0]; *sp; sp++) {
2168 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2175 #ifdef KDUMP_RX_LOCK
2176 static struct rx_call_rx_lock *rx_allCallsp = 0;
2178 static struct rx_call *rx_allCallsp = 0;
2182 /* Allocate a call structure, for the indicated channel of the
2183 * supplied connection. The mode and state of the call must be set by
2184 * the caller. Returns the call with mutex locked. */
2186 rxi_NewCall(struct rx_connection *conn, int channel)
2188 struct rx_call *call;
2189 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2190 struct rx_call *cp; /* Call pointer temp */
2191 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2192 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2194 dpf(("rxi_NewCall(conn %x, channel %d)\n", conn, channel));
2196 /* Grab an existing call structure, or allocate a new one.
2197 * Existing call structures are assumed to have been left reset by
2199 MUTEX_ENTER(&rx_freeCallQueue_lock);
2201 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2203 * EXCEPT that the TQ might not yet be cleared out.
2204 * Skip over those with in-use TQs.
2207 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2208 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2214 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2215 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2216 call = queue_First(&rx_freeCallQueue, rx_call);
2217 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2219 if (rx_stats_active)
2220 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2221 MUTEX_EXIT(&rx_freeCallQueue_lock);
2222 MUTEX_ENTER(&call->lock);
2223 CLEAR_CALL_QUEUE_LOCK(call);
2224 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2225 /* Now, if TQ wasn't cleared earlier, do it now. */
2226 if (call->flags & RX_CALL_TQ_CLEARME) {
2227 rxi_ClearTransmitQueue(call, 1);
2228 /*queue_Init(&call->tq);*/
2230 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2231 /* Bind the call to its connection structure */
2233 rxi_ResetCall(call, 1);
2236 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2237 #ifdef RXDEBUG_PACKET
2238 call->allNextp = rx_allCallsp;
2239 rx_allCallsp = call;
2241 #endif /* RXDEBUG_PACKET */
2242 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2244 MUTEX_EXIT(&rx_freeCallQueue_lock);
2245 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2246 MUTEX_ENTER(&call->lock);
2247 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2248 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2249 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2251 /* Initialize once-only items */
2252 queue_Init(&call->tq);
2253 queue_Init(&call->rq);
2254 queue_Init(&call->iovq);
2255 #ifdef RXDEBUG_PACKET
2256 call->rqc = call->tqc = call->iovqc = 0;
2257 #endif /* RXDEBUG_PACKET */
2258 /* Bind the call to its connection structure (prereq for reset) */
2260 rxi_ResetCall(call, 1);
2262 call->channel = channel;
2263 call->callNumber = &conn->callNumber[channel];
2264 call->rwind = conn->rwind[channel];
2265 call->twind = conn->twind[channel];
2266 /* Note that the next expected call number is retained (in
2267 * conn->callNumber[i]), even if we reallocate the call structure
2269 conn->call[channel] = call;
2270 /* if the channel's never been used (== 0), we should start at 1, otherwise
2271 * the call number is valid from the last time this channel was used */
2272 if (*call->callNumber == 0)
2273 *call->callNumber = 1;
2278 /* A call has been inactive long enough that so we can throw away
2279 * state, including the call structure, which is placed on the call
2281 * Call is locked upon entry.
2282 * haveCTLock set if called from rxi_ReapConnections
2284 #ifdef RX_ENABLE_LOCKS
2286 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2287 #else /* RX_ENABLE_LOCKS */
2289 rxi_FreeCall(struct rx_call *call)
2290 #endif /* RX_ENABLE_LOCKS */
2292 int channel = call->channel;
2293 struct rx_connection *conn = call->conn;
2296 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2297 (*call->callNumber)++;
2298 rxi_ResetCall(call, 0);
2299 call->conn->call[channel] = (struct rx_call *)0;
2301 MUTEX_ENTER(&rx_freeCallQueue_lock);
2302 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2303 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2304 /* A call may be free even though its transmit queue is still in use.
2305 * Since we search the call list from head to tail, put busy calls at
2306 * the head of the list, and idle calls at the tail.
2308 if (call->flags & RX_CALL_TQ_BUSY)
2309 queue_Prepend(&rx_freeCallQueue, call);
2311 queue_Append(&rx_freeCallQueue, call);
2312 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2313 queue_Append(&rx_freeCallQueue, call);
2314 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2315 if (rx_stats_active)
2316 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2317 MUTEX_EXIT(&rx_freeCallQueue_lock);
2319 /* Destroy the connection if it was previously slated for
2320 * destruction, i.e. the Rx client code previously called
2321 * rx_DestroyConnection (client connections), or
2322 * rxi_ReapConnections called the same routine (server
2323 * connections). Only do this, however, if there are no
2324 * outstanding calls. Note that for fine grain locking, there appears
2325 * to be a deadlock in that rxi_FreeCall has a call locked and
2326 * DestroyConnectionNoLock locks each call in the conn. But note a
2327 * few lines up where we have removed this call from the conn.
2328 * If someone else destroys a connection, they either have no
2329 * call lock held or are going through this section of code.
2331 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2332 MUTEX_ENTER(&conn->conn_data_lock);
2334 MUTEX_EXIT(&conn->conn_data_lock);
2335 #ifdef RX_ENABLE_LOCKS
2337 rxi_DestroyConnectionNoLock(conn);
2339 rxi_DestroyConnection(conn);
2340 #else /* RX_ENABLE_LOCKS */
2341 rxi_DestroyConnection(conn);
2342 #endif /* RX_ENABLE_LOCKS */
2346 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2348 rxi_Alloc(size_t size)
2352 if (rx_stats_active)
2353 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2356 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2357 afs_osi_Alloc_NoSleep(size);
2362 osi_Panic("rxi_Alloc error");
2368 rxi_Free(void *addr, size_t size)
2370 if (rx_stats_active)
2371 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2372 osi_Free(addr, size);
2376 rxi_SetPeerMtu(afs_uint32 host, afs_uint32 port, int mtu)
2378 struct rx_peer **peer_ptr, **peer_end;
2381 MUTEX_ENTER(&rx_peerHashTable_lock);
2383 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2384 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2386 struct rx_peer *peer, *next;
2387 for (peer = *peer_ptr; peer; peer = next) {
2389 if (host == peer->host) {
2390 MUTEX_ENTER(&peer->peer_lock);
2391 peer->ifMTU=MIN(mtu, peer->ifMTU);
2392 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2393 MUTEX_EXIT(&peer->peer_lock);
2398 struct rx_peer *peer;
2399 hashIndex = PEER_HASH(host, port);
2400 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2401 if ((peer->host == host) && (peer->port == port)) {
2402 MUTEX_ENTER(&peer->peer_lock);
2403 peer->ifMTU=MIN(mtu, peer->ifMTU);
2404 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2405 MUTEX_EXIT(&peer->peer_lock);
2409 MUTEX_EXIT(&rx_peerHashTable_lock);
2412 /* Find the peer process represented by the supplied (host,port)
2413 * combination. If there is no appropriate active peer structure, a
2414 * new one will be allocated and initialized
2415 * The origPeer, if set, is a pointer to a peer structure on which the
2416 * refcount will be be decremented. This is used to replace the peer
2417 * structure hanging off a connection structure */
2419 rxi_FindPeer(afs_uint32 host, u_short port,
2420 struct rx_peer *origPeer, int create)
2424 hashIndex = PEER_HASH(host, port);
2425 MUTEX_ENTER(&rx_peerHashTable_lock);
2426 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2427 if ((pp->host == host) && (pp->port == port))
2432 pp = rxi_AllocPeer(); /* This bzero's *pp */
2433 pp->host = host; /* set here or in InitPeerParams is zero */
2435 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2436 queue_Init(&pp->congestionQueue);
2437 queue_Init(&pp->rpcStats);
2438 pp->next = rx_peerHashTable[hashIndex];
2439 rx_peerHashTable[hashIndex] = pp;
2440 rxi_InitPeerParams(pp);
2441 if (rx_stats_active)
2442 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2449 origPeer->refCount--;
2450 MUTEX_EXIT(&rx_peerHashTable_lock);
2455 /* Find the connection at (host, port) started at epoch, and with the
2456 * given connection id. Creates the server connection if necessary.
2457 * The type specifies whether a client connection or a server
2458 * connection is desired. In both cases, (host, port) specify the
2459 * peer's (host, pair) pair. Client connections are not made
2460 * automatically by this routine. The parameter socket gives the
2461 * socket descriptor on which the packet was received. This is used,
2462 * in the case of server connections, to check that *new* connections
2463 * come via a valid (port, serviceId). Finally, the securityIndex
2464 * parameter must match the existing index for the connection. If a
2465 * server connection is created, it will be created using the supplied
2466 * index, if the index is valid for this service */
2467 struct rx_connection *
2468 rxi_FindConnection(osi_socket socket, afs_int32 host,
2469 u_short port, u_short serviceId, afs_uint32 cid,
2470 afs_uint32 epoch, int type, u_int securityIndex)
2472 int hashindex, flag, i;
2473 struct rx_connection *conn;
2474 hashindex = CONN_HASH(host, port, cid, epoch, type);
2475 MUTEX_ENTER(&rx_connHashTable_lock);
2476 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2477 rx_connHashTable[hashindex],
2480 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2481 && (epoch == conn->epoch)) {
2482 struct rx_peer *pp = conn->peer;
2483 if (securityIndex != conn->securityIndex) {
2484 /* this isn't supposed to happen, but someone could forge a packet
2485 * like this, and there seems to be some CM bug that makes this
2486 * happen from time to time -- in which case, the fileserver
2488 MUTEX_EXIT(&rx_connHashTable_lock);
2489 return (struct rx_connection *)0;
2491 if (pp->host == host && pp->port == port)
2493 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2495 /* So what happens when it's a callback connection? */
2496 if ( /*type == RX_CLIENT_CONNECTION && */
2497 (conn->epoch & 0x80000000))
2501 /* the connection rxLastConn that was used the last time is not the
2502 ** one we are looking for now. Hence, start searching in the hash */
2504 conn = rx_connHashTable[hashindex];
2509 struct rx_service *service;
2510 if (type == RX_CLIENT_CONNECTION) {
2511 MUTEX_EXIT(&rx_connHashTable_lock);
2512 return (struct rx_connection *)0;
2514 service = rxi_FindService(socket, serviceId);
2515 if (!service || (securityIndex >= service->nSecurityObjects)
2516 || (service->securityObjects[securityIndex] == 0)) {
2517 MUTEX_EXIT(&rx_connHashTable_lock);
2518 return (struct rx_connection *)0;
2520 conn = rxi_AllocConnection(); /* This bzero's the connection */
2521 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2522 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2523 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2524 conn->next = rx_connHashTable[hashindex];
2525 rx_connHashTable[hashindex] = conn;
2526 conn->peer = rxi_FindPeer(host, port, 0, 1);
2527 conn->type = RX_SERVER_CONNECTION;
2528 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2529 conn->epoch = epoch;
2530 conn->cid = cid & RX_CIDMASK;
2531 /* conn->serial = conn->lastSerial = 0; */
2532 /* conn->timeout = 0; */
2533 conn->ackRate = RX_FAST_ACK_RATE;
2534 conn->service = service;
2535 conn->serviceId = serviceId;
2536 conn->securityIndex = securityIndex;
2537 conn->securityObject = service->securityObjects[securityIndex];
2538 conn->nSpecific = 0;
2539 conn->specific = NULL;
2540 rx_SetConnDeadTime(conn, service->connDeadTime);
2541 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2542 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2543 for (i = 0; i < RX_MAXCALLS; i++) {
2544 conn->twind[i] = rx_initSendWindow;
2545 conn->rwind[i] = rx_initReceiveWindow;
2547 /* Notify security object of the new connection */
2548 RXS_NewConnection(conn->securityObject, conn);
2549 /* XXXX Connection timeout? */
2550 if (service->newConnProc)
2551 (*service->newConnProc) (conn);
2552 if (rx_stats_active)
2553 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2556 MUTEX_ENTER(&conn->conn_data_lock);
2558 MUTEX_EXIT(&conn->conn_data_lock);
2560 rxLastConn = conn; /* store this connection as the last conn used */
2561 MUTEX_EXIT(&rx_connHashTable_lock);
2565 /* There are two packet tracing routines available for testing and monitoring
2566 * Rx. One is called just after every packet is received and the other is
2567 * called just before every packet is sent. Received packets, have had their
2568 * headers decoded, and packets to be sent have not yet had their headers
2569 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2570 * containing the network address. Both can be modified. The return value, if
2571 * non-zero, indicates that the packet should be dropped. */
2573 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2574 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2576 /* A packet has been received off the interface. Np is the packet, socket is
2577 * the socket number it was received from (useful in determining which service
2578 * this packet corresponds to), and (host, port) reflect the host,port of the
2579 * sender. This call returns the packet to the caller if it is finished with
2580 * it, rather than de-allocating it, just as a small performance hack */
2583 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2584 afs_uint32 host, u_short port, int *tnop,
2585 struct rx_call **newcallp)
2587 struct rx_call *call;
2588 struct rx_connection *conn;
2590 afs_uint32 currentCallNumber;
2596 struct rx_packet *tnp;
2599 /* We don't print out the packet until now because (1) the time may not be
2600 * accurate enough until now in the lwp implementation (rx_Listener only gets
2601 * the time after the packet is read) and (2) from a protocol point of view,
2602 * this is the first time the packet has been seen */
2603 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2604 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2605 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2606 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2607 np->header.epoch, np->header.cid, np->header.callNumber,
2608 np->header.seq, np->header.flags, np));
2611 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2612 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2615 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2616 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2619 /* If an input tracer function is defined, call it with the packet and
2620 * network address. Note this function may modify its arguments. */
2621 if (rx_justReceived) {
2622 struct sockaddr_in addr;
2624 addr.sin_family = AF_INET;
2625 addr.sin_port = port;
2626 addr.sin_addr.s_addr = host;
2627 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2628 addr.sin_len = sizeof(addr);
2629 #endif /* AFS_OSF_ENV */
2630 drop = (*rx_justReceived) (np, &addr);
2631 /* drop packet if return value is non-zero */
2634 port = addr.sin_port; /* in case fcn changed addr */
2635 host = addr.sin_addr.s_addr;
2639 /* If packet was not sent by the client, then *we* must be the client */
2640 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2641 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2643 /* Find the connection (or fabricate one, if we're the server & if
2644 * necessary) associated with this packet */
2646 rxi_FindConnection(socket, host, port, np->header.serviceId,
2647 np->header.cid, np->header.epoch, type,
2648 np->header.securityIndex);
2651 /* If no connection found or fabricated, just ignore the packet.
2652 * (An argument could be made for sending an abort packet for
2657 MUTEX_ENTER(&conn->conn_data_lock);
2658 if (conn->maxSerial < np->header.serial)
2659 conn->maxSerial = np->header.serial;
2660 MUTEX_EXIT(&conn->conn_data_lock);
2662 /* If the connection is in an error state, send an abort packet and ignore
2663 * the incoming packet */
2665 /* Don't respond to an abort packet--we don't want loops! */
2666 MUTEX_ENTER(&conn->conn_data_lock);
2667 if (np->header.type != RX_PACKET_TYPE_ABORT)
2668 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2670 MUTEX_EXIT(&conn->conn_data_lock);
2674 /* Check for connection-only requests (i.e. not call specific). */
2675 if (np->header.callNumber == 0) {
2676 switch (np->header.type) {
2677 case RX_PACKET_TYPE_ABORT: {
2678 /* What if the supplied error is zero? */
2679 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2680 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2681 rxi_ConnectionError(conn, errcode);
2682 MUTEX_ENTER(&conn->conn_data_lock);
2684 MUTEX_EXIT(&conn->conn_data_lock);
2687 case RX_PACKET_TYPE_CHALLENGE:
2688 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2689 MUTEX_ENTER(&conn->conn_data_lock);
2691 MUTEX_EXIT(&conn->conn_data_lock);
2693 case RX_PACKET_TYPE_RESPONSE:
2694 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2695 MUTEX_ENTER(&conn->conn_data_lock);
2697 MUTEX_EXIT(&conn->conn_data_lock);
2699 case RX_PACKET_TYPE_PARAMS:
2700 case RX_PACKET_TYPE_PARAMS + 1:
2701 case RX_PACKET_TYPE_PARAMS + 2:
2702 /* ignore these packet types for now */
2703 MUTEX_ENTER(&conn->conn_data_lock);
2705 MUTEX_EXIT(&conn->conn_data_lock);
2710 /* Should not reach here, unless the peer is broken: send an
2712 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2713 MUTEX_ENTER(&conn->conn_data_lock);
2714 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2716 MUTEX_EXIT(&conn->conn_data_lock);
2721 channel = np->header.cid & RX_CHANNELMASK;
2722 call = conn->call[channel];
2723 #ifdef RX_ENABLE_LOCKS
2725 MUTEX_ENTER(&call->lock);
2726 /* Test to see if call struct is still attached to conn. */
2727 if (call != conn->call[channel]) {
2729 MUTEX_EXIT(&call->lock);
2730 if (type == RX_SERVER_CONNECTION) {
2731 call = conn->call[channel];
2732 /* If we started with no call attached and there is one now,
2733 * another thread is also running this routine and has gotten
2734 * the connection channel. We should drop this packet in the tests
2735 * below. If there was a call on this connection and it's now
2736 * gone, then we'll be making a new call below.
2737 * If there was previously a call and it's now different then
2738 * the old call was freed and another thread running this routine
2739 * has created a call on this channel. One of these two threads
2740 * has a packet for the old call and the code below handles those
2744 MUTEX_ENTER(&call->lock);
2746 /* This packet can't be for this call. If the new call address is
2747 * 0 then no call is running on this channel. If there is a call
2748 * then, since this is a client connection we're getting data for
2749 * it must be for the previous call.
2751 if (rx_stats_active)
2752 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2753 MUTEX_ENTER(&conn->conn_data_lock);
2755 MUTEX_EXIT(&conn->conn_data_lock);
2760 currentCallNumber = conn->callNumber[channel];
2762 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2763 if (np->header.callNumber < currentCallNumber) {
2764 if (rx_stats_active)
2765 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2766 #ifdef RX_ENABLE_LOCKS
2768 MUTEX_EXIT(&call->lock);
2770 MUTEX_ENTER(&conn->conn_data_lock);
2772 MUTEX_EXIT(&conn->conn_data_lock);
2776 MUTEX_ENTER(&conn->conn_call_lock);
2777 call = rxi_NewCall(conn, channel);
2778 MUTEX_EXIT(&conn->conn_call_lock);
2779 *call->callNumber = np->header.callNumber;
2781 if (np->header.callNumber == 0)
2782 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %lx resend %d.%0.3d len %d", np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port), np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq, np->header.flags, (unsigned long)np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2784 call->state = RX_STATE_PRECALL;
2785 clock_GetTime(&call->queueTime);
2786 hzero(call->bytesSent);
2787 hzero(call->bytesRcvd);
2789 * If the number of queued calls exceeds the overload
2790 * threshold then abort this call.
2792 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2793 struct rx_packet *tp;
2795 rxi_CallError(call, rx_BusyError);
2796 tp = rxi_SendCallAbort(call, np, 1, 0);
2797 MUTEX_EXIT(&call->lock);
2798 MUTEX_ENTER(&conn->conn_data_lock);
2800 MUTEX_EXIT(&conn->conn_data_lock);
2801 if (rx_stats_active)
2802 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2805 rxi_KeepAliveOn(call);
2806 } else if (np->header.callNumber != currentCallNumber) {
2807 /* Wait until the transmit queue is idle before deciding
2808 * whether to reset the current call. Chances are that the
2809 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2812 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2813 while ((call->state == RX_STATE_ACTIVE)
2814 && (call->flags & RX_CALL_TQ_BUSY)) {
2815 call->flags |= RX_CALL_TQ_WAIT;
2817 #ifdef RX_ENABLE_LOCKS
2818 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2819 CV_WAIT(&call->cv_tq, &call->lock);
2820 #else /* RX_ENABLE_LOCKS */
2821 osi_rxSleep(&call->tq);
2822 #endif /* RX_ENABLE_LOCKS */
2824 if (call->tqWaiters == 0)
2825 call->flags &= ~RX_CALL_TQ_WAIT;
2827 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2828 /* If the new call cannot be taken right now send a busy and set
2829 * the error condition in this call, so that it terminates as
2830 * quickly as possible */
2831 if (call->state == RX_STATE_ACTIVE) {
2832 struct rx_packet *tp;
2834 rxi_CallError(call, RX_CALL_DEAD);
2835 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2837 MUTEX_EXIT(&call->lock);
2838 MUTEX_ENTER(&conn->conn_data_lock);
2840 MUTEX_EXIT(&conn->conn_data_lock);
2843 rxi_ResetCall(call, 0);
2844 *call->callNumber = np->header.callNumber;
2846 if (np->header.callNumber == 0)
2847 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %lx resend %d.%0.3d len %d", np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port), np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq, np->header.flags, (unsigned long)np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2849 call->state = RX_STATE_PRECALL;
2850 clock_GetTime(&call->queueTime);
2851 hzero(call->bytesSent);
2852 hzero(call->bytesRcvd);
2854 * If the number of queued calls exceeds the overload
2855 * threshold then abort this call.
2857 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2858 struct rx_packet *tp;
2860 rxi_CallError(call, rx_BusyError);
2861 tp = rxi_SendCallAbort(call, np, 1, 0);
2862 MUTEX_EXIT(&call->lock);
2863 MUTEX_ENTER(&conn->conn_data_lock);
2865 MUTEX_EXIT(&conn->conn_data_lock);
2866 if (rx_stats_active)
2867 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2870 rxi_KeepAliveOn(call);
2872 /* Continuing call; do nothing here. */
2874 } else { /* we're the client */
2875 /* Ignore all incoming acknowledgements for calls in DALLY state */
2876 if (call && (call->state == RX_STATE_DALLY)
2877 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2878 if (rx_stats_active)
2879 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2880 #ifdef RX_ENABLE_LOCKS
2882 MUTEX_EXIT(&call->lock);
2885 MUTEX_ENTER(&conn->conn_data_lock);
2887 MUTEX_EXIT(&conn->conn_data_lock);
2891 /* Ignore anything that's not relevant to the current call. If there
2892 * isn't a current call, then no packet is relevant. */
2893 if (!call || (np->header.callNumber != currentCallNumber)) {
2894 if (rx_stats_active)
2895 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2896 #ifdef RX_ENABLE_LOCKS
2898 MUTEX_EXIT(&call->lock);
2901 MUTEX_ENTER(&conn->conn_data_lock);
2903 MUTEX_EXIT(&conn->conn_data_lock);
2906 /* If the service security object index stamped in the packet does not
2907 * match the connection's security index, ignore the packet */
2908 if (np->header.securityIndex != conn->securityIndex) {
2909 #ifdef RX_ENABLE_LOCKS
2910 MUTEX_EXIT(&call->lock);
2912 MUTEX_ENTER(&conn->conn_data_lock);
2914 MUTEX_EXIT(&conn->conn_data_lock);
2918 /* If we're receiving the response, then all transmit packets are
2919 * implicitly acknowledged. Get rid of them. */
2920 if (np->header.type == RX_PACKET_TYPE_DATA) {
2921 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2922 /* XXX Hack. Because we must release the global rx lock when
2923 * sending packets (osi_NetSend) we drop all acks while we're
2924 * traversing the tq in rxi_Start sending packets out because
2925 * packets may move to the freePacketQueue as result of being here!
2926 * So we drop these packets until we're safely out of the
2927 * traversing. Really ugly!
2928 * For fine grain RX locking, we set the acked field in the
2929 * packets and let rxi_Start remove them from the transmit queue.
2931 if (call->flags & RX_CALL_TQ_BUSY) {
2932 #ifdef RX_ENABLE_LOCKS
2933 rxi_SetAcksInTransmitQueue(call);
2936 return np; /* xmitting; drop packet */
2939 rxi_ClearTransmitQueue(call, 0);
2941 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2942 rxi_ClearTransmitQueue(call, 0);
2943 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2945 if (np->header.type == RX_PACKET_TYPE_ACK) {
2946 /* now check to see if this is an ack packet acknowledging that the
2947 * server actually *lost* some hard-acked data. If this happens we
2948 * ignore this packet, as it may indicate that the server restarted in
2949 * the middle of a call. It is also possible that this is an old ack
2950 * packet. We don't abort the connection in this case, because this
2951 * *might* just be an old ack packet. The right way to detect a server
2952 * restart in the midst of a call is to notice that the server epoch
2954 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2955 * XXX unacknowledged. I think that this is off-by-one, but
2956 * XXX I don't dare change it just yet, since it will
2957 * XXX interact badly with the server-restart detection
2958 * XXX code in receiveackpacket. */
2959 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2960 if (rx_stats_active)
2961 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2962 MUTEX_EXIT(&call->lock);
2963 MUTEX_ENTER(&conn->conn_data_lock);
2965 MUTEX_EXIT(&conn->conn_data_lock);
2969 } /* else not a data packet */
2972 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
2973 /* Set remote user defined status from packet */
2974 call->remoteStatus = np->header.userStatus;
2976 /* Note the gap between the expected next packet and the actual
2977 * packet that arrived, when the new packet has a smaller serial number
2978 * than expected. Rioses frequently reorder packets all by themselves,
2979 * so this will be quite important with very large window sizes.
2980 * Skew is checked against 0 here to avoid any dependence on the type of
2981 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
2983 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
2984 * see CalculateRoundTripTime for an example of how to keep smoothed values.
2985 * I think using a beta of 1/8 is probably appropriate. 93.04.21
2987 MUTEX_ENTER(&conn->conn_data_lock);
2988 skew = conn->lastSerial - np->header.serial;
2989 conn->lastSerial = np->header.serial;
2990 MUTEX_EXIT(&conn->conn_data_lock);
2992 struct rx_peer *peer;
2994 if (skew > peer->inPacketSkew) {
2995 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
2997 peer->inPacketSkew = skew;
3001 /* Now do packet type-specific processing */
3002 switch (np->header.type) {
3003 case RX_PACKET_TYPE_DATA:
3004 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3007 case RX_PACKET_TYPE_ACK:
3008 /* Respond immediately to ack packets requesting acknowledgement
3010 if (np->header.flags & RX_REQUEST_ACK) {
3012 (void)rxi_SendCallAbort(call, 0, 1, 0);
3014 (void)rxi_SendAck(call, 0, np->header.serial,
3015 RX_ACK_PING_RESPONSE, 1);
3017 np = rxi_ReceiveAckPacket(call, np, 1);
3019 case RX_PACKET_TYPE_ABORT: {
3020 /* An abort packet: reset the call, passing the error up to the user. */
3021 /* What if error is zero? */
3022 /* What if the error is -1? the application will treat it as a timeout. */
3023 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3024 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3025 rxi_CallError(call, errdata);
3026 MUTEX_EXIT(&call->lock);
3027 MUTEX_ENTER(&conn->conn_data_lock);
3029 MUTEX_EXIT(&conn->conn_data_lock);
3030 return np; /* xmitting; drop packet */
3032 case RX_PACKET_TYPE_BUSY:
3035 case RX_PACKET_TYPE_ACKALL:
3036 /* All packets acknowledged, so we can drop all packets previously
3037 * readied for sending */
3038 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3039 /* XXX Hack. We because we can't release the global rx lock when
3040 * sending packets (osi_NetSend) we drop all ack pkts while we're
3041 * traversing the tq in rxi_Start sending packets out because
3042 * packets may move to the freePacketQueue as result of being
3043 * here! So we drop these packets until we're safely out of the
3044 * traversing. Really ugly!
3045 * For fine grain RX locking, we set the acked field in the packets
3046 * and let rxi_Start remove the packets from the transmit queue.
3048 if (call->flags & RX_CALL_TQ_BUSY) {
3049 #ifdef RX_ENABLE_LOCKS
3050 rxi_SetAcksInTransmitQueue(call);
3052 #else /* RX_ENABLE_LOCKS */
3053 MUTEX_EXIT(&call->lock);
3054 MUTEX_ENTER(&conn->conn_data_lock);
3056 MUTEX_EXIT(&conn->conn_data_lock);
3057 return np; /* xmitting; drop packet */
3058 #endif /* RX_ENABLE_LOCKS */
3060 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3061 rxi_ClearTransmitQueue(call, 0);
3062 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3065 /* Should not reach here, unless the peer is broken: send an abort
3067 rxi_CallError(call, RX_PROTOCOL_ERROR);
3068 np = rxi_SendCallAbort(call, np, 1, 0);
3071 /* Note when this last legitimate packet was received, for keep-alive
3072 * processing. Note, we delay getting the time until now in the hope that
3073 * the packet will be delivered to the user before any get time is required
3074 * (if not, then the time won't actually be re-evaluated here). */
3075 call->lastReceiveTime = clock_Sec();
3076 MUTEX_EXIT(&call->lock);
3077 MUTEX_ENTER(&conn->conn_data_lock);
3079 MUTEX_EXIT(&conn->conn_data_lock);
3083 /* return true if this is an "interesting" connection from the point of view
3084 of someone trying to debug the system */
3086 rxi_IsConnInteresting(struct rx_connection *aconn)
3089 struct rx_call *tcall;
3091 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3093 for (i = 0; i < RX_MAXCALLS; i++) {
3094 tcall = aconn->call[i];
3096 if ((tcall->state == RX_STATE_PRECALL)
3097 || (tcall->state == RX_STATE_ACTIVE))
3099 if ((tcall->mode == RX_MODE_SENDING)
3100 || (tcall->mode == RX_MODE_RECEIVING))
3108 /* if this is one of the last few packets AND it wouldn't be used by the
3109 receiving call to immediately satisfy a read request, then drop it on
3110 the floor, since accepting it might prevent a lock-holding thread from
3111 making progress in its reading. If a call has been cleared while in
3112 the precall state then ignore all subsequent packets until the call
3113 is assigned to a thread. */
3116 TooLow(struct rx_packet *ap, struct rx_call *acall)
3120 MUTEX_ENTER(&rx_quota_mutex);
3121 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3122 && (acall->state == RX_STATE_PRECALL))
3123 || ((rx_nFreePackets < rxi_dataQuota + 2)
3124 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3125 && (acall->flags & RX_CALL_READER_WAIT)))) {
3128 MUTEX_EXIT(&rx_quota_mutex);
3134 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3136 struct rx_connection *conn = arg1;
3137 struct rx_call *acall = arg2;
3138 struct rx_call *call = acall;
3139 struct clock when, now;
3142 MUTEX_ENTER(&conn->conn_data_lock);
3143 conn->checkReachEvent = NULL;
3144 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3147 MUTEX_EXIT(&conn->conn_data_lock);
3151 MUTEX_ENTER(&conn->conn_call_lock);
3152 MUTEX_ENTER(&conn->conn_data_lock);
3153 for (i = 0; i < RX_MAXCALLS; i++) {
3154 struct rx_call *tc = conn->call[i];
3155 if (tc && tc->state == RX_STATE_PRECALL) {
3161 /* Indicate that rxi_CheckReachEvent is no longer running by
3162 * clearing the flag. Must be atomic under conn_data_lock to
3163 * avoid a new call slipping by: rxi_CheckConnReach holds
3164 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3166 conn->flags &= ~RX_CONN_ATTACHWAIT;
3167 MUTEX_EXIT(&conn->conn_data_lock);
3168 MUTEX_EXIT(&conn->conn_call_lock);
3173 MUTEX_ENTER(&call->lock);
3174 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3176 MUTEX_EXIT(&call->lock);
3178 clock_GetTime(&now);
3180 when.sec += RX_CHECKREACH_TIMEOUT;
3181 MUTEX_ENTER(&conn->conn_data_lock);
3182 if (!conn->checkReachEvent) {
3184 conn->checkReachEvent =
3185 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3188 MUTEX_EXIT(&conn->conn_data_lock);
3194 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3196 struct rx_service *service = conn->service;
3197 struct rx_peer *peer = conn->peer;
3198 afs_uint32 now, lastReach;
3200 if (service->checkReach == 0)
3204 MUTEX_ENTER(&peer->peer_lock);
3205 lastReach = peer->lastReachTime;
3206 MUTEX_EXIT(&peer->peer_lock);
3207 if (now - lastReach < RX_CHECKREACH_TTL)
3210 MUTEX_ENTER(&conn->conn_data_lock);
3211 if (conn->flags & RX_CONN_ATTACHWAIT) {
3212 MUTEX_EXIT(&conn->conn_data_lock);
3215 conn->flags |= RX_CONN_ATTACHWAIT;
3216 MUTEX_EXIT(&conn->conn_data_lock);
3217 if (!conn->checkReachEvent)
3218 rxi_CheckReachEvent(NULL, conn, call);
3223 /* try to attach call, if authentication is complete */
3225 TryAttach(struct rx_call *acall, osi_socket socket,
3226 int *tnop, struct rx_call **newcallp,
3229 struct rx_connection *conn = acall->conn;
3231 if (conn->type == RX_SERVER_CONNECTION
3232 && acall->state == RX_STATE_PRECALL) {
3233 /* Don't attach until we have any req'd. authentication. */
3234 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3235 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3236 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3237 /* Note: this does not necessarily succeed; there
3238 * may not any proc available
3241 rxi_ChallengeOn(acall->conn);
3246 /* A data packet has been received off the interface. This packet is
3247 * appropriate to the call (the call is in the right state, etc.). This
3248 * routine can return a packet to the caller, for re-use */
3251 rxi_ReceiveDataPacket(struct rx_call *call,
3252 struct rx_packet *np, int istack,
3253 osi_socket socket, afs_uint32 host, u_short port,
3254 int *tnop, struct rx_call **newcallp)
3256 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3260 afs_uint32 seq, serial, flags;
3262 struct rx_packet *tnp;
3263 struct clock when, now;
3264 if (rx_stats_active)
3265 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3268 /* If there are no packet buffers, drop this new packet, unless we can find
3269 * packet buffers from inactive calls */
3271 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3272 MUTEX_ENTER(&rx_freePktQ_lock);
3273 rxi_NeedMorePackets = TRUE;
3274 MUTEX_EXIT(&rx_freePktQ_lock);
3275 if (rx_stats_active)
3276 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3277 call->rprev = np->header.serial;
3278 rxi_calltrace(RX_TRACE_DROP, call);
3279 dpf(("packet %x dropped on receipt - quota problems", np));
3281 rxi_ClearReceiveQueue(call);
3282 clock_GetTime(&now);
3284 clock_Add(&when, &rx_softAckDelay);
3285 if (!call->delayedAckEvent
3286 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3287 rxevent_Cancel(call->delayedAckEvent, call,
3288 RX_CALL_REFCOUNT_DELAY);
3289 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3290 call->delayedAckEvent =
3291 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3293 /* we've damaged this call already, might as well do it in. */
3299 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3300 * packet is one of several packets transmitted as a single
3301 * datagram. Do not send any soft or hard acks until all packets
3302 * in a jumbogram have been processed. Send negative acks right away.
3304 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3305 /* tnp is non-null when there are more packets in the
3306 * current jumbo gram */
3313 seq = np->header.seq;
3314 serial = np->header.serial;
3315 flags = np->header.flags;
3317 /* If the call is in an error state, send an abort message */
3319 return rxi_SendCallAbort(call, np, istack, 0);
3321 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3322 * AFS 3.5 jumbogram. */
3323 if (flags & RX_JUMBO_PACKET) {
3324 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3329 if (np->header.spare != 0) {
3330 MUTEX_ENTER(&call->conn->conn_data_lock);
3331 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3332 MUTEX_EXIT(&call->conn->conn_data_lock);
3335 /* The usual case is that this is the expected next packet */
3336 if (seq == call->rnext) {
3338 /* Check to make sure it is not a duplicate of one already queued */
3339 if (queue_IsNotEmpty(&call->rq)
3340 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3341 if (rx_stats_active)
3342 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3343 dpf(("packet %x dropped on receipt - duplicate", np));
3344 rxevent_Cancel(call->delayedAckEvent, call,
3345 RX_CALL_REFCOUNT_DELAY);
3346 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3352 /* It's the next packet. Stick it on the receive queue
3353 * for this call. Set newPackets to make sure we wake
3354 * the reader once all packets have been processed */
3355 np->flags |= RX_PKTFLAG_RQ;
3356 queue_Prepend(&call->rq, np);
3357 #ifdef RXDEBUG_PACKET
3359 #endif /* RXDEBUG_PACKET */
3361 np = NULL; /* We can't use this anymore */
3364 /* If an ack is requested then set a flag to make sure we
3365 * send an acknowledgement for this packet */
3366 if (flags & RX_REQUEST_ACK) {
3367 ackNeeded = RX_ACK_REQUESTED;
3370 /* Keep track of whether we have received the last packet */
3371 if (flags & RX_LAST_PACKET) {
3372 call->flags |= RX_CALL_HAVE_LAST;
3376 /* Check whether we have all of the packets for this call */
3377 if (call->flags & RX_CALL_HAVE_LAST) {
3378 afs_uint32 tseq; /* temporary sequence number */
3379 struct rx_packet *tp; /* Temporary packet pointer */
3380 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3382 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3383 if (tseq != tp->header.seq)
3385 if (tp->header.flags & RX_LAST_PACKET) {
3386 call->flags |= RX_CALL_RECEIVE_DONE;
3393 /* Provide asynchronous notification for those who want it
3394 * (e.g. multi rx) */
3395 if (call->arrivalProc) {
3396 (*call->arrivalProc) (call, call->arrivalProcHandle,
3397 call->arrivalProcArg);
3398 call->arrivalProc = (void (*)())0;
3401 /* Update last packet received */
3404 /* If there is no server process serving this call, grab
3405 * one, if available. We only need to do this once. If a
3406 * server thread is available, this thread becomes a server
3407 * thread and the server thread becomes a listener thread. */
3409 TryAttach(call, socket, tnop, newcallp, 0);
3412 /* This is not the expected next packet. */
3414 /* Determine whether this is a new or old packet, and if it's
3415 * a new one, whether it fits into the current receive window.
3416 * Also figure out whether the packet was delivered in sequence.
3417 * We use the prev variable to determine whether the new packet
3418 * is the successor of its immediate predecessor in the
3419 * receive queue, and the missing flag to determine whether
3420 * any of this packets predecessors are missing. */
3422 afs_uint32 prev; /* "Previous packet" sequence number */
3423 struct rx_packet *tp; /* Temporary packet pointer */
3424 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3425 int missing; /* Are any predecessors missing? */
3427 /* If the new packet's sequence number has been sent to the
3428 * application already, then this is a duplicate */
3429 if (seq < call->rnext) {
3430 if (rx_stats_active)
3431 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3432 rxevent_Cancel(call->delayedAckEvent, call,
3433 RX_CALL_REFCOUNT_DELAY);
3434 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3440 /* If the sequence number is greater than what can be
3441 * accomodated by the current window, then send a negative
3442 * acknowledge and drop the packet */
3443 if ((call->rnext + call->rwind) <= seq) {
3444 rxevent_Cancel(call->delayedAckEvent, call,
3445 RX_CALL_REFCOUNT_DELAY);
3446 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3453 /* Look for the packet in the queue of old received packets */
3454 for (prev = call->rnext - 1, missing =
3455 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3456 /*Check for duplicate packet */
3457 if (seq == tp->header.seq) {
3458 if (rx_stats_active)
3459 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3460 rxevent_Cancel(call->delayedAckEvent, call,
3461 RX_CALL_REFCOUNT_DELAY);
3462 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3468 /* If we find a higher sequence packet, break out and
3469 * insert the new packet here. */
3470 if (seq < tp->header.seq)
3472 /* Check for missing packet */
3473 if (tp->header.seq != prev + 1) {
3477 prev = tp->header.seq;
3480 /* Keep track of whether we have received the last packet. */
3481 if (flags & RX_LAST_PACKET) {
3482 call->flags |= RX_CALL_HAVE_LAST;
3485 /* It's within the window: add it to the the receive queue.
3486 * tp is left by the previous loop either pointing at the
3487 * packet before which to insert the new packet, or at the
3488 * queue head if the queue is empty or the packet should be
3490 np->flags |= RX_PKTFLAG_RQ;
3491 #ifdef RXDEBUG_PACKET
3493 #endif /* RXDEBUG_PACKET */
3494 queue_InsertBefore(tp, np);
3498 /* Check whether we have all of the packets for this call */
3499 if ((call->flags & RX_CALL_HAVE_LAST)
3500 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3501 afs_uint32 tseq; /* temporary sequence number */
3504 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3505 if (tseq != tp->header.seq)
3507 if (tp->header.flags & RX_LAST_PACKET) {
3508 call->flags |= RX_CALL_RECEIVE_DONE;
3515 /* We need to send an ack of the packet is out of sequence,
3516 * or if an ack was requested by the peer. */
3517 if (seq != prev + 1 || missing) {
3518 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3519 } else if (flags & RX_REQUEST_ACK) {
3520 ackNeeded = RX_ACK_REQUESTED;
3523 /* Acknowledge the last packet for each call */
3524 if (flags & RX_LAST_PACKET) {
3535 * If the receiver is waiting for an iovec, fill the iovec
3536 * using the data from the receive queue */
3537 if (call->flags & RX_CALL_IOVEC_WAIT) {
3538 didHardAck = rxi_FillReadVec(call, serial);
3539 /* the call may have been aborted */
3548 /* Wakeup the reader if any */
3549 if ((call->flags & RX_CALL_READER_WAIT)
3550 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3551 || (call->iovNext >= call->iovMax)
3552 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3553 call->flags &= ~RX_CALL_READER_WAIT;
3554 #ifdef RX_ENABLE_LOCKS
3555 CV_BROADCAST(&call->cv_rq);
3557 osi_rxWakeup(&call->rq);
3563 * Send an ack when requested by the peer, or once every
3564 * rxi_SoftAckRate packets until the last packet has been
3565 * received. Always send a soft ack for the last packet in
3566 * the server's reply. */
3568 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3569 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3570 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3571 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3572 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3573 } else if (call->nSoftAcks) {
3574 clock_GetTime(&now);
3576 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3577 clock_Add(&when, &rx_lastAckDelay);
3579 clock_Add(&when, &rx_softAckDelay);
3581 if (!call->delayedAckEvent
3582 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3583 rxevent_Cancel(call->delayedAckEvent, call,
3584 RX_CALL_REFCOUNT_DELAY);
3585 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3586 call->delayedAckEvent =
3587 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3589 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3590 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3597 static void rxi_ComputeRate();
3601 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3603 struct rx_peer *peer = conn->peer;
3605 MUTEX_ENTER(&peer->peer_lock);
3606 peer->lastReachTime = clock_Sec();
3607 MUTEX_EXIT(&peer->peer_lock);
3609 MUTEX_ENTER(&conn->conn_data_lock);
3610 if (conn->flags & RX_CONN_ATTACHWAIT) {
3613 conn->flags &= ~RX_CONN_ATTACHWAIT;
3614 MUTEX_EXIT(&conn->conn_data_lock);
3616 for (i = 0; i < RX_MAXCALLS; i++) {
3617 struct rx_call *call = conn->call[i];
3620 MUTEX_ENTER(&call->lock);
3621 /* tnop can be null if newcallp is null */
3622 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3624 MUTEX_EXIT(&call->lock);
3628 MUTEX_EXIT(&conn->conn_data_lock);
3632 rx_ack_reason(int reason)
3635 case RX_ACK_REQUESTED:
3637 case RX_ACK_DUPLICATE:
3639 case RX_ACK_OUT_OF_SEQUENCE:
3641 case RX_ACK_EXCEEDS_WINDOW:
3643 case RX_ACK_NOSPACE:
3647 case RX_ACK_PING_RESPONSE:
3659 /* rxi_ComputePeerNetStats
3661 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3662 * estimates (like RTT and throughput) based on ack packets. Caller
3663 * must ensure that the packet in question is the right one (i.e.
3664 * serial number matches).
3667 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3668 struct rx_ackPacket *ap, struct rx_packet *np)
3670 struct rx_peer *peer = call->conn->peer;
3672 /* Use RTT if not delayed by client. */
3673 if (ap->reason != RX_ACK_DELAY)
3674 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3676 rxi_ComputeRate(peer, call, p, np, ap->reason);
3680 /* The real smarts of the whole thing. */
3682 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3685 struct rx_ackPacket *ap;
3687 struct rx_packet *tp;
3688 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3689 struct rx_connection *conn = call->conn;
3690 struct rx_peer *peer = conn->peer;
3693 /* because there are CM's that are bogus, sending weird values for this. */
3694 afs_uint32 skew = 0;
3699 int newAckCount = 0;
3700 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3701 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3703 if (rx_stats_active)
3704 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3705 ap = (struct rx_ackPacket *)rx_DataOf(np);
3706 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3708 return np; /* truncated ack packet */
3710 /* depends on ack packet struct */
3711 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3712 first = ntohl(ap->firstPacket);
3713 serial = ntohl(ap->serial);
3714 /* temporarily disabled -- needs to degrade over time
3715 * skew = ntohs(ap->maxSkew); */
3717 /* Ignore ack packets received out of order */
3718 if (first < call->tfirst) {
3722 if (np->header.flags & RX_SLOW_START_OK) {
3723 call->flags |= RX_CALL_SLOW_START_OK;
3726 if (ap->reason == RX_ACK_PING_RESPONSE)
3727 rxi_UpdatePeerReach(conn, call);
3731 if (rxdebug_active) {
3735 len = _snprintf(msg, sizeof(msg),
3736 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3737 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3738 ntohl(ap->serial), ntohl(ap->previousPacket),
3739 (unsigned int)np->header.seq, (unsigned int)skew,
3740 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3744 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3745 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3749 OutputDebugString(msg);
3751 #else /* AFS_NT40_ENV */
3754 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3755 ap->reason, ntohl(ap->previousPacket),
3756 (unsigned int)np->header.seq, (unsigned int)serial,
3757 (unsigned int)skew, ntohl(ap->firstPacket));
3760 for (offset = 0; offset < nAcks; offset++)
3761 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3766 #endif /* AFS_NT40_ENV */
3769 /* Update the outgoing packet skew value to the latest value of
3770 * the peer's incoming packet skew value. The ack packet, of
3771 * course, could arrive out of order, but that won't affect things
3773 MUTEX_ENTER(&peer->peer_lock);
3774 peer->outPacketSkew = skew;
3776 /* Check for packets that no longer need to be transmitted, and
3777 * discard them. This only applies to packets positively
3778 * acknowledged as having been sent to the peer's upper level.
3779 * All other packets must be retained. So only packets with
3780 * sequence numbers < ap->firstPacket are candidates. */
3781 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3782 if (tp->header.seq >= first)
3784 call->tfirst = tp->header.seq + 1;
3786 && (tp->header.serial == serial || tp->firstSerial == serial))
3787 rxi_ComputePeerNetStats(call, tp, ap, np);
3788 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3791 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3792 /* XXX Hack. Because we have to release the global rx lock when sending
3793 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3794 * in rxi_Start sending packets out because packets may move to the
3795 * freePacketQueue as result of being here! So we drop these packets until
3796 * we're safely out of the traversing. Really ugly!
3797 * To make it even uglier, if we're using fine grain locking, we can
3798 * set the ack bits in the packets and have rxi_Start remove the packets
3799 * when it's done transmitting.
3801 if (call->flags & RX_CALL_TQ_BUSY) {
3802 #ifdef RX_ENABLE_LOCKS
3803 tp->flags |= RX_PKTFLAG_ACKED;
3804 call->flags |= RX_CALL_TQ_SOME_ACKED;
3805 #else /* RX_ENABLE_LOCKS */
3807 #endif /* RX_ENABLE_LOCKS */
3809 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3812 tp->flags &= ~RX_PKTFLAG_TQ;
3813 #ifdef RXDEBUG_PACKET
3815 #endif /* RXDEBUG_PACKET */
3816 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3821 /* Give rate detector a chance to respond to ping requests */
3822 if (ap->reason == RX_ACK_PING_RESPONSE) {
3823 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3827 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3829 /* Now go through explicit acks/nacks and record the results in
3830 * the waiting packets. These are packets that can't be released
3831 * yet, even with a positive acknowledge. This positive
3832 * acknowledge only means the packet has been received by the
3833 * peer, not that it will be retained long enough to be sent to
3834 * the peer's upper level. In addition, reset the transmit timers
3835 * of any missing packets (those packets that must be missing
3836 * because this packet was out of sequence) */
3838 call->nSoftAcked = 0;
3839 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3840 /* Update round trip time if the ack was stimulated on receipt
3842 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3843 #ifdef RX_ENABLE_LOCKS
3844 if (tp->header.seq >= first)
3845 #endif /* RX_ENABLE_LOCKS */
3846 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3848 && (tp->header.serial == serial || tp->firstSerial == serial))
3849 rxi_ComputePeerNetStats(call, tp, ap, np);
3851 /* Set the acknowledge flag per packet based on the
3852 * information in the ack packet. An acknowlegded packet can
3853 * be downgraded when the server has discarded a packet it
3854 * soacked previously, or when an ack packet is received
3855 * out of sequence. */
3856 if (tp->header.seq < first) {
3857 /* Implicit ack information */
3858 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3861 tp->flags |= RX_PKTFLAG_ACKED;
3862 } else if (tp->header.seq < first + nAcks) {
3863 /* Explicit ack information: set it in the packet appropriately */
3864 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3865 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3867 tp->flags |= RX_PKTFLAG_ACKED;
3874 } else /* RX_ACK_TYPE_NACK */ {
3875 tp->flags &= ~RX_PKTFLAG_ACKED;
3879 tp->flags &= ~RX_PKTFLAG_ACKED;
3883 /* If packet isn't yet acked, and it has been transmitted at least
3884 * once, reset retransmit time using latest timeout
3885 * ie, this should readjust the retransmit timer for all outstanding
3886 * packets... So we don't just retransmit when we should know better*/
3888 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3889 tp->retryTime = tp->timeSent;
3890 clock_Add(&tp->retryTime, &peer->timeout);
3891 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3892 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3896 /* If the window has been extended by this acknowledge packet,
3897 * then wakeup a sender waiting in alloc for window space, or try
3898 * sending packets now, if he's been sitting on packets due to
3899 * lack of window space */
3900 if (call->tnext < (call->tfirst + call->twind)) {
3901 #ifdef RX_ENABLE_LOCKS
3902 CV_SIGNAL(&call->cv_twind);
3904 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3905 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3906 osi_rxWakeup(&call->twind);
3909 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3910 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3914 /* if the ack packet has a receivelen field hanging off it,
3915 * update our state */
3916 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3919 /* If the ack packet has a "recommended" size that is less than
3920 * what I am using now, reduce my size to match */
3921 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3922 (int)sizeof(afs_int32), &tSize);
3923 tSize = (afs_uint32) ntohl(tSize);
3924 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3926 /* Get the maximum packet size to send to this peer */
3927 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3929 tSize = (afs_uint32) ntohl(tSize);
3930 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3931 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3933 /* sanity check - peer might have restarted with different params.
3934 * If peer says "send less", dammit, send less... Peer should never
3935 * be unable to accept packets of the size that prior AFS versions would
3936 * send without asking. */
3937 if (peer->maxMTU != tSize) {
3938 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3940 peer->maxMTU = tSize;
3941 peer->MTU = MIN(tSize, peer->MTU);
3942 call->MTU = MIN(call->MTU, tSize);
3945 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3948 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3949 (int)sizeof(afs_int32), &tSize);
3950 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3951 if (tSize < call->twind) { /* smaller than our send */
3952 call->twind = tSize; /* window, we must send less... */
3953 call->ssthresh = MIN(call->twind, call->ssthresh);
3954 call->conn->twind[call->channel] = call->twind;
3957 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3958 * network MTU confused with the loopback MTU. Calculate the
3959 * maximum MTU here for use in the slow start code below.
3961 maxMTU = peer->maxMTU;
3962 /* Did peer restart with older RX version? */
3963 if (peer->maxDgramPackets > 1) {
3964 peer->maxDgramPackets = 1;
3966 } else if (np->length >=
3967 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3970 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3971 sizeof(afs_int32), &tSize);
3972 tSize = (afs_uint32) ntohl(tSize);
3974 * As of AFS 3.5 we set the send window to match the receive window.
3976 if (tSize < call->twind) {
3977 call->twind = tSize;
3978 call->conn->twind[call->channel] = call->twind;
3979 call->ssthresh = MIN(call->twind, call->ssthresh);
3980 } else if (tSize > call->twind) {
3981 call->twind = tSize;
3982 call->conn->twind[call->channel] = call->twind;
3986 * As of AFS 3.5, a jumbogram is more than one fixed size
3987 * packet transmitted in a single UDP datagram. If the remote
3988 * MTU is smaller than our local MTU then never send a datagram
3989 * larger than the natural MTU.
3992 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
3993 sizeof(afs_int32), &tSize);
3994 maxDgramPackets = (afs_uint32) ntohl(tSize);
3995 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
3997 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
3998 maxDgramPackets = MIN(maxDgramPackets, tSize);
3999 if (maxDgramPackets > 1) {
4000 peer->maxDgramPackets = maxDgramPackets;
4001 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4003 peer->maxDgramPackets = 1;
4004 call->MTU = peer->natMTU;
4006 } else if (peer->maxDgramPackets > 1) {
4007 /* Restarted with lower version of RX */
4008 peer->maxDgramPackets = 1;
4010 } else if (peer->maxDgramPackets > 1
4011 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4012 /* Restarted with lower version of RX */
4013 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4014 peer->natMTU = OLD_MAX_PACKET_SIZE;
4015 peer->MTU = OLD_MAX_PACKET_SIZE;
4016 peer->maxDgramPackets = 1;
4017 peer->nDgramPackets = 1;
4019 call->MTU = OLD_MAX_PACKET_SIZE;
4024 * Calculate how many datagrams were successfully received after
4025 * the first missing packet and adjust the negative ack counter
4030 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4031 if (call->nNacks < nNacked) {
4032 call->nNacks = nNacked;
4035 call->nAcks += newAckCount;
4039 if (call->flags & RX_CALL_FAST_RECOVER) {
4041 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4043 call->flags &= ~RX_CALL_FAST_RECOVER;
4044 call->cwind = call->nextCwind;
4045 call->nextCwind = 0;
4048 call->nCwindAcks = 0;
4049 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4050 /* Three negative acks in a row trigger congestion recovery */
4051 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4052 MUTEX_EXIT(&peer->peer_lock);
4053 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4054 /* someone else is waiting to start recovery */
4057 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4058 rxi_WaitforTQBusy(call);
4059 MUTEX_ENTER(&peer->peer_lock);
4060 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4061 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4062 call->flags |= RX_CALL_FAST_RECOVER;
4063 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4065 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4066 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4067 call->nextCwind = call->ssthresh;
4070 peer->MTU = call->MTU;
4071 peer->cwind = call->nextCwind;
4072 peer->nDgramPackets = call->nDgramPackets;
4074 call->congestSeq = peer->congestSeq;
4075 /* Reset the resend times on the packets that were nacked
4076 * so we will retransmit as soon as the window permits*/
4077 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4079 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4080 clock_Zero(&tp->retryTime);
4082 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4087 /* If cwind is smaller than ssthresh, then increase
4088 * the window one packet for each ack we receive (exponential
4090 * If cwind is greater than or equal to ssthresh then increase
4091 * the congestion window by one packet for each cwind acks we
4092 * receive (linear growth). */
4093 if (call->cwind < call->ssthresh) {
4095 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4096 call->nCwindAcks = 0;
4098 call->nCwindAcks += newAckCount;
4099 if (call->nCwindAcks >= call->cwind) {
4100 call->nCwindAcks = 0;
4101 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4105 * If we have received several acknowledgements in a row then
4106 * it is time to increase the size of our datagrams
4108 if ((int)call->nAcks > rx_nDgramThreshold) {
4109 if (peer->maxDgramPackets > 1) {
4110 if (call->nDgramPackets < peer->maxDgramPackets) {
4111 call->nDgramPackets++;
4113 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4114 } else if (call->MTU < peer->maxMTU) {
4115 call->MTU += peer->natMTU;
4116 call->MTU = MIN(call->MTU, peer->maxMTU);
4122 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4124 /* Servers need to hold the call until all response packets have
4125 * been acknowledged. Soft acks are good enough since clients
4126 * are not allowed to clear their receive queues. */
4127 if (call->state == RX_STATE_HOLD
4128 && call->tfirst + call->nSoftAcked >= call->tnext) {
4129 call->state = RX_STATE_DALLY;
4130 rxi_ClearTransmitQueue(call, 0);
4131 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4132 } else if (!queue_IsEmpty(&call->tq)) {
4133 rxi_Start(0, call, 0, istack);
4138 /* Received a response to a challenge packet */
4140 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4141 struct rx_packet *np, int istack)
4145 /* Ignore the packet if we're the client */
4146 if (conn->type == RX_CLIENT_CONNECTION)
4149 /* If already authenticated, ignore the packet (it's probably a retry) */
4150 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4153 /* Otherwise, have the security object evaluate the response packet */
4154 error = RXS_CheckResponse(conn->securityObject, conn, np);
4156 /* If the response is invalid, reset the connection, sending
4157 * an abort to the peer */
4161 rxi_ConnectionError(conn, error);
4162 MUTEX_ENTER(&conn->conn_data_lock);
4163 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4164 MUTEX_EXIT(&conn->conn_data_lock);
4167 /* If the response is valid, any calls waiting to attach
4168 * servers can now do so */
4171 for (i = 0; i < RX_MAXCALLS; i++) {
4172 struct rx_call *call = conn->call[i];
4174 MUTEX_ENTER(&call->lock);
4175 if (call->state == RX_STATE_PRECALL)
4176 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4177 /* tnop can be null if newcallp is null */
4178 MUTEX_EXIT(&call->lock);
4182 /* Update the peer reachability information, just in case
4183 * some calls went into attach-wait while we were waiting
4184 * for authentication..
4186 rxi_UpdatePeerReach(conn, NULL);
4191 /* A client has received an authentication challenge: the security
4192 * object is asked to cough up a respectable response packet to send
4193 * back to the server. The server is responsible for retrying the
4194 * challenge if it fails to get a response. */
4197 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4198 struct rx_packet *np, int istack)
4202 /* Ignore the challenge if we're the server */
4203 if (conn->type == RX_SERVER_CONNECTION)
4206 /* Ignore the challenge if the connection is otherwise idle; someone's
4207 * trying to use us as an oracle. */
4208 if (!rxi_HasActiveCalls(conn))
4211 /* Send the security object the challenge packet. It is expected to fill
4212 * in the response. */
4213 error = RXS_GetResponse(conn->securityObject, conn, np);
4215 /* If the security object is unable to return a valid response, reset the
4216 * connection and send an abort to the peer. Otherwise send the response
4217 * packet to the peer connection. */
4219 rxi_ConnectionError(conn, error);
4220 MUTEX_ENTER(&conn->conn_data_lock);
4221 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4222 MUTEX_EXIT(&conn->conn_data_lock);
4224 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4225 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4231 /* Find an available server process to service the current request in
4232 * the given call structure. If one isn't available, queue up this
4233 * call so it eventually gets one */
4235 rxi_AttachServerProc(struct rx_call *call,
4236 osi_socket socket, int *tnop,
4237 struct rx_call **newcallp)
4239 struct rx_serverQueueEntry *sq;
4240 struct rx_service *service = call->conn->service;
4243 /* May already be attached */
4244 if (call->state == RX_STATE_ACTIVE)
4247 MUTEX_ENTER(&rx_serverPool_lock);
4249 haveQuota = QuotaOK(service);
4250 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4251 /* If there are no processes available to service this call,
4252 * put the call on the incoming call queue (unless it's
4253 * already on the queue).
4255 #ifdef RX_ENABLE_LOCKS
4257 ReturnToServerPool(service);
4258 #endif /* RX_ENABLE_LOCKS */
4260 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4261 call->flags |= RX_CALL_WAIT_PROC;
4262 MUTEX_ENTER(&rx_waiting_mutex);
4265 MUTEX_EXIT(&rx_waiting_mutex);
4266 rxi_calltrace(RX_CALL_ARRIVAL, call);
4267 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4268 queue_Append(&rx_incomingCallQueue, call);
4271 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4273 /* If hot threads are enabled, and both newcallp and sq->socketp
4274 * are non-null, then this thread will process the call, and the
4275 * idle server thread will start listening on this threads socket.
4278 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4281 *sq->socketp = socket;
4282 clock_GetTime(&call->startTime);
4283 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4287 if (call->flags & RX_CALL_WAIT_PROC) {
4288 /* Conservative: I don't think this should happen */
4289 call->flags &= ~RX_CALL_WAIT_PROC;
4290 if (queue_IsOnQueue(call)) {
4293 MUTEX_ENTER(&rx_waiting_mutex);
4295 MUTEX_EXIT(&rx_waiting_mutex);
4298 call->state = RX_STATE_ACTIVE;
4299 call->mode = RX_MODE_RECEIVING;
4300 #ifdef RX_KERNEL_TRACE
4302 int glockOwner = ISAFS_GLOCK();
4305 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4306 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4312 if (call->flags & RX_CALL_CLEARED) {
4313 /* send an ack now to start the packet flow up again */
4314 call->flags &= ~RX_CALL_CLEARED;
4315 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4317 #ifdef RX_ENABLE_LOCKS
4320 service->nRequestsRunning++;
4321 if (service->nRequestsRunning <= service->minProcs)
4327 MUTEX_EXIT(&rx_serverPool_lock);
4330 /* Delay the sending of an acknowledge event for a short while, while
4331 * a new call is being prepared (in the case of a client) or a reply
4332 * is being prepared (in the case of a server). Rather than sending
4333 * an ack packet, an ACKALL packet is sent. */
4335 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4337 #ifdef RX_ENABLE_LOCKS
4339 MUTEX_ENTER(&call->lock);
4340 call->delayedAckEvent = NULL;
4341 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4343 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4344 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4346 MUTEX_EXIT(&call->lock);
4347 #else /* RX_ENABLE_LOCKS */
4349 call->delayedAckEvent = NULL;
4350 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4351 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4352 #endif /* RX_ENABLE_LOCKS */
4356 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4358 struct rx_call *call = arg1;
4359 #ifdef RX_ENABLE_LOCKS
4361 MUTEX_ENTER(&call->lock);
4362 if (event == call->delayedAckEvent)
4363 call->delayedAckEvent = NULL;
4364 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4366 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4368 MUTEX_EXIT(&call->lock);
4369 #else /* RX_ENABLE_LOCKS */
4371 call->delayedAckEvent = NULL;
4372 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4373 #endif /* RX_ENABLE_LOCKS */
4377 #ifdef RX_ENABLE_LOCKS
4378 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4379 * clearing them out.
4382 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4384 struct rx_packet *p, *tp;
4387 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4388 p->flags |= RX_PKTFLAG_ACKED;
4392 call->flags |= RX_CALL_TQ_CLEARME;
4393 call->flags |= RX_CALL_TQ_SOME_ACKED;
4396 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4397 call->tfirst = call->tnext;
4398 call->nSoftAcked = 0;
4400 if (call->flags & RX_CALL_FAST_RECOVER) {
4401 call->flags &= ~RX_CALL_FAST_RECOVER;
4402 call->cwind = call->nextCwind;
4403 call->nextCwind = 0;
4406 CV_SIGNAL(&call->cv_twind);
4408 #endif /* RX_ENABLE_LOCKS */
4410 /* Clear out the transmit queue for the current call (all packets have
4411 * been received by peer) */
4413 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4415 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4416 struct rx_packet *p, *tp;
4418 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4420 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4421 p->flags |= RX_PKTFLAG_ACKED;
4425 call->flags |= RX_CALL_TQ_CLEARME;
4426 call->flags |= RX_CALL_TQ_SOME_ACKED;
4429 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4430 #ifdef RXDEBUG_PACKET
4432 #endif /* RXDEBUG_PACKET */
4433 rxi_FreePackets(0, &call->tq);
4434 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4435 call->flags &= ~RX_CALL_TQ_CLEARME;
4437 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4439 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4440 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4441 call->nSoftAcked = 0;
4443 if (call->flags & RX_CALL_FAST_RECOVER) {
4444 call->flags &= ~RX_CALL_FAST_RECOVER;
4445 call->cwind = call->nextCwind;
4447 #ifdef RX_ENABLE_LOCKS
4448 CV_SIGNAL(&call->cv_twind);
4450 osi_rxWakeup(&call->twind);
4455 rxi_ClearReceiveQueue(struct rx_call *call)
4457 if (queue_IsNotEmpty(&call->rq)) {
4460 count = rxi_FreePackets(0, &call->rq);
4461 rx_packetReclaims += count;
4462 #ifdef RXDEBUG_PACKET
4464 if ( call->rqc != 0 )
4465 dpf(("rxi_ClearReceiveQueue call %x rqc %u != 0", call, call->rqc));
4467 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4469 if (call->state == RX_STATE_PRECALL) {
4470 call->flags |= RX_CALL_CLEARED;
4474 /* Send an abort packet for the specified call */
4476 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
4477 int istack, int force)
4480 struct clock when, now;
4485 /* Clients should never delay abort messages */
4486 if (rx_IsClientConn(call->conn))
4489 if (call->abortCode != call->error) {
4490 call->abortCode = call->error;
4491 call->abortCount = 0;
4494 if (force || rxi_callAbortThreshhold == 0
4495 || call->abortCount < rxi_callAbortThreshhold) {
4496 if (call->delayedAbortEvent) {
4497 rxevent_Cancel(call->delayedAbortEvent, call,
4498 RX_CALL_REFCOUNT_ABORT);
4500 error = htonl(call->error);
4503 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4504 (char *)&error, sizeof(error), istack);
4505 } else if (!call->delayedAbortEvent) {
4506 clock_GetTime(&now);
4508 clock_Addmsec(&when, rxi_callAbortDelay);
4509 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4510 call->delayedAbortEvent =
4511 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4516 /* Send an abort packet for the specified connection. Packet is an
4517 * optional pointer to a packet that can be used to send the abort.
4518 * Once the number of abort messages reaches the threshhold, an
4519 * event is scheduled to send the abort. Setting the force flag
4520 * overrides sending delayed abort messages.
4522 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4523 * to send the abort packet.
4526 rxi_SendConnectionAbort(struct rx_connection *conn,
4527 struct rx_packet *packet, int istack, int force)
4530 struct clock when, now;
4535 /* Clients should never delay abort messages */
4536 if (rx_IsClientConn(conn))
4539 if (force || rxi_connAbortThreshhold == 0
4540 || conn->abortCount < rxi_connAbortThreshhold) {
4541 if (conn->delayedAbortEvent) {
4542 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4544 error = htonl(conn->error);
4546 MUTEX_EXIT(&conn->conn_data_lock);
4548 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4549 RX_PACKET_TYPE_ABORT, (char *)&error,
4550 sizeof(error), istack);
4551 MUTEX_ENTER(&conn->conn_data_lock);
4552 } else if (!conn->delayedAbortEvent) {
4553 clock_GetTime(&now);
4555 clock_Addmsec(&when, rxi_connAbortDelay);
4556 conn->delayedAbortEvent =
4557 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4562 /* Associate an error all of the calls owned by a connection. Called
4563 * with error non-zero. This is only for really fatal things, like
4564 * bad authentication responses. The connection itself is set in
4565 * error at this point, so that future packets received will be
4568 rxi_ConnectionError(struct rx_connection *conn,
4574 dpf(("rxi_ConnectionError conn %x error %d", conn, error));
4576 MUTEX_ENTER(&conn->conn_data_lock);
4577 if (conn->challengeEvent)
4578 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4579 if (conn->checkReachEvent) {
4580 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4581 conn->checkReachEvent = 0;
4582 conn->flags &= ~RX_CONN_ATTACHWAIT;
4585 MUTEX_EXIT(&conn->conn_data_lock);
4586 for (i = 0; i < RX_MAXCALLS; i++) {
4587 struct rx_call *call = conn->call[i];
4589 MUTEX_ENTER(&call->lock);
4590 rxi_CallError(call, error);
4591 MUTEX_EXIT(&call->lock);
4594 conn->error = error;
4595 if (rx_stats_active)
4596 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4601 rxi_CallError(struct rx_call *call, afs_int32 error)
4604 osirx_AssertMine(&call->lock, "rxi_CallError");
4606 dpf(("rxi_CallError call %x error %d call->error %d", call, error, call->error));
4608 error = call->error;
4610 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4611 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4612 rxi_ResetCall(call, 0);
4615 rxi_ResetCall(call, 0);
4617 call->error = error;
4618 call->mode = RX_MODE_ERROR;
4621 /* Reset various fields in a call structure, and wakeup waiting
4622 * processes. Some fields aren't changed: state & mode are not
4623 * touched (these must be set by the caller), and bufptr, nLeft, and
4624 * nFree are not reset, since these fields are manipulated by
4625 * unprotected macros, and may only be reset by non-interrupting code.
4628 /* this code requires that call->conn be set properly as a pre-condition. */
4629 #endif /* ADAPT_WINDOW */
4632 rxi_ResetCall(struct rx_call *call, int newcall)
4635 struct rx_peer *peer;
4636 struct rx_packet *packet;
4638 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4640 dpf(("rxi_ResetCall(call %x, newcall %d)\n", call, newcall));
4642 /* Notify anyone who is waiting for asynchronous packet arrival */
4643 if (call->arrivalProc) {
4644 (*call->arrivalProc) (call, call->arrivalProcHandle,
4645 call->arrivalProcArg);
4646 call->arrivalProc = (void (*)())0;
4649 if (call->delayedAbortEvent) {
4650 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4651 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4653 rxi_SendCallAbort(call, packet, 0, 1);
4654 rxi_FreePacket(packet);
4659 * Update the peer with the congestion information in this call
4660 * so other calls on this connection can pick up where this call
4661 * left off. If the congestion sequence numbers don't match then
4662 * another call experienced a retransmission.
4664 peer = call->conn->peer;
4665 MUTEX_ENTER(&peer->peer_lock);
4667 if (call->congestSeq == peer->congestSeq) {
4668 peer->cwind = MAX(peer->cwind, call->cwind);
4669 peer->MTU = MAX(peer->MTU, call->MTU);
4670 peer->nDgramPackets =
4671 MAX(peer->nDgramPackets, call->nDgramPackets);
4674 call->abortCode = 0;
4675 call->abortCount = 0;
4677 if (peer->maxDgramPackets > 1) {
4678 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4680 call->MTU = peer->MTU;
4682 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4683 call->ssthresh = rx_maxSendWindow;
4684 call->nDgramPackets = peer->nDgramPackets;
4685 call->congestSeq = peer->congestSeq;
4686 MUTEX_EXIT(&peer->peer_lock);
4688 flags = call->flags;
4689 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4690 if (flags & RX_CALL_TQ_BUSY) {
4691 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4692 call->flags |= (flags & RX_CALL_TQ_WAIT);
4694 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4696 rxi_ClearTransmitQueue(call, 1);
4697 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4698 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4699 dpf(("rcall %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4702 while (call->tqWaiters) {
4703 #ifdef RX_ENABLE_LOCKS
4704 CV_BROADCAST(&call->cv_tq);
4705 #else /* RX_ENABLE_LOCKS */
4706 osi_rxWakeup(&call->tq);
4707 #endif /* RX_ENABLE_LOCKS */
4712 rxi_ClearReceiveQueue(call);
4713 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4715 if (call->currentPacket) {
4716 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4717 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4718 queue_Prepend(&call->iovq, call->currentPacket);
4719 #ifdef RXDEBUG_PACKET
4721 #endif /* RXDEBUG_PACKET */
4722 call->currentPacket = (struct rx_packet *)0;
4724 call->curlen = call->nLeft = call->nFree = 0;
4726 #ifdef RXDEBUG_PACKET
4729 rxi_FreePackets(0, &call->iovq);
4732 call->twind = call->conn->twind[call->channel];
4733 call->rwind = call->conn->rwind[call->channel];
4734 call->nSoftAcked = 0;
4735 call->nextCwind = 0;
4738 call->nCwindAcks = 0;
4739 call->nSoftAcks = 0;
4740 call->nHardAcks = 0;
4742 call->tfirst = call->rnext = call->tnext = 1;
4744 call->lastAcked = 0;
4745 call->localStatus = call->remoteStatus = 0;
4747 if (flags & RX_CALL_READER_WAIT) {
4748 #ifdef RX_ENABLE_LOCKS
4749 CV_BROADCAST(&call->cv_rq);
4751 osi_rxWakeup(&call->rq);
4754 if (flags & RX_CALL_WAIT_PACKETS) {
4755 MUTEX_ENTER(&rx_freePktQ_lock);
4756 rxi_PacketsUnWait(); /* XXX */
4757 MUTEX_EXIT(&rx_freePktQ_lock);
4759 #ifdef RX_ENABLE_LOCKS
4760 CV_SIGNAL(&call->cv_twind);
4762 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4763 osi_rxWakeup(&call->twind);
4766 #ifdef RX_ENABLE_LOCKS
4767 /* The following ensures that we don't mess with any queue while some
4768 * other thread might also be doing so. The call_queue_lock field is
4769 * is only modified under the call lock. If the call is in the process
4770 * of being removed from a queue, the call is not locked until the
4771 * the queue lock is dropped and only then is the call_queue_lock field
4772 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4773 * Note that any other routine which removes a call from a queue has to
4774 * obtain the queue lock before examing the queue and removing the call.
4776 if (call->call_queue_lock) {
4777 MUTEX_ENTER(call->call_queue_lock);
4778 if (queue_IsOnQueue(call)) {
4780 if (flags & RX_CALL_WAIT_PROC) {
4782 MUTEX_ENTER(&rx_waiting_mutex);
4784 MUTEX_EXIT(&rx_waiting_mutex);
4787 MUTEX_EXIT(call->call_queue_lock);
4788 CLEAR_CALL_QUEUE_LOCK(call);
4790 #else /* RX_ENABLE_LOCKS */
4791 if (queue_IsOnQueue(call)) {
4793 if (flags & RX_CALL_WAIT_PROC)
4796 #endif /* RX_ENABLE_LOCKS */
4798 rxi_KeepAliveOff(call);
4799 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4802 /* Send an acknowledge for the indicated packet (seq,serial) of the
4803 * indicated call, for the indicated reason (reason). This
4804 * acknowledge will specifically acknowledge receiving the packet, and
4805 * will also specify which other packets for this call have been
4806 * received. This routine returns the packet that was used to the
4807 * caller. The caller is responsible for freeing it or re-using it.
4808 * This acknowledgement also returns the highest sequence number
4809 * actually read out by the higher level to the sender; the sender
4810 * promises to keep around packets that have not been read by the
4811 * higher level yet (unless, of course, the sender decides to abort
4812 * the call altogether). Any of p, seq, serial, pflags, or reason may
4813 * be set to zero without ill effect. That is, if they are zero, they
4814 * will not convey any information.
4815 * NOW there is a trailer field, after the ack where it will safely be
4816 * ignored by mundanes, which indicates the maximum size packet this
4817 * host can swallow. */
4819 struct rx_packet *optionalPacket; use to send ack (or null)
4820 int seq; Sequence number of the packet we are acking
4821 int serial; Serial number of the packet
4822 int pflags; Flags field from packet header
4823 int reason; Reason an acknowledge was prompted
4827 rxi_SendAck(struct rx_call *call,
4828 struct rx_packet *optionalPacket, int serial, int reason,
4831 struct rx_ackPacket *ap;
4832 struct rx_packet *rqp;
4833 struct rx_packet *nxp; /* For queue_Scan */
4834 struct rx_packet *p;
4837 #ifdef RX_ENABLE_TSFPQ
4838 struct rx_ts_info_t * rx_ts_info;
4842 * Open the receive window once a thread starts reading packets
4844 if (call->rnext > 1) {
4845 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4848 call->nHardAcks = 0;
4849 call->nSoftAcks = 0;
4850 if (call->rnext > call->lastAcked)
4851 call->lastAcked = call->rnext;
4855 rx_computelen(p, p->length); /* reset length, you never know */
4856 } /* where that's been... */
4857 #ifdef RX_ENABLE_TSFPQ
4859 RX_TS_INFO_GET(rx_ts_info);
4860 if ((p = rx_ts_info->local_special_packet)) {
4861 rx_computelen(p, p->length);
4862 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4863 rx_ts_info->local_special_packet = p;
4864 } else { /* We won't send the ack, but don't panic. */
4865 return optionalPacket;
4869 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4870 /* We won't send the ack, but don't panic. */
4871 return optionalPacket;
4876 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4879 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4880 #ifndef RX_ENABLE_TSFPQ
4881 if (!optionalPacket)
4884 return optionalPacket;
4886 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4887 if (rx_Contiguous(p) < templ) {
4888 #ifndef RX_ENABLE_TSFPQ
4889 if (!optionalPacket)
4892 return optionalPacket;
4897 /* MTUXXX failing to send an ack is very serious. We should */
4898 /* try as hard as possible to send even a partial ack; it's */
4899 /* better than nothing. */
4900 ap = (struct rx_ackPacket *)rx_DataOf(p);
4901 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4902 ap->reason = reason;
4904 /* The skew computation used to be bogus, I think it's better now. */
4905 /* We should start paying attention to skew. XXX */
4906 ap->serial = htonl(serial);
4907 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4909 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4910 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4912 /* No fear of running out of ack packet here because there can only be at most
4913 * one window full of unacknowledged packets. The window size must be constrained
4914 * to be less than the maximum ack size, of course. Also, an ack should always
4915 * fit into a single packet -- it should not ever be fragmented. */
4916 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4917 if (!rqp || !call->rq.next
4918 || (rqp->header.seq > (call->rnext + call->rwind))) {
4919 #ifndef RX_ENABLE_TSFPQ
4920 if (!optionalPacket)
4923 rxi_CallError(call, RX_CALL_DEAD);
4924 return optionalPacket;
4927 while (rqp->header.seq > call->rnext + offset)
4928 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4929 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4931 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4932 #ifndef RX_ENABLE_TSFPQ
4933 if (!optionalPacket)
4936 rxi_CallError(call, RX_CALL_DEAD);
4937 return optionalPacket;
4942 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4944 /* these are new for AFS 3.3 */
4945 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4946 templ = htonl(templ);
4947 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4948 templ = htonl(call->conn->peer->ifMTU);
4949 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4950 sizeof(afs_int32), &templ);
4952 /* new for AFS 3.4 */
4953 templ = htonl(call->rwind);
4954 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4955 sizeof(afs_int32), &templ);
4957 /* new for AFS 3.5 */
4958 templ = htonl(call->conn->peer->ifDgramPackets);
4959 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4960 sizeof(afs_int32), &templ);
4962 p->header.serviceId = call->conn->serviceId;
4963 p->header.cid = (call->conn->cid | call->channel);
4964 p->header.callNumber = *call->callNumber;
4966 p->header.securityIndex = call->conn->securityIndex;
4967 p->header.epoch = call->conn->epoch;
4968 p->header.type = RX_PACKET_TYPE_ACK;
4969 p->header.flags = RX_SLOW_START_OK;
4970 if (reason == RX_ACK_PING) {
4971 p->header.flags |= RX_REQUEST_ACK;
4973 clock_GetTime(&call->pingRequestTime);
4976 if (call->conn->type == RX_CLIENT_CONNECTION)
4977 p->header.flags |= RX_CLIENT_INITIATED;
4981 if (rxdebug_active) {
4985 len = _snprintf(msg, sizeof(msg),
4986 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4987 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4988 ntohl(ap->serial), ntohl(ap->previousPacket),
4989 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
4990 ap->nAcks, ntohs(ap->bufferSpace) );
4994 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
4995 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4999 OutputDebugString(msg);
5001 #else /* AFS_NT40_ENV */
5003 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5004 ap->reason, ntohl(ap->previousPacket),
5005 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5007 for (offset = 0; offset < ap->nAcks; offset++)
5008 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5013 #endif /* AFS_NT40_ENV */
5016 int i, nbytes = p->length;
5018 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5019 if (nbytes <= p->wirevec[i].iov_len) {
5022 savelen = p->wirevec[i].iov_len;
5024 p->wirevec[i].iov_len = nbytes;
5026 rxi_Send(call, p, istack);
5027 p->wirevec[i].iov_len = savelen;
5031 nbytes -= p->wirevec[i].iov_len;
5034 if (rx_stats_active)
5035 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5036 #ifndef RX_ENABLE_TSFPQ
5037 if (!optionalPacket)
5040 return optionalPacket; /* Return packet for re-use by caller */
5043 /* Send all of the packets in the list in single datagram */
5045 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5046 int istack, int moreFlag, struct clock *now,
5047 struct clock *retryTime, int resending)
5052 struct rx_connection *conn = call->conn;
5053 struct rx_peer *peer = conn->peer;
5055 MUTEX_ENTER(&peer->peer_lock);
5058 peer->reSends += len;
5059 if (rx_stats_active)
5060 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5061 MUTEX_EXIT(&peer->peer_lock);
5063 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5067 /* Set the packet flags and schedule the resend events */
5068 /* Only request an ack for the last packet in the list */
5069 for (i = 0; i < len; i++) {
5070 list[i]->retryTime = *retryTime;
5071 if (list[i]->header.serial) {
5072 /* Exponentially backoff retry times */
5073 if (list[i]->backoff < MAXBACKOFF) {
5074 /* so it can't stay == 0 */
5075 list[i]->backoff = (list[i]->backoff << 1) + 1;
5078 clock_Addmsec(&(list[i]->retryTime),
5079 ((afs_uint32) list[i]->backoff) << 8);
5082 /* Wait a little extra for the ack on the last packet */
5083 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5084 clock_Addmsec(&(list[i]->retryTime), 400);
5087 /* Record the time sent */
5088 list[i]->timeSent = *now;
5090 /* Ask for an ack on retransmitted packets, on every other packet
5091 * if the peer doesn't support slow start. Ask for an ack on every
5092 * packet until the congestion window reaches the ack rate. */
5093 if (list[i]->header.serial) {
5095 if (rx_stats_active)
5096 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5098 /* improved RTO calculation- not Karn */
5099 list[i]->firstSent = *now;
5100 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5101 || (!(call->flags & RX_CALL_SLOW_START_OK)
5102 && (list[i]->header.seq & 1)))) {
5107 MUTEX_ENTER(&peer->peer_lock);
5111 if (rx_stats_active)
5112 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5113 MUTEX_EXIT(&peer->peer_lock);
5115 /* Tag this packet as not being the last in this group,
5116 * for the receiver's benefit */
5117 if (i < len - 1 || moreFlag) {
5118 list[i]->header.flags |= RX_MORE_PACKETS;
5121 /* Install the new retransmit time for the packet, and
5122 * record the time sent */
5123 list[i]->timeSent = *now;
5127 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5130 /* Since we're about to send a data packet to the peer, it's
5131 * safe to nuke any scheduled end-of-packets ack */
5132 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5134 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5135 MUTEX_EXIT(&call->lock);
5137 rxi_SendPacketList(call, conn, list, len, istack);
5139 rxi_SendPacket(call, conn, list[0], istack);
5141 MUTEX_ENTER(&call->lock);
5142 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5144 /* Update last send time for this call (for keep-alive
5145 * processing), and for the connection (so that we can discover
5146 * idle connections) */
5147 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5150 /* When sending packets we need to follow these rules:
5151 * 1. Never send more than maxDgramPackets in a jumbogram.
5152 * 2. Never send a packet with more than two iovecs in a jumbogram.
5153 * 3. Never send a retransmitted packet in a jumbogram.
5154 * 4. Never send more than cwind/4 packets in a jumbogram
5155 * We always keep the last list we should have sent so we
5156 * can set the RX_MORE_PACKETS flags correctly.
5159 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5160 int istack, struct clock *now, struct clock *retryTime,
5163 int i, cnt, lastCnt = 0;
5164 struct rx_packet **listP, **lastP = 0;
5165 struct rx_peer *peer = call->conn->peer;
5166 int morePackets = 0;
5168 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5169 /* Does the current packet force us to flush the current list? */
5171 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5172 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5174 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5176 /* If the call enters an error state stop sending, or if
5177 * we entered congestion recovery mode, stop sending */
5178 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5186 /* Add the current packet to the list if it hasn't been acked.
5187 * Otherwise adjust the list pointer to skip the current packet. */
5188 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5190 /* Do we need to flush the list? */
5191 if (cnt >= (int)peer->maxDgramPackets
5192 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5193 || list[i]->header.serial
5194 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5196 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5197 retryTime, resending);
5198 /* If the call enters an error state stop sending, or if
5199 * we entered congestion recovery mode, stop sending */
5201 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5206 listP = &list[i + 1];
5211 osi_Panic("rxi_SendList error");
5213 listP = &list[i + 1];
5217 /* Send the whole list when the call is in receive mode, when
5218 * the call is in eof mode, when we are in fast recovery mode,
5219 * and when we have the last packet */
5220 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5221 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5222 || (call->flags & RX_CALL_FAST_RECOVER)) {
5223 /* Check for the case where the current list contains
5224 * an acked packet. Since we always send retransmissions
5225 * in a separate packet, we only need to check the first
5226 * packet in the list */
5227 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5231 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5232 retryTime, resending);
5233 /* If the call enters an error state stop sending, or if
5234 * we entered congestion recovery mode, stop sending */
5235 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5239 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5242 } else if (lastCnt > 0) {
5243 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5248 #ifdef RX_ENABLE_LOCKS
5249 /* Call rxi_Start, below, but with the call lock held. */
5251 rxi_StartUnlocked(struct rxevent *event,
5252 void *arg0, void *arg1, int istack)
5254 struct rx_call *call = arg0;
5256 MUTEX_ENTER(&call->lock);
5257 rxi_Start(event, call, arg1, istack);
5258 MUTEX_EXIT(&call->lock);
5260 #endif /* RX_ENABLE_LOCKS */
5262 /* This routine is called when new packets are readied for
5263 * transmission and when retransmission may be necessary, or when the
5264 * transmission window or burst count are favourable. This should be
5265 * better optimized for new packets, the usual case, now that we've
5266 * got rid of queues of send packets. XXXXXXXXXXX */
5268 rxi_Start(struct rxevent *event,
5269 void *arg0, void *arg1, int istack)
5271 struct rx_call *call = arg0;
5273 struct rx_packet *p;
5274 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5275 struct rx_peer *peer = call->conn->peer;
5276 struct clock now, usenow, retryTime;
5280 struct rx_packet **xmitList;
5283 /* If rxi_Start is being called as a result of a resend event,
5284 * then make sure that the event pointer is removed from the call
5285 * structure, since there is no longer a per-call retransmission
5287 if (event && event == call->resendEvent) {
5288 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5289 call->resendEvent = NULL;
5291 if (queue_IsEmpty(&call->tq)) {
5295 /* Timeouts trigger congestion recovery */
5296 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5297 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5298 /* someone else is waiting to start recovery */
5301 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5302 rxi_WaitforTQBusy(call);
5303 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5304 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5305 call->flags |= RX_CALL_FAST_RECOVER;
5306 if (peer->maxDgramPackets > 1) {
5307 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5309 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5311 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5312 call->nDgramPackets = 1;
5314 call->nextCwind = 1;
5317 MUTEX_ENTER(&peer->peer_lock);
5318 peer->MTU = call->MTU;
5319 peer->cwind = call->cwind;
5320 peer->nDgramPackets = 1;
5322 call->congestSeq = peer->congestSeq;
5323 MUTEX_EXIT(&peer->peer_lock);
5324 /* Clear retry times on packets. Otherwise, it's possible for
5325 * some packets in the queue to force resends at rates faster
5326 * than recovery rates.
5328 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5329 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5330 clock_Zero(&p->retryTime);
5335 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5336 if (rx_stats_active)
5337 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5342 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5343 /* Get clock to compute the re-transmit time for any packets
5344 * in this burst. Note, if we back off, it's reasonable to
5345 * back off all of the packets in the same manner, even if
5346 * some of them have been retransmitted more times than more
5348 * Do a dance to avoid blocking after setting now. */
5349 clock_Zero(&retryTime);
5350 MUTEX_ENTER(&peer->peer_lock);
5351 clock_Add(&retryTime, &peer->timeout);
5352 MUTEX_EXIT(&peer->peer_lock);
5353 clock_GetTime(&now);
5354 clock_Add(&retryTime, &now);
5356 /* Send (or resend) any packets that need it, subject to
5357 * window restrictions and congestion burst control
5358 * restrictions. Ask for an ack on the last packet sent in
5359 * this burst. For now, we're relying upon the window being
5360 * considerably bigger than the largest number of packets that
5361 * are typically sent at once by one initial call to
5362 * rxi_Start. This is probably bogus (perhaps we should ask
5363 * for an ack when we're half way through the current
5364 * window?). Also, for non file transfer applications, this
5365 * may end up asking for an ack for every packet. Bogus. XXXX
5368 * But check whether we're here recursively, and let the other guy
5371 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5372 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5373 call->flags |= RX_CALL_TQ_BUSY;
5375 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5377 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5378 call->flags &= ~RX_CALL_NEED_START;
5379 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5381 maxXmitPackets = MIN(call->twind, call->cwind);
5382 xmitList = (struct rx_packet **)
5383 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5384 /* XXXX else we must drop any mtx we hold */
5385 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5387 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5389 if (xmitList == NULL)
5390 osi_Panic("rxi_Start, failed to allocate xmit list");
5391 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5392 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5393 /* We shouldn't be sending packets if a thread is waiting
5394 * to initiate congestion recovery */
5398 && (call->flags & RX_CALL_FAST_RECOVER)) {
5399 /* Only send one packet during fast recovery */
5402 if ((p->flags & RX_PKTFLAG_FREE)
5403 || (!queue_IsEnd(&call->tq, nxp)
5404 && (nxp->flags & RX_PKTFLAG_FREE))
5405 || (p == (struct rx_packet *)&rx_freePacketQueue)
5406 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5407 osi_Panic("rxi_Start: xmit queue clobbered");
5409 if (p->flags & RX_PKTFLAG_ACKED) {
5410 /* Since we may block, don't trust this */
5411 usenow.sec = usenow.usec = 0;
5412 if (rx_stats_active)
5413 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5414 continue; /* Ignore this packet if it has been acknowledged */
5417 /* Turn off all flags except these ones, which are the same
5418 * on each transmission */
5419 p->header.flags &= RX_PRESET_FLAGS;
5421 if (p->header.seq >=
5422 call->tfirst + MIN((int)call->twind,
5423 (int)(call->nSoftAcked +
5425 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5426 /* Note: if we're waiting for more window space, we can
5427 * still send retransmits; hence we don't return here, but
5428 * break out to schedule a retransmit event */
5429 dpf(("call %d waiting for window",
5430 *(call->callNumber)));
5434 /* Transmit the packet if it needs to be sent. */
5435 if (!clock_Lt(&now, &p->retryTime)) {
5436 if (nXmitPackets == maxXmitPackets) {
5437 rxi_SendXmitList(call, xmitList, nXmitPackets,
5438 istack, &now, &retryTime,
5440 osi_Free(xmitList, maxXmitPackets *
5441 sizeof(struct rx_packet *));
5444 xmitList[nXmitPackets++] = p;
5448 /* xmitList now hold pointers to all of the packets that are
5449 * ready to send. Now we loop to send the packets */
5450 if (nXmitPackets > 0) {
5451 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5452 &now, &retryTime, resending);
5455 maxXmitPackets * sizeof(struct rx_packet *));
5457 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5459 * TQ references no longer protected by this flag; they must remain
5460 * protected by the global lock.
5462 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5463 call->flags &= ~RX_CALL_TQ_BUSY;
5464 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5465 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5466 #ifdef RX_ENABLE_LOCKS
5467 osirx_AssertMine(&call->lock, "rxi_Start start");
5468 CV_BROADCAST(&call->cv_tq);
5469 #else /* RX_ENABLE_LOCKS */
5470 osi_rxWakeup(&call->tq);
5471 #endif /* RX_ENABLE_LOCKS */
5476 /* We went into the error state while sending packets. Now is
5477 * the time to reset the call. This will also inform the using
5478 * process that the call is in an error state.
5480 if (rx_stats_active)
5481 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5482 call->flags &= ~RX_CALL_TQ_BUSY;
5483 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5484 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5485 #ifdef RX_ENABLE_LOCKS
5486 osirx_AssertMine(&call->lock, "rxi_Start middle");
5487 CV_BROADCAST(&call->cv_tq);
5488 #else /* RX_ENABLE_LOCKS */
5489 osi_rxWakeup(&call->tq);
5490 #endif /* RX_ENABLE_LOCKS */
5492 rxi_CallError(call, call->error);
5495 #ifdef RX_ENABLE_LOCKS
5496 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5498 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5499 /* Some packets have received acks. If they all have, we can clear
5500 * the transmit queue.
5503 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5504 if (p->header.seq < call->tfirst
5505 && (p->flags & RX_PKTFLAG_ACKED)) {
5507 p->flags &= ~RX_PKTFLAG_TQ;
5508 #ifdef RXDEBUG_PACKET
5516 call->flags |= RX_CALL_TQ_CLEARME;
5518 #endif /* RX_ENABLE_LOCKS */
5519 /* Don't bother doing retransmits if the TQ is cleared. */
5520 if (call->flags & RX_CALL_TQ_CLEARME) {
5521 rxi_ClearTransmitQueue(call, 1);
5523 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5526 /* Always post a resend event, if there is anything in the
5527 * queue, and resend is possible. There should be at least
5528 * one unacknowledged packet in the queue ... otherwise none
5529 * of these packets should be on the queue in the first place.
5531 if (call->resendEvent) {
5532 /* Cancel the existing event and post a new one */
5533 rxevent_Cancel(call->resendEvent, call,
5534 RX_CALL_REFCOUNT_RESEND);
5537 /* The retry time is the retry time on the first unacknowledged
5538 * packet inside the current window */
5540 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5541 /* Don't set timers for packets outside the window */
5542 if (p->header.seq >= call->tfirst + call->twind) {
5546 if (!(p->flags & RX_PKTFLAG_ACKED)
5547 && !clock_IsZero(&p->retryTime)) {
5549 retryTime = p->retryTime;
5554 /* Post a new event to re-run rxi_Start when retries may be needed */
5555 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5556 #ifdef RX_ENABLE_LOCKS
5557 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5559 rxevent_PostNow2(&retryTime, &usenow,
5561 (void *)call, 0, istack);
5562 #else /* RX_ENABLE_LOCKS */
5564 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5565 (void *)call, 0, istack);
5566 #endif /* RX_ENABLE_LOCKS */
5569 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5570 } while (call->flags & RX_CALL_NEED_START);
5572 * TQ references no longer protected by this flag; they must remain
5573 * protected by the global lock.
5575 call->flags &= ~RX_CALL_TQ_BUSY;
5576 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5577 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5578 #ifdef RX_ENABLE_LOCKS
5579 osirx_AssertMine(&call->lock, "rxi_Start end");
5580 CV_BROADCAST(&call->cv_tq);
5581 #else /* RX_ENABLE_LOCKS */
5582 osi_rxWakeup(&call->tq);
5583 #endif /* RX_ENABLE_LOCKS */
5586 call->flags |= RX_CALL_NEED_START;
5588 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5590 if (call->resendEvent) {
5591 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5596 /* Also adjusts the keep alive parameters for the call, to reflect
5597 * that we have just sent a packet (so keep alives aren't sent
5600 rxi_Send(struct rx_call *call, struct rx_packet *p,
5603 struct rx_connection *conn = call->conn;
5605 /* Stamp each packet with the user supplied status */
5606 p->header.userStatus = call->localStatus;
5608 /* Allow the security object controlling this call's security to
5609 * make any last-minute changes to the packet */
5610 RXS_SendPacket(conn->securityObject, call, p);
5612 /* Since we're about to send SOME sort of packet to the peer, it's
5613 * safe to nuke any scheduled end-of-packets ack */
5614 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5616 /* Actually send the packet, filling in more connection-specific fields */
5617 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5618 MUTEX_EXIT(&call->lock);
5619 rxi_SendPacket(call, conn, p, istack);
5620 MUTEX_ENTER(&call->lock);
5621 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5623 /* Update last send time for this call (for keep-alive
5624 * processing), and for the connection (so that we can discover
5625 * idle connections) */
5626 conn->lastSendTime = call->lastSendTime = clock_Sec();
5627 /* Don't count keepalives here, so idleness can be tracked. */
5628 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5629 call->lastSendData = call->lastSendTime;
5633 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5634 * that things are fine. Also called periodically to guarantee that nothing
5635 * falls through the cracks (e.g. (error + dally) connections have keepalive
5636 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5638 * haveCTLock Set if calling from rxi_ReapConnections
5640 #ifdef RX_ENABLE_LOCKS
5642 rxi_CheckCall(struct rx_call *call, int haveCTLock)
5643 #else /* RX_ENABLE_LOCKS */
5645 rxi_CheckCall(struct rx_call *call)
5646 #endif /* RX_ENABLE_LOCKS */
5648 struct rx_connection *conn = call->conn;
5650 afs_uint32 deadTime;
5652 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5653 if (call->flags & RX_CALL_TQ_BUSY) {
5654 /* Call is active and will be reset by rxi_Start if it's
5655 * in an error state.
5660 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5662 (((afs_uint32) conn->secondsUntilDead << 10) +
5663 ((afs_uint32) conn->peer->rtt >> 3) +
5664 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5666 /* These are computed to the second (+- 1 second). But that's
5667 * good enough for these values, which should be a significant
5668 * number of seconds. */
5669 if (now > (call->lastReceiveTime + deadTime)) {
5670 if (call->state == RX_STATE_ACTIVE) {
5672 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5674 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5675 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5676 ip_stack_t *ipst = ns->netstack_ip;
5678 ire = ire_cache_lookup(call->conn->peer->host
5679 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5681 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5683 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5690 if (ire && ire->ire_max_frag > 0)
5691 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5692 #if defined(GLOBAL_NETSTACKID)
5696 #endif /* ADAPT_PMTU */
5697 rxi_CallError(call, RX_CALL_DEAD);
5700 #ifdef RX_ENABLE_LOCKS
5701 /* Cancel pending events */
5702 rxevent_Cancel(call->delayedAckEvent, call,
5703 RX_CALL_REFCOUNT_DELAY);
5704 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5705 rxevent_Cancel(call->keepAliveEvent, call,
5706 RX_CALL_REFCOUNT_ALIVE);
5707 if (call->refCount == 0) {
5708 rxi_FreeCall(call, haveCTLock);
5712 #else /* RX_ENABLE_LOCKS */
5715 #endif /* RX_ENABLE_LOCKS */
5717 /* Non-active calls are destroyed if they are not responding
5718 * to pings; active calls are simply flagged in error, so the
5719 * attached process can die reasonably gracefully. */
5721 /* see if we have a non-activity timeout */
5722 if (call->startWait && conn->idleDeadTime
5723 && ((call->startWait + conn->idleDeadTime) < now)) {
5724 if (call->state == RX_STATE_ACTIVE) {
5725 rxi_CallError(call, RX_CALL_TIMEOUT);
5729 if (call->lastSendData && conn->idleDeadTime && (conn->idleDeadErr != 0)
5730 && ((call->lastSendData + conn->idleDeadTime) < now)) {
5731 if (call->state == RX_STATE_ACTIVE) {
5732 rxi_CallError(call, conn->idleDeadErr);
5736 /* see if we have a hard timeout */
5737 if (conn->hardDeadTime
5738 && (now > (conn->hardDeadTime + call->startTime.sec))) {
5739 if (call->state == RX_STATE_ACTIVE)
5740 rxi_CallError(call, RX_CALL_TIMEOUT);
5747 /* When a call is in progress, this routine is called occasionally to
5748 * make sure that some traffic has arrived (or been sent to) the peer.
5749 * If nothing has arrived in a reasonable amount of time, the call is
5750 * declared dead; if nothing has been sent for a while, we send a
5751 * keep-alive packet (if we're actually trying to keep the call alive)
5754 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5756 struct rx_call *call = arg1;
5757 struct rx_connection *conn;
5760 MUTEX_ENTER(&call->lock);
5761 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5762 if (event == call->keepAliveEvent)
5763 call->keepAliveEvent = NULL;
5766 #ifdef RX_ENABLE_LOCKS
5767 if (rxi_CheckCall(call, 0)) {
5768 MUTEX_EXIT(&call->lock);
5771 #else /* RX_ENABLE_LOCKS */
5772 if (rxi_CheckCall(call))
5774 #endif /* RX_ENABLE_LOCKS */
5776 /* Don't try to keep alive dallying calls */
5777 if (call->state == RX_STATE_DALLY) {
5778 MUTEX_EXIT(&call->lock);
5783 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
5784 /* Don't try to send keepalives if there is unacknowledged data */
5785 /* the rexmit code should be good enough, this little hack
5786 * doesn't quite work XXX */
5787 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5789 rxi_ScheduleKeepAliveEvent(call);
5790 MUTEX_EXIT(&call->lock);
5795 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
5797 if (!call->keepAliveEvent) {
5798 struct clock when, now;
5799 clock_GetTime(&now);
5801 when.sec += call->conn->secondsUntilPing;
5802 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5803 call->keepAliveEvent =
5804 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5808 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5810 rxi_KeepAliveOn(struct rx_call *call)
5812 /* Pretend last packet received was received now--i.e. if another
5813 * packet isn't received within the keep alive time, then the call
5814 * will die; Initialize last send time to the current time--even
5815 * if a packet hasn't been sent yet. This will guarantee that a
5816 * keep-alive is sent within the ping time */
5817 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5818 rxi_ScheduleKeepAliveEvent(call);
5821 /* This routine is called to send connection abort messages
5822 * that have been delayed to throttle looping clients. */
5824 rxi_SendDelayedConnAbort(struct rxevent *event,
5825 void *arg1, void *unused)
5827 struct rx_connection *conn = arg1;
5830 struct rx_packet *packet;
5832 MUTEX_ENTER(&conn->conn_data_lock);
5833 conn->delayedAbortEvent = NULL;
5834 error = htonl(conn->error);
5836 MUTEX_EXIT(&conn->conn_data_lock);
5837 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5840 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5841 RX_PACKET_TYPE_ABORT, (char *)&error,
5843 rxi_FreePacket(packet);
5847 /* This routine is called to send call abort messages
5848 * that have been delayed to throttle looping clients. */
5850 rxi_SendDelayedCallAbort(struct rxevent *event,
5851 void *arg1, void *dummy)
5853 struct rx_call *call = arg1;
5856 struct rx_packet *packet;
5858 MUTEX_ENTER(&call->lock);
5859 call->delayedAbortEvent = NULL;
5860 error = htonl(call->error);
5862 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5865 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5866 (char *)&error, sizeof(error), 0);
5867 rxi_FreePacket(packet);
5869 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5870 MUTEX_EXIT(&call->lock);
5873 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5874 * seconds) to ask the client to authenticate itself. The routine
5875 * issues a challenge to the client, which is obtained from the
5876 * security object associated with the connection */
5878 rxi_ChallengeEvent(struct rxevent *event,
5879 void *arg0, void *arg1, int tries)
5881 struct rx_connection *conn = arg0;
5883 conn->challengeEvent = NULL;
5884 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5885 struct rx_packet *packet;
5886 struct clock when, now;
5889 /* We've failed to authenticate for too long.
5890 * Reset any calls waiting for authentication;
5891 * they are all in RX_STATE_PRECALL.
5895 MUTEX_ENTER(&conn->conn_call_lock);
5896 for (i = 0; i < RX_MAXCALLS; i++) {
5897 struct rx_call *call = conn->call[i];
5899 MUTEX_ENTER(&call->lock);
5900 if (call->state == RX_STATE_PRECALL) {
5901 rxi_CallError(call, RX_CALL_DEAD);
5902 rxi_SendCallAbort(call, NULL, 0, 0);
5904 MUTEX_EXIT(&call->lock);
5907 MUTEX_EXIT(&conn->conn_call_lock);
5911 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5913 /* If there's no packet available, do this later. */
5914 RXS_GetChallenge(conn->securityObject, conn, packet);
5915 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5916 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5917 rxi_FreePacket(packet);
5919 clock_GetTime(&now);
5921 when.sec += RX_CHALLENGE_TIMEOUT;
5922 conn->challengeEvent =
5923 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5928 /* Call this routine to start requesting the client to authenticate
5929 * itself. This will continue until authentication is established,
5930 * the call times out, or an invalid response is returned. The
5931 * security object associated with the connection is asked to create
5932 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5933 * defined earlier. */
5935 rxi_ChallengeOn(struct rx_connection *conn)
5937 if (!conn->challengeEvent) {
5938 RXS_CreateChallenge(conn->securityObject, conn);
5939 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5944 /* Compute round trip time of the packet provided, in *rttp.
5947 /* rxi_ComputeRoundTripTime is called with peer locked. */
5948 /* sentp and/or peer may be null */
5950 rxi_ComputeRoundTripTime(struct rx_packet *p,
5951 struct clock *sentp,
5952 struct rx_peer *peer)
5954 struct clock thisRtt, *rttp = &thisRtt;
5958 clock_GetTime(rttp);
5960 if (clock_Lt(rttp, sentp)) {
5962 return; /* somebody set the clock back, don't count this time. */
5964 clock_Sub(rttp, sentp);
5965 if (rx_stats_active) {
5966 MUTEX_ENTER(&rx_stats_mutex);
5967 if (clock_Lt(rttp, &rx_stats.minRtt))
5968 rx_stats.minRtt = *rttp;
5969 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
5970 if (rttp->sec > 60) {
5971 MUTEX_EXIT(&rx_stats_mutex);
5972 return; /* somebody set the clock ahead */
5974 rx_stats.maxRtt = *rttp;
5976 clock_Add(&rx_stats.totalRtt, rttp);
5977 rx_stats.nRttSamples++;
5978 MUTEX_EXIT(&rx_stats_mutex);
5981 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
5983 /* Apply VanJacobson round-trip estimations */
5988 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
5989 * srtt is stored as fixed point with 3 bits after the binary
5990 * point (i.e., scaled by 8). The following magic is
5991 * equivalent to the smoothing algorithm in rfc793 with an
5992 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
5993 * srtt*8 = srtt*8 + rtt - srtt
5994 * srtt = srtt + rtt/8 - srtt/8
5997 delta = MSEC(rttp) - (peer->rtt >> 3);
6001 * We accumulate a smoothed rtt variance (actually, a smoothed
6002 * mean difference), then set the retransmit timer to smoothed
6003 * rtt + 4 times the smoothed variance (was 2x in van's original
6004 * paper, but 4x works better for me, and apparently for him as
6006 * rttvar is stored as
6007 * fixed point with 2 bits after the binary point (scaled by
6008 * 4). The following is equivalent to rfc793 smoothing with
6009 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
6010 * replaces rfc793's wired-in beta.
6011 * dev*4 = dev*4 + (|actual - expected| - dev)
6017 delta -= (peer->rtt_dev >> 2);
6018 peer->rtt_dev += delta;
6020 /* I don't have a stored RTT so I start with this value. Since I'm
6021 * probably just starting a call, and will be pushing more data down
6022 * this, I expect congestion to increase rapidly. So I fudge a
6023 * little, and I set deviance to half the rtt. In practice,
6024 * deviance tends to approach something a little less than
6025 * half the smoothed rtt. */
6026 peer->rtt = (MSEC(rttp) << 3) + 8;
6027 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6029 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
6030 * the other of these connections is usually in a user process, and can
6031 * be switched and/or swapped out. So on fast, reliable networks, the
6032 * timeout would otherwise be too short.
6034 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
6035 clock_Zero(&(peer->timeout));
6036 clock_Addmsec(&(peer->timeout), rtt_timeout);
6038 dpf(("rxi_ComputeRoundTripTime(rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%0.3d sec)\n", MSEC(rttp), peer->rtt >> 3, peer->rtt_dev >> 2, (peer->timeout.sec), (peer->timeout.usec)));
6042 /* Find all server connections that have not been active for a long time, and
6045 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6047 struct clock now, when;
6048 clock_GetTime(&now);
6050 /* Find server connection structures that haven't been used for
6051 * greater than rx_idleConnectionTime */
6053 struct rx_connection **conn_ptr, **conn_end;
6054 int i, havecalls = 0;
6055 MUTEX_ENTER(&rx_connHashTable_lock);
6056 for (conn_ptr = &rx_connHashTable[0], conn_end =
6057 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6059 struct rx_connection *conn, *next;
6060 struct rx_call *call;
6064 for (conn = *conn_ptr; conn; conn = next) {
6065 /* XXX -- Shouldn't the connection be locked? */
6068 for (i = 0; i < RX_MAXCALLS; i++) {
6069 call = conn->call[i];
6073 code = MUTEX_TRYENTER(&call->lock);
6076 #ifdef RX_ENABLE_LOCKS
6077 result = rxi_CheckCall(call, 1);
6078 #else /* RX_ENABLE_LOCKS */
6079 result = rxi_CheckCall(call);
6080 #endif /* RX_ENABLE_LOCKS */
6081 MUTEX_EXIT(&call->lock);
6083 /* If CheckCall freed the call, it might
6084 * have destroyed the connection as well,
6085 * which screws up the linked lists.
6091 if (conn->type == RX_SERVER_CONNECTION) {
6092 /* This only actually destroys the connection if
6093 * there are no outstanding calls */
6094 MUTEX_ENTER(&conn->conn_data_lock);
6095 if (!havecalls && !conn->refCount
6096 && ((conn->lastSendTime + rx_idleConnectionTime) <
6098 conn->refCount++; /* it will be decr in rx_DestroyConn */
6099 MUTEX_EXIT(&conn->conn_data_lock);
6100 #ifdef RX_ENABLE_LOCKS
6101 rxi_DestroyConnectionNoLock(conn);
6102 #else /* RX_ENABLE_LOCKS */
6103 rxi_DestroyConnection(conn);
6104 #endif /* RX_ENABLE_LOCKS */
6106 #ifdef RX_ENABLE_LOCKS
6108 MUTEX_EXIT(&conn->conn_data_lock);
6110 #endif /* RX_ENABLE_LOCKS */
6114 #ifdef RX_ENABLE_LOCKS
6115 while (rx_connCleanup_list) {
6116 struct rx_connection *conn;
6117 conn = rx_connCleanup_list;
6118 rx_connCleanup_list = rx_connCleanup_list->next;
6119 MUTEX_EXIT(&rx_connHashTable_lock);
6120 rxi_CleanupConnection(conn);
6121 MUTEX_ENTER(&rx_connHashTable_lock);
6123 MUTEX_EXIT(&rx_connHashTable_lock);
6124 #endif /* RX_ENABLE_LOCKS */
6127 /* Find any peer structures that haven't been used (haven't had an
6128 * associated connection) for greater than rx_idlePeerTime */
6130 struct rx_peer **peer_ptr, **peer_end;
6132 MUTEX_ENTER(&rx_rpc_stats);
6133 MUTEX_ENTER(&rx_peerHashTable_lock);
6134 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6135 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6137 struct rx_peer *peer, *next, *prev;
6138 for (prev = peer = *peer_ptr; peer; peer = next) {
6140 code = MUTEX_TRYENTER(&peer->peer_lock);
6141 if ((code) && (peer->refCount == 0)
6142 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6143 rx_interface_stat_p rpc_stat, nrpc_stat;
6145 MUTEX_EXIT(&peer->peer_lock);
6146 MUTEX_DESTROY(&peer->peer_lock);
6148 (&peer->rpcStats, rpc_stat, nrpc_stat,
6149 rx_interface_stat)) {
6150 unsigned int num_funcs;
6153 queue_Remove(&rpc_stat->queue_header);
6154 queue_Remove(&rpc_stat->all_peers);
6155 num_funcs = rpc_stat->stats[0].func_total;
6157 sizeof(rx_interface_stat_t) +
6158 rpc_stat->stats[0].func_total *
6159 sizeof(rx_function_entry_v1_t);
6161 rxi_Free(rpc_stat, space);
6162 rxi_rpc_peer_stat_cnt -= num_funcs;
6165 if (rx_stats_active)
6166 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6167 if (peer == *peer_ptr) {
6174 MUTEX_EXIT(&peer->peer_lock);
6180 MUTEX_EXIT(&rx_peerHashTable_lock);
6181 MUTEX_EXIT(&rx_rpc_stats);
6184 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6185 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6186 * GC, just below. Really, we shouldn't have to keep moving packets from
6187 * one place to another, but instead ought to always know if we can
6188 * afford to hold onto a packet in its particular use. */
6189 MUTEX_ENTER(&rx_freePktQ_lock);
6190 if (rx_waitingForPackets) {
6191 rx_waitingForPackets = 0;
6192 #ifdef RX_ENABLE_LOCKS
6193 CV_BROADCAST(&rx_waitingForPackets_cv);
6195 osi_rxWakeup(&rx_waitingForPackets);
6198 MUTEX_EXIT(&rx_freePktQ_lock);
6201 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6202 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6206 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6207 * rx.h is sort of strange this is better. This is called with a security
6208 * object before it is discarded. Each connection using a security object has
6209 * its own refcount to the object so it won't actually be freed until the last
6210 * connection is destroyed.
6212 * This is the only rxs module call. A hold could also be written but no one
6216 rxs_Release(struct rx_securityClass *aobj)
6218 return RXS_Close(aobj);
6222 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6223 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6224 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6225 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6227 /* Adjust our estimate of the transmission rate to this peer, given
6228 * that the packet p was just acked. We can adjust peer->timeout and
6229 * call->twind. Pragmatically, this is called
6230 * only with packets of maximal length.
6231 * Called with peer and call locked.
6235 rxi_ComputeRate(struct rx_peer *peer, struct rx_call *call,
6236 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6238 afs_int32 xferSize, xferMs;
6242 /* Count down packets */
6243 if (peer->rateFlag > 0)
6245 /* Do nothing until we're enabled */
6246 if (peer->rateFlag != 0)
6251 /* Count only when the ack seems legitimate */
6252 switch (ackReason) {
6253 case RX_ACK_REQUESTED:
6255 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6259 case RX_ACK_PING_RESPONSE:
6260 if (p) /* want the response to ping-request, not data send */
6262 clock_GetTime(&newTO);
6263 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6264 clock_Sub(&newTO, &call->pingRequestTime);
6265 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6269 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6276 dpf(("CONG peer %lx/%u: sample (%s) size %ld, %ld ms (to %lu.%06lu, rtt %u, ps %u)", ntohl(peer->host), ntohs(peer->port), (ackReason == RX_ACK_REQUESTED ? "dataack" : "pingack"), xferSize, xferMs, peer->timeout.sec, peer->timeout.usec, peer->smRtt, peer->ifMTU));
6278 /* Track only packets that are big enough. */
6279 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6283 /* absorb RTT data (in milliseconds) for these big packets */
6284 if (peer->smRtt == 0) {
6285 peer->smRtt = xferMs;
6287 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6292 if (peer->countDown) {
6296 peer->countDown = 10; /* recalculate only every so often */
6298 /* In practice, we can measure only the RTT for full packets,
6299 * because of the way Rx acks the data that it receives. (If it's
6300 * smaller than a full packet, it often gets implicitly acked
6301 * either by the call response (from a server) or by the next call
6302 * (from a client), and either case confuses transmission times
6303 * with processing times.) Therefore, replace the above
6304 * more-sophisticated processing with a simpler version, where the
6305 * smoothed RTT is kept for full-size packets, and the time to
6306 * transmit a windowful of full-size packets is simply RTT *
6307 * windowSize. Again, we take two steps:
6308 - ensure the timeout is large enough for a single packet's RTT;
6309 - ensure that the window is small enough to fit in the desired timeout.*/
6311 /* First, the timeout check. */
6312 minTime = peer->smRtt;
6313 /* Get a reasonable estimate for a timeout period */
6315 newTO.sec = minTime / 1000;
6316 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6318 /* Increase the timeout period so that we can always do at least
6319 * one packet exchange */
6320 if (clock_Gt(&newTO, &peer->timeout)) {
6322 dpf(("CONG peer %lx/%u: timeout %lu.%06lu ==> %lu.%06lu (rtt %u, ps %u)", ntohl(peer->host), ntohs(peer->port), peer->timeout.sec, peer->timeout.usec, newTO.sec, newTO.usec, peer->smRtt, peer->packetSize));
6324 peer->timeout = newTO;
6327 /* Now, get an estimate for the transmit window size. */
6328 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6329 /* Now, convert to the number of full packets that could fit in a
6330 * reasonable fraction of that interval */
6331 minTime /= (peer->smRtt << 1);
6332 xferSize = minTime; /* (make a copy) */
6334 /* Now clamp the size to reasonable bounds. */
6337 else if (minTime > rx_Window)
6338 minTime = rx_Window;
6339 /* if (minTime != peer->maxWindow) {
6340 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6341 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6342 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6344 peer->maxWindow = minTime;
6345 elide... call->twind = minTime;
6349 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6350 * Discern this by calculating the timeout necessary for rx_Window
6352 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6353 /* calculate estimate for transmission interval in milliseconds */
6354 minTime = rx_Window * peer->smRtt;
6355 if (minTime < 1000) {
6356 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
6357 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6358 peer->timeout.usec, peer->smRtt, peer->packetSize));
6360 newTO.sec = 0; /* cut back on timeout by half a second */
6361 newTO.usec = 500000;
6362 clock_Sub(&peer->timeout, &newTO);
6367 } /* end of rxi_ComputeRate */
6368 #endif /* ADAPT_WINDOW */
6376 #define TRACE_OPTION_RX_DEBUG 16
6384 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6385 0, KEY_QUERY_VALUE, &parmKey);
6386 if (code != ERROR_SUCCESS)
6389 dummyLen = sizeof(TraceOption);
6390 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6391 (BYTE *) &TraceOption, &dummyLen);
6392 if (code == ERROR_SUCCESS) {
6393 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
6395 RegCloseKey (parmKey);
6396 #endif /* AFS_NT40_ENV */
6401 rx_DebugOnOff(int on)
6405 rxdebug_active = on;
6411 rx_StatsOnOff(int on)
6414 rx_stats_active = on;
6419 /* Don't call this debugging routine directly; use dpf */
6421 rxi_DebugPrint(char *format, ...)
6430 va_start(ap, format);
6432 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6435 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6437 if (msg[len-1] != '\n') {
6441 OutputDebugString(msg);
6448 va_start(ap, format);
6450 clock_GetTime(&now);
6451 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
6452 (unsigned int)now.usec / 1000);
6453 vfprintf(rx_Log, format, ap);
6462 * This function is used to process the rx_stats structure that is local
6463 * to a process as well as an rx_stats structure received from a remote
6464 * process (via rxdebug). Therefore, it needs to do minimal version
6468 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6469 afs_int32 freePackets, char version)
6474 if (size != sizeof(struct rx_statistics)) {
6476 "Unexpected size of stats structure: was %d, expected %lud\n",
6477 size, sizeof(struct rx_statistics));
6480 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6483 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6484 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
6485 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6486 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6487 s->specialPktAllocFailures);
6489 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
6490 s->receivePktAllocFailures, s->sendPktAllocFailures,
6491 s->specialPktAllocFailures);
6495 " greedy %d, " "bogusReads %d (last from host %x), "
6496 "noPackets %d, " "noBuffers %d, " "selects %d, "
6497 "sendSelects %d\n", s->socketGreedy, s->bogusPacketOnRead,
6498 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6499 s->selects, s->sendSelects);
6501 fprintf(file, " packets read: ");
6502 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6503 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsRead[i]);
6505 fprintf(file, "\n");
6508 " other read counters: data %d, " "ack %d, " "dup %d "
6509 "spurious %d " "dally %d\n", s->dataPacketsRead,
6510 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6511 s->ignorePacketDally);
6513 fprintf(file, " packets sent: ");
6514 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6515 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsSent[i]);
6517 fprintf(file, "\n");
6520 " other send counters: ack %d, " "data %d (not resends), "
6521 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6522 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6523 s->dataPacketsPushed, s->ignoreAckedPacket);
6526 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6527 s->netSendFailures, (int)s->fatalErrors);
6529 if (s->nRttSamples) {
6530 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6531 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6533 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6534 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6538 " %d server connections, " "%d client connections, "
6539 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6540 s->nServerConns, s->nClientConns, s->nPeerStructs,
6541 s->nCallStructs, s->nFreeCallStructs);
6543 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6544 fprintf(file, " %d clock updates\n", clock_nUpdates);
6547 fprintf(file, "ERROR: compiled without RXDEBUG\n");
6551 /* for backward compatibility */
6553 rx_PrintStats(FILE * file)
6555 MUTEX_ENTER(&rx_stats_mutex);
6556 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6558 MUTEX_EXIT(&rx_stats_mutex);
6562 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6564 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6565 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6566 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6569 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6570 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6571 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6574 " Packet size %d, " "max in packet skew %d, "
6575 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6576 (int)peer->outPacketSkew);
6580 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
6582 * This mutex protects the following static variables:
6586 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
6587 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
6589 #define LOCK_RX_DEBUG
6590 #define UNLOCK_RX_DEBUG
6591 #endif /* AFS_PTHREAD_ENV */
6595 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6596 u_char type, void *inputData, size_t inputLength,
6597 void *outputData, size_t outputLength)
6599 static afs_int32 counter = 100;
6600 time_t waitTime, waitCount, startTime;
6601 struct rx_header theader;
6604 struct timeval tv_now, tv_wake, tv_delta;
6605 struct sockaddr_in taddr, faddr;
6614 startTime = time(0);
6620 tp = &tbuffer[sizeof(struct rx_header)];
6621 taddr.sin_family = AF_INET;
6622 taddr.sin_port = remotePort;
6623 taddr.sin_addr.s_addr = remoteAddr;
6624 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6625 taddr.sin_len = sizeof(struct sockaddr_in);
6628 memset(&theader, 0, sizeof(theader));
6629 theader.epoch = htonl(999);
6631 theader.callNumber = htonl(counter);
6634 theader.type = type;
6635 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6636 theader.serviceId = 0;
6638 memcpy(tbuffer, &theader, sizeof(theader));
6639 memcpy(tp, inputData, inputLength);
6641 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6642 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6644 /* see if there's a packet available */
6645 gettimeofday(&tv_wake,0);
6646 tv_wake.tv_sec += waitTime;
6649 FD_SET(socket, &imask);
6650 tv_delta.tv_sec = tv_wake.tv_sec;
6651 tv_delta.tv_usec = tv_wake.tv_usec;
6652 gettimeofday(&tv_now, 0);
6654 if (tv_delta.tv_usec < tv_now.tv_usec) {
6656 tv_delta.tv_usec += 1000000;
6659 tv_delta.tv_usec -= tv_now.tv_usec;
6661 if (tv_delta.tv_sec < tv_now.tv_sec) {
6665 tv_delta.tv_sec -= tv_now.tv_sec;
6667 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6668 if (code == 1 && FD_ISSET(socket, &imask)) {
6669 /* now receive a packet */
6670 faddrLen = sizeof(struct sockaddr_in);
6672 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6673 (struct sockaddr *)&faddr, &faddrLen);
6676 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6677 if (counter == ntohl(theader.callNumber))
6685 /* see if we've timed out */
6693 code -= sizeof(struct rx_header);
6694 if (code > outputLength)
6695 code = outputLength;
6696 memcpy(outputData, tp, code);
6699 #endif /* RXDEBUG */
6702 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6703 afs_uint16 remotePort, struct rx_debugStats * stat,
6704 afs_uint32 * supportedValues)
6710 struct rx_debugIn in;
6711 afs_int32 *lp = (afs_int32 *) stat;
6713 *supportedValues = 0;
6714 in.type = htonl(RX_DEBUGI_GETSTATS);
6717 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6718 &in, sizeof(in), stat, sizeof(*stat));
6721 * If the call was successful, fixup the version and indicate
6722 * what contents of the stat structure are valid.
6723 * Also do net to host conversion of fields here.
6727 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6728 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6730 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6731 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6733 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6734 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6736 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6737 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6739 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6740 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6742 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6743 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6745 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6746 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6748 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6749 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6751 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6752 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6754 stat->nFreePackets = ntohl(stat->nFreePackets);
6755 stat->packetReclaims = ntohl(stat->packetReclaims);
6756 stat->callsExecuted = ntohl(stat->callsExecuted);
6757 stat->nWaiting = ntohl(stat->nWaiting);
6758 stat->idleThreads = ntohl(stat->idleThreads);
6759 stat->nWaited = ntohl(stat->nWaited);
6760 stat->nPackets = ntohl(stat->nPackets);
6767 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6768 afs_uint16 remotePort, struct rx_statistics * stat,
6769 afs_uint32 * supportedValues)
6775 struct rx_debugIn in;
6776 afs_int32 *lp = (afs_int32 *) stat;
6780 * supportedValues is currently unused, but added to allow future
6781 * versioning of this function.
6784 *supportedValues = 0;
6785 in.type = htonl(RX_DEBUGI_RXSTATS);
6787 memset(stat, 0, sizeof(*stat));
6789 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6790 &in, sizeof(in), stat, sizeof(*stat));
6795 * Do net to host conversion here
6798 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6807 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6808 afs_uint16 remotePort, size_t version_length,
6813 return MakeDebugCall(socket, remoteAddr, remotePort,
6814 RX_PACKET_TYPE_VERSION, a, 1, version,
6822 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6823 afs_uint16 remotePort, afs_int32 * nextConnection,
6824 int allConnections, afs_uint32 debugSupportedValues,
6825 struct rx_debugConn * conn,
6826 afs_uint32 * supportedValues)
6832 struct rx_debugIn in;
6836 * supportedValues is currently unused, but added to allow future
6837 * versioning of this function.
6840 *supportedValues = 0;
6841 if (allConnections) {
6842 in.type = htonl(RX_DEBUGI_GETALLCONN);
6844 in.type = htonl(RX_DEBUGI_GETCONN);
6846 in.index = htonl(*nextConnection);
6847 memset(conn, 0, sizeof(*conn));
6849 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6850 &in, sizeof(in), conn, sizeof(*conn));
6853 *nextConnection += 1;
6856 * Convert old connection format to new structure.
6859 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6860 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6861 #define MOVEvL(a) (conn->a = vL->a)
6863 /* any old or unrecognized version... */
6864 for (i = 0; i < RX_MAXCALLS; i++) {
6865 MOVEvL(callState[i]);
6866 MOVEvL(callMode[i]);
6867 MOVEvL(callFlags[i]);
6868 MOVEvL(callOther[i]);
6870 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6871 MOVEvL(secStats.type);
6872 MOVEvL(secStats.level);
6873 MOVEvL(secStats.flags);
6874 MOVEvL(secStats.expires);
6875 MOVEvL(secStats.packetsReceived);
6876 MOVEvL(secStats.packetsSent);
6877 MOVEvL(secStats.bytesReceived);
6878 MOVEvL(secStats.bytesSent);
6883 * Do net to host conversion here
6885 * I don't convert host or port since we are most likely
6886 * going to want these in NBO.
6888 conn->cid = ntohl(conn->cid);
6889 conn->serial = ntohl(conn->serial);
6890 for (i = 0; i < RX_MAXCALLS; i++) {
6891 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6893 conn->error = ntohl(conn->error);
6894 conn->secStats.flags = ntohl(conn->secStats.flags);
6895 conn->secStats.expires = ntohl(conn->secStats.expires);
6896 conn->secStats.packetsReceived =
6897 ntohl(conn->secStats.packetsReceived);
6898 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6899 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6900 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6901 conn->epoch = ntohl(conn->epoch);
6902 conn->natMTU = ntohl(conn->natMTU);
6909 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6910 afs_uint16 remotePort, afs_int32 * nextPeer,
6911 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6912 afs_uint32 * supportedValues)
6918 struct rx_debugIn in;
6921 * supportedValues is currently unused, but added to allow future
6922 * versioning of this function.
6925 *supportedValues = 0;
6926 in.type = htonl(RX_DEBUGI_GETPEER);
6927 in.index = htonl(*nextPeer);
6928 memset(peer, 0, sizeof(*peer));
6930 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6931 &in, sizeof(in), peer, sizeof(*peer));
6937 * Do net to host conversion here
6939 * I don't convert host or port since we are most likely
6940 * going to want these in NBO.
6942 peer->ifMTU = ntohs(peer->ifMTU);
6943 peer->idleWhen = ntohl(peer->idleWhen);
6944 peer->refCount = ntohs(peer->refCount);
6945 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6946 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6947 peer->rtt = ntohl(peer->rtt);
6948 peer->rtt_dev = ntohl(peer->rtt_dev);
6949 peer->timeout.sec = ntohl(peer->timeout.sec);
6950 peer->timeout.usec = ntohl(peer->timeout.usec);
6951 peer->nSent = ntohl(peer->nSent);
6952 peer->reSends = ntohl(peer->reSends);
6953 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6954 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6955 peer->rateFlag = ntohl(peer->rateFlag);
6956 peer->natMTU = ntohs(peer->natMTU);
6957 peer->maxMTU = ntohs(peer->maxMTU);
6958 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6959 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
6960 peer->MTU = ntohs(peer->MTU);
6961 peer->cwind = ntohs(peer->cwind);
6962 peer->nDgramPackets = ntohs(peer->nDgramPackets);
6963 peer->congestSeq = ntohs(peer->congestSeq);
6964 peer->bytesSent.high = ntohl(peer->bytesSent.high);
6965 peer->bytesSent.low = ntohl(peer->bytesSent.low);
6966 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
6967 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
6976 struct rx_serverQueueEntry *np;
6979 struct rx_call *call;
6980 struct rx_serverQueueEntry *sq;
6984 if (rxinit_status == 1) {
6986 return; /* Already shutdown. */
6990 #ifndef AFS_PTHREAD_ENV
6991 FD_ZERO(&rx_selectMask);
6992 #endif /* AFS_PTHREAD_ENV */
6993 rxi_dataQuota = RX_MAX_QUOTA;
6994 #ifndef AFS_PTHREAD_ENV
6996 #endif /* AFS_PTHREAD_ENV */
6999 #ifndef AFS_PTHREAD_ENV
7000 #ifndef AFS_USE_GETTIMEOFDAY
7002 #endif /* AFS_USE_GETTIMEOFDAY */
7003 #endif /* AFS_PTHREAD_ENV */
7005 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7006 call = queue_First(&rx_freeCallQueue, rx_call);
7008 rxi_Free(call, sizeof(struct rx_call));
7011 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7012 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7018 struct rx_peer **peer_ptr, **peer_end;
7019 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7020 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7022 struct rx_peer *peer, *next;
7023 for (peer = *peer_ptr; peer; peer = next) {
7024 rx_interface_stat_p rpc_stat, nrpc_stat;
7027 (&peer->rpcStats, rpc_stat, nrpc_stat,
7028 rx_interface_stat)) {
7029 unsigned int num_funcs;
7032 queue_Remove(&rpc_stat->queue_header);
7033 queue_Remove(&rpc_stat->all_peers);
7034 num_funcs = rpc_stat->stats[0].func_total;
7036 sizeof(rx_interface_stat_t) +
7037 rpc_stat->stats[0].func_total *
7038 sizeof(rx_function_entry_v1_t);
7040 rxi_Free(rpc_stat, space);
7041 MUTEX_ENTER(&rx_rpc_stats);
7042 rxi_rpc_peer_stat_cnt -= num_funcs;
7043 MUTEX_EXIT(&rx_rpc_stats);
7047 if (rx_stats_active)
7048 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
7052 for (i = 0; i < RX_MAX_SERVICES; i++) {
7054 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7056 for (i = 0; i < rx_hashTableSize; i++) {
7057 struct rx_connection *tc, *ntc;
7058 MUTEX_ENTER(&rx_connHashTable_lock);
7059 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7061 for (j = 0; j < RX_MAXCALLS; j++) {
7063 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7066 rxi_Free(tc, sizeof(*tc));
7068 MUTEX_EXIT(&rx_connHashTable_lock);
7071 MUTEX_ENTER(&freeSQEList_lock);
7073 while ((np = rx_FreeSQEList)) {
7074 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7075 MUTEX_DESTROY(&np->lock);
7076 rxi_Free(np, sizeof(*np));
7079 MUTEX_EXIT(&freeSQEList_lock);
7080 MUTEX_DESTROY(&freeSQEList_lock);
7081 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7082 MUTEX_DESTROY(&rx_connHashTable_lock);
7083 MUTEX_DESTROY(&rx_peerHashTable_lock);
7084 MUTEX_DESTROY(&rx_serverPool_lock);
7086 osi_Free(rx_connHashTable,
7087 rx_hashTableSize * sizeof(struct rx_connection *));
7088 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7090 UNPIN(rx_connHashTable,
7091 rx_hashTableSize * sizeof(struct rx_connection *));
7092 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7094 rxi_FreeAllPackets();
7096 MUTEX_ENTER(&rx_quota_mutex);
7097 rxi_dataQuota = RX_MAX_QUOTA;
7098 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7099 MUTEX_EXIT(&rx_quota_mutex);
7104 #ifdef RX_ENABLE_LOCKS
7106 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7108 if (!MUTEX_ISMINE(lockaddr))
7109 osi_Panic("Lock not held: %s", msg);
7111 #endif /* RX_ENABLE_LOCKS */
7116 * Routines to implement connection specific data.
7120 rx_KeyCreate(rx_destructor_t rtn)
7123 MUTEX_ENTER(&rxi_keyCreate_lock);
7124 key = rxi_keyCreate_counter++;
7125 rxi_keyCreate_destructor = (rx_destructor_t *)
7126 realloc((void *)rxi_keyCreate_destructor,
7127 (key + 1) * sizeof(rx_destructor_t));
7128 rxi_keyCreate_destructor[key] = rtn;
7129 MUTEX_EXIT(&rxi_keyCreate_lock);
7134 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7137 MUTEX_ENTER(&conn->conn_data_lock);
7138 if (!conn->specific) {
7139 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7140 for (i = 0; i < key; i++)
7141 conn->specific[i] = NULL;
7142 conn->nSpecific = key + 1;
7143 conn->specific[key] = ptr;
7144 } else if (key >= conn->nSpecific) {
7145 conn->specific = (void **)
7146 realloc(conn->specific, (key + 1) * sizeof(void *));
7147 for (i = conn->nSpecific; i < key; i++)
7148 conn->specific[i] = NULL;
7149 conn->nSpecific = key + 1;
7150 conn->specific[key] = ptr;
7152 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7153 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7154 conn->specific[key] = ptr;
7156 MUTEX_EXIT(&conn->conn_data_lock);
7160 rx_GetSpecific(struct rx_connection *conn, int key)
7163 MUTEX_ENTER(&conn->conn_data_lock);
7164 if (key >= conn->nSpecific)
7167 ptr = conn->specific[key];
7168 MUTEX_EXIT(&conn->conn_data_lock);
7172 #endif /* !KERNEL */
7175 * processStats is a queue used to store the statistics for the local
7176 * process. Its contents are similar to the contents of the rpcStats
7177 * queue on a rx_peer structure, but the actual data stored within
7178 * this queue contains totals across the lifetime of the process (assuming
7179 * the stats have not been reset) - unlike the per peer structures
7180 * which can come and go based upon the peer lifetime.
7183 static struct rx_queue processStats = { &processStats, &processStats };
7186 * peerStats is a queue used to store the statistics for all peer structs.
7187 * Its contents are the union of all the peer rpcStats queues.
7190 static struct rx_queue peerStats = { &peerStats, &peerStats };
7193 * rxi_monitor_processStats is used to turn process wide stat collection
7197 static int rxi_monitor_processStats = 0;
7200 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7203 static int rxi_monitor_peerStats = 0;
7206 * rxi_AddRpcStat - given all of the information for a particular rpc
7207 * call, create (if needed) and update the stat totals for the rpc.
7211 * IN stats - the queue of stats that will be updated with the new value
7213 * IN rxInterface - a unique number that identifies the rpc interface
7215 * IN currentFunc - the index of the function being invoked
7217 * IN totalFunc - the total number of functions in this interface
7219 * IN queueTime - the amount of time this function waited for a thread
7221 * IN execTime - the amount of time this function invocation took to execute
7223 * IN bytesSent - the number bytes sent by this invocation
7225 * IN bytesRcvd - the number bytes received by this invocation
7227 * IN isServer - if true, this invocation was made to a server
7229 * IN remoteHost - the ip address of the remote host
7231 * IN remotePort - the port of the remote host
7233 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7235 * INOUT counter - if a new stats structure is allocated, the counter will
7236 * be updated with the new number of allocated stat structures
7244 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7245 afs_uint32 currentFunc, afs_uint32 totalFunc,
7246 struct clock *queueTime, struct clock *execTime,
7247 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7248 afs_uint32 remoteHost, afs_uint32 remotePort,
7249 int addToPeerList, unsigned int *counter)
7252 rx_interface_stat_p rpc_stat, nrpc_stat;
7255 * See if there's already a structure for this interface
7258 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7259 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7260 && (rpc_stat->stats[0].remote_is_server == isServer))
7265 * Didn't find a match so allocate a new structure and add it to the
7269 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7270 || (rpc_stat->stats[0].interfaceId != rxInterface)
7271 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7276 sizeof(rx_interface_stat_t) +
7277 totalFunc * sizeof(rx_function_entry_v1_t);
7279 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7280 if (rpc_stat == NULL) {
7284 *counter += totalFunc;
7285 for (i = 0; i < totalFunc; i++) {
7286 rpc_stat->stats[i].remote_peer = remoteHost;
7287 rpc_stat->stats[i].remote_port = remotePort;
7288 rpc_stat->stats[i].remote_is_server = isServer;
7289 rpc_stat->stats[i].interfaceId = rxInterface;
7290 rpc_stat->stats[i].func_total = totalFunc;
7291 rpc_stat->stats[i].func_index = i;
7292 hzero(rpc_stat->stats[i].invocations);
7293 hzero(rpc_stat->stats[i].bytes_sent);
7294 hzero(rpc_stat->stats[i].bytes_rcvd);
7295 rpc_stat->stats[i].queue_time_sum.sec = 0;
7296 rpc_stat->stats[i].queue_time_sum.usec = 0;
7297 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7298 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7299 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7300 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7301 rpc_stat->stats[i].queue_time_max.sec = 0;
7302 rpc_stat->stats[i].queue_time_max.usec = 0;
7303 rpc_stat->stats[i].execution_time_sum.sec = 0;
7304 rpc_stat->stats[i].execution_time_sum.usec = 0;
7305 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7306 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7307 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7308 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7309 rpc_stat->stats[i].execution_time_max.sec = 0;
7310 rpc_stat->stats[i].execution_time_max.usec = 0;
7312 queue_Prepend(stats, rpc_stat);
7313 if (addToPeerList) {
7314 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7319 * Increment the stats for this function
7322 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7323 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7324 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7325 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7326 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7327 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7328 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7330 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7331 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7333 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7334 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7336 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7337 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7339 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7340 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7348 * rx_IncrementTimeAndCount - increment the times and count for a particular
7353 * IN peer - the peer who invoked the rpc
7355 * IN rxInterface - a unique number that identifies the rpc interface
7357 * IN currentFunc - the index of the function being invoked
7359 * IN totalFunc - the total number of functions in this interface
7361 * IN queueTime - the amount of time this function waited for a thread
7363 * IN execTime - the amount of time this function invocation took to execute
7365 * IN bytesSent - the number bytes sent by this invocation
7367 * IN bytesRcvd - the number bytes received by this invocation
7369 * IN isServer - if true, this invocation was made to a server
7377 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7378 afs_uint32 currentFunc, afs_uint32 totalFunc,
7379 struct clock *queueTime, struct clock *execTime,
7380 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7384 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7387 MUTEX_ENTER(&rx_rpc_stats);
7388 MUTEX_ENTER(&peer->peer_lock);
7390 if (rxi_monitor_peerStats) {
7391 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7392 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7393 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7396 if (rxi_monitor_processStats) {
7397 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7398 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7399 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7402 MUTEX_EXIT(&peer->peer_lock);
7403 MUTEX_EXIT(&rx_rpc_stats);
7408 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7412 * IN callerVersion - the rpc stat version of the caller.
7414 * IN count - the number of entries to marshall.
7416 * IN stats - pointer to stats to be marshalled.
7418 * OUT ptr - Where to store the marshalled data.
7425 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7426 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7432 * We only support the first version
7434 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7435 *(ptr++) = stats->remote_peer;
7436 *(ptr++) = stats->remote_port;
7437 *(ptr++) = stats->remote_is_server;
7438 *(ptr++) = stats->interfaceId;
7439 *(ptr++) = stats->func_total;
7440 *(ptr++) = stats->func_index;
7441 *(ptr++) = hgethi(stats->invocations);
7442 *(ptr++) = hgetlo(stats->invocations);
7443 *(ptr++) = hgethi(stats->bytes_sent);
7444 *(ptr++) = hgetlo(stats->bytes_sent);
7445 *(ptr++) = hgethi(stats->bytes_rcvd);
7446 *(ptr++) = hgetlo(stats->bytes_rcvd);
7447 *(ptr++) = stats->queue_time_sum.sec;
7448 *(ptr++) = stats->queue_time_sum.usec;
7449 *(ptr++) = stats->queue_time_sum_sqr.sec;
7450 *(ptr++) = stats->queue_time_sum_sqr.usec;
7451 *(ptr++) = stats->queue_time_min.sec;
7452 *(ptr++) = stats->queue_time_min.usec;
7453 *(ptr++) = stats->queue_time_max.sec;
7454 *(ptr++) = stats->queue_time_max.usec;
7455 *(ptr++) = stats->execution_time_sum.sec;
7456 *(ptr++) = stats->execution_time_sum.usec;
7457 *(ptr++) = stats->execution_time_sum_sqr.sec;
7458 *(ptr++) = stats->execution_time_sum_sqr.usec;
7459 *(ptr++) = stats->execution_time_min.sec;
7460 *(ptr++) = stats->execution_time_min.usec;
7461 *(ptr++) = stats->execution_time_max.sec;
7462 *(ptr++) = stats->execution_time_max.usec;
7468 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7473 * IN callerVersion - the rpc stat version of the caller
7475 * OUT myVersion - the rpc stat version of this function
7477 * OUT clock_sec - local time seconds
7479 * OUT clock_usec - local time microseconds
7481 * OUT allocSize - the number of bytes allocated to contain stats
7483 * OUT statCount - the number stats retrieved from this process.
7485 * OUT stats - the actual stats retrieved from this process.
7489 * Returns void. If successful, stats will != NULL.
7493 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7494 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7495 size_t * allocSize, afs_uint32 * statCount,
7496 afs_uint32 ** stats)
7506 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7509 * Check to see if stats are enabled
7512 MUTEX_ENTER(&rx_rpc_stats);
7513 if (!rxi_monitor_processStats) {
7514 MUTEX_EXIT(&rx_rpc_stats);
7518 clock_GetTime(&now);
7519 *clock_sec = now.sec;
7520 *clock_usec = now.usec;
7523 * Allocate the space based upon the caller version
7525 * If the client is at an older version than we are,
7526 * we return the statistic data in the older data format, but
7527 * we still return our version number so the client knows we
7528 * are maintaining more data than it can retrieve.
7531 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7532 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7533 *statCount = rxi_rpc_process_stat_cnt;
7536 * This can't happen yet, but in the future version changes
7537 * can be handled by adding additional code here
7541 if (space > (size_t) 0) {
7543 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7546 rx_interface_stat_p rpc_stat, nrpc_stat;
7550 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7552 * Copy the data based upon the caller version
7554 rx_MarshallProcessRPCStats(callerVersion,
7555 rpc_stat->stats[0].func_total,
7556 rpc_stat->stats, &ptr);
7562 MUTEX_EXIT(&rx_rpc_stats);
7567 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7571 * IN callerVersion - the rpc stat version of the caller
7573 * OUT myVersion - the rpc stat version of this function
7575 * OUT clock_sec - local time seconds
7577 * OUT clock_usec - local time microseconds
7579 * OUT allocSize - the number of bytes allocated to contain stats
7581 * OUT statCount - the number of stats retrieved from the individual
7584 * OUT stats - the actual stats retrieved from the individual peer structures.
7588 * Returns void. If successful, stats will != NULL.
7592 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7593 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7594 size_t * allocSize, afs_uint32 * statCount,
7595 afs_uint32 ** stats)
7605 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7608 * Check to see if stats are enabled
7611 MUTEX_ENTER(&rx_rpc_stats);
7612 if (!rxi_monitor_peerStats) {
7613 MUTEX_EXIT(&rx_rpc_stats);
7617 clock_GetTime(&now);
7618 *clock_sec = now.sec;
7619 *clock_usec = now.usec;
7622 * Allocate the space based upon the caller version
7624 * If the client is at an older version than we are,
7625 * we return the statistic data in the older data format, but
7626 * we still return our version number so the client knows we
7627 * are maintaining more data than it can retrieve.
7630 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7631 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7632 *statCount = rxi_rpc_peer_stat_cnt;
7635 * This can't happen yet, but in the future version changes
7636 * can be handled by adding additional code here
7640 if (space > (size_t) 0) {
7642 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7645 rx_interface_stat_p rpc_stat, nrpc_stat;
7649 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7651 * We have to fix the offset of rpc_stat since we are
7652 * keeping this structure on two rx_queues. The rx_queue
7653 * package assumes that the rx_queue member is the first
7654 * member of the structure. That is, rx_queue assumes that
7655 * any one item is only on one queue at a time. We are
7656 * breaking that assumption and so we have to do a little
7657 * math to fix our pointers.
7660 fix_offset = (char *)rpc_stat;
7661 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7662 rpc_stat = (rx_interface_stat_p) fix_offset;
7665 * Copy the data based upon the caller version
7667 rx_MarshallProcessRPCStats(callerVersion,
7668 rpc_stat->stats[0].func_total,
7669 rpc_stat->stats, &ptr);
7675 MUTEX_EXIT(&rx_rpc_stats);
7680 * rx_FreeRPCStats - free memory allocated by
7681 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7685 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7686 * rx_RetrievePeerRPCStats
7688 * IN allocSize - the number of bytes in stats.
7696 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7698 rxi_Free(stats, allocSize);
7702 * rx_queryProcessRPCStats - see if process rpc stat collection is
7703 * currently enabled.
7709 * Returns 0 if stats are not enabled != 0 otherwise
7713 rx_queryProcessRPCStats(void)
7716 MUTEX_ENTER(&rx_rpc_stats);
7717 rc = rxi_monitor_processStats;
7718 MUTEX_EXIT(&rx_rpc_stats);
7723 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7729 * Returns 0 if stats are not enabled != 0 otherwise
7733 rx_queryPeerRPCStats(void)
7736 MUTEX_ENTER(&rx_rpc_stats);
7737 rc = rxi_monitor_peerStats;
7738 MUTEX_EXIT(&rx_rpc_stats);
7743 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7753 rx_enableProcessRPCStats(void)
7755 MUTEX_ENTER(&rx_rpc_stats);
7756 rx_enable_stats = 1;
7757 rxi_monitor_processStats = 1;
7758 MUTEX_EXIT(&rx_rpc_stats);
7762 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7772 rx_enablePeerRPCStats(void)
7774 MUTEX_ENTER(&rx_rpc_stats);
7775 rx_enable_stats = 1;
7776 rxi_monitor_peerStats = 1;
7777 MUTEX_EXIT(&rx_rpc_stats);
7781 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7791 rx_disableProcessRPCStats(void)
7793 rx_interface_stat_p rpc_stat, nrpc_stat;
7796 MUTEX_ENTER(&rx_rpc_stats);
7799 * Turn off process statistics and if peer stats is also off, turn
7803 rxi_monitor_processStats = 0;
7804 if (rxi_monitor_peerStats == 0) {
7805 rx_enable_stats = 0;
7808 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7809 unsigned int num_funcs = 0;
7812 queue_Remove(rpc_stat);
7813 num_funcs = rpc_stat->stats[0].func_total;
7815 sizeof(rx_interface_stat_t) +
7816 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7818 rxi_Free(rpc_stat, space);
7819 rxi_rpc_process_stat_cnt -= num_funcs;
7821 MUTEX_EXIT(&rx_rpc_stats);
7825 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7835 rx_disablePeerRPCStats(void)
7837 struct rx_peer **peer_ptr, **peer_end;
7840 MUTEX_ENTER(&rx_rpc_stats);
7843 * Turn off peer statistics and if process stats is also off, turn
7847 rxi_monitor_peerStats = 0;
7848 if (rxi_monitor_processStats == 0) {
7849 rx_enable_stats = 0;
7852 MUTEX_ENTER(&rx_peerHashTable_lock);
7853 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7854 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7856 struct rx_peer *peer, *next, *prev;
7857 for (prev = peer = *peer_ptr; peer; peer = next) {
7859 code = MUTEX_TRYENTER(&peer->peer_lock);
7861 rx_interface_stat_p rpc_stat, nrpc_stat;
7864 (&peer->rpcStats, rpc_stat, nrpc_stat,
7865 rx_interface_stat)) {
7866 unsigned int num_funcs = 0;
7869 queue_Remove(&rpc_stat->queue_header);
7870 queue_Remove(&rpc_stat->all_peers);
7871 num_funcs = rpc_stat->stats[0].func_total;
7873 sizeof(rx_interface_stat_t) +
7874 rpc_stat->stats[0].func_total *
7875 sizeof(rx_function_entry_v1_t);
7877 rxi_Free(rpc_stat, space);
7878 rxi_rpc_peer_stat_cnt -= num_funcs;
7880 MUTEX_EXIT(&peer->peer_lock);
7881 if (prev == *peer_ptr) {
7891 MUTEX_EXIT(&rx_peerHashTable_lock);
7892 MUTEX_EXIT(&rx_rpc_stats);
7896 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7901 * IN clearFlag - flag indicating which stats to clear
7909 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7911 rx_interface_stat_p rpc_stat, nrpc_stat;
7913 MUTEX_ENTER(&rx_rpc_stats);
7915 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7916 unsigned int num_funcs = 0, i;
7917 num_funcs = rpc_stat->stats[0].func_total;
7918 for (i = 0; i < num_funcs; i++) {
7919 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7920 hzero(rpc_stat->stats[i].invocations);
7922 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7923 hzero(rpc_stat->stats[i].bytes_sent);
7925 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7926 hzero(rpc_stat->stats[i].bytes_rcvd);
7928 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7929 rpc_stat->stats[i].queue_time_sum.sec = 0;
7930 rpc_stat->stats[i].queue_time_sum.usec = 0;
7932 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7933 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7934 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7936 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7937 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7938 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7940 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7941 rpc_stat->stats[i].queue_time_max.sec = 0;
7942 rpc_stat->stats[i].queue_time_max.usec = 0;
7944 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7945 rpc_stat->stats[i].execution_time_sum.sec = 0;
7946 rpc_stat->stats[i].execution_time_sum.usec = 0;
7948 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7949 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7950 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7952 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7953 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7954 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7956 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7957 rpc_stat->stats[i].execution_time_max.sec = 0;
7958 rpc_stat->stats[i].execution_time_max.usec = 0;
7963 MUTEX_EXIT(&rx_rpc_stats);
7967 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
7972 * IN clearFlag - flag indicating which stats to clear
7980 rx_clearPeerRPCStats(afs_uint32 clearFlag)
7982 rx_interface_stat_p rpc_stat, nrpc_stat;
7984 MUTEX_ENTER(&rx_rpc_stats);
7986 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7987 unsigned int num_funcs = 0, i;
7990 * We have to fix the offset of rpc_stat since we are
7991 * keeping this structure on two rx_queues. The rx_queue
7992 * package assumes that the rx_queue member is the first
7993 * member of the structure. That is, rx_queue assumes that
7994 * any one item is only on one queue at a time. We are
7995 * breaking that assumption and so we have to do a little
7996 * math to fix our pointers.
7999 fix_offset = (char *)rpc_stat;
8000 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8001 rpc_stat = (rx_interface_stat_p) fix_offset;
8003 num_funcs = rpc_stat->stats[0].func_total;
8004 for (i = 0; i < num_funcs; i++) {
8005 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8006 hzero(rpc_stat->stats[i].invocations);
8008 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8009 hzero(rpc_stat->stats[i].bytes_sent);
8011 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8012 hzero(rpc_stat->stats[i].bytes_rcvd);
8014 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8015 rpc_stat->stats[i].queue_time_sum.sec = 0;
8016 rpc_stat->stats[i].queue_time_sum.usec = 0;
8018 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8019 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8020 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8022 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8023 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8024 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8026 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8027 rpc_stat->stats[i].queue_time_max.sec = 0;
8028 rpc_stat->stats[i].queue_time_max.usec = 0;
8030 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8031 rpc_stat->stats[i].execution_time_sum.sec = 0;
8032 rpc_stat->stats[i].execution_time_sum.usec = 0;
8034 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8035 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8036 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8038 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8039 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8040 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8042 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8043 rpc_stat->stats[i].execution_time_max.sec = 0;
8044 rpc_stat->stats[i].execution_time_max.usec = 0;
8049 MUTEX_EXIT(&rx_rpc_stats);
8053 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8054 * is authorized to enable/disable/clear RX statistics.
8056 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8059 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8061 rxi_rxstat_userok = proc;
8065 rx_RxStatUserOk(struct rx_call *call)
8067 if (!rxi_rxstat_userok)
8069 return rxi_rxstat_userok(call);
8074 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8075 * function in the MSVC runtime DLL (msvcrt.dll).
8077 * Note: the system serializes calls to this function.
8080 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8081 DWORD reason, /* reason function is being called */
8082 LPVOID reserved) /* reserved for future use */
8085 case DLL_PROCESS_ATTACH:
8086 /* library is being attached to a process */
8090 case DLL_PROCESS_DETACH:
8099 int rx_DumpCalls(FILE *outputFile, char *cookie)
8101 #ifdef RXDEBUG_PACKET
8103 #ifdef KDUMP_RX_LOCK
8104 struct rx_call_rx_lock *c;
8110 sprintf(output, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8111 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8113 for (c = rx_allCallsp; c; c = c->allNextp) {
8114 u_short rqc, tqc, iovqc;
8115 struct rx_packet *p, *np;
8117 MUTEX_ENTER(&c->lock);
8118 queue_Count(&c->rq, p, np, rx_packet, rqc);
8119 queue_Count(&c->tq, p, np, rx_packet, tqc);
8120 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8122 sprintf(output, "%s - call=0x%p, id=%u, state=%u, mode=%u, conn=%p, epoch=%u, cid=%u, callNum=%u, connFlags=0x%x, flags=0x%x, "
8123 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8124 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8125 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8126 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8127 #ifdef RX_ENABLE_LOCKS
8130 #ifdef RX_REFCOUNT_CHECK
8131 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8132 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8135 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,
8136 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8137 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8138 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8139 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8140 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8141 #ifdef RX_ENABLE_LOCKS
8142 , (afs_uint32)c->refCount
8144 #ifdef RX_REFCOUNT_CHECK
8145 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8148 MUTEX_EXIT(&c->lock);
8150 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8152 sprintf(output, "%s - End dumping all Rx Calls\r\n", cookie);
8153 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8154 #endif /* RXDEBUG_PACKET */
8157 #endif /* AFS_NT40_ENV */