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"
72 #include "rx_internal.h"
74 #include "rx_globals.h"
76 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
77 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
78 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
80 extern afs_int32 afs_termState;
82 #include "sys/lockl.h"
83 #include "sys/lock_def.h"
84 #endif /* AFS_AIX41_ENV */
85 # include "rxgen_consts.h"
87 # include <sys/types.h>
94 # include <afs/afsutil.h>
95 # include <WINNT\afsreg.h>
97 # include <sys/socket.h>
98 # include <sys/file.h>
100 # include <sys/stat.h>
101 # include <netinet/in.h>
102 # include <sys/time.h>
104 # include "rx_internal.h"
106 # include "rx_user.h"
107 # include "rx_clock.h"
108 # include "rx_queue.h"
109 # include "rx_globals.h"
110 # include "rx_trace.h"
111 # include <afs/rxgen_consts.h>
115 #ifdef AFS_PTHREAD_ENV
117 int (*registerProgram) (pid_t, char *) = 0;
118 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
121 int (*registerProgram) (PROCESS, char *) = 0;
122 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
126 /* Local static routines */
127 static void rxi_DestroyConnectionNoLock(register struct rx_connection *conn);
128 #ifdef RX_ENABLE_LOCKS
129 static void rxi_SetAcksInTransmitQueue(register struct rx_call *call);
132 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
134 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
135 afs_int32 rxi_start_in_error;
137 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
140 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
141 * currently allocated within rx. This number is used to allocate the
142 * memory required to return the statistics when queried.
145 static unsigned int rxi_rpc_peer_stat_cnt;
148 * rxi_rpc_process_stat_cnt counts the total number of local process stat
149 * structures currently allocated within rx. The number is used to allocate
150 * the memory required to return the statistics when queried.
153 static unsigned int rxi_rpc_process_stat_cnt;
155 #if !defined(offsetof)
156 #include <stddef.h> /* for definition of offsetof() */
159 #ifdef AFS_PTHREAD_ENV
163 * Use procedural initialization of mutexes/condition variables
167 extern pthread_mutex_t rx_stats_mutex;
168 extern pthread_mutex_t rx_waiting_mutex;
169 extern pthread_mutex_t rx_quota_mutex;
170 extern pthread_mutex_t rx_pthread_mutex;
171 extern pthread_mutex_t rx_packets_mutex;
172 extern pthread_mutex_t des_init_mutex;
173 extern pthread_mutex_t des_random_mutex;
174 extern pthread_mutex_t rx_clock_mutex;
175 extern pthread_mutex_t rxi_connCacheMutex;
176 extern pthread_mutex_t rx_event_mutex;
177 extern pthread_mutex_t osi_malloc_mutex;
178 extern pthread_mutex_t event_handler_mutex;
179 extern pthread_mutex_t listener_mutex;
180 extern pthread_mutex_t rx_if_init_mutex;
181 extern pthread_mutex_t rx_if_mutex;
182 extern pthread_mutex_t rxkad_client_uid_mutex;
183 extern pthread_mutex_t rxkad_random_mutex;
185 extern pthread_cond_t rx_event_handler_cond;
186 extern pthread_cond_t rx_listener_cond;
188 static pthread_mutex_t epoch_mutex;
189 static pthread_mutex_t rx_init_mutex;
190 static pthread_mutex_t rx_debug_mutex;
191 static pthread_mutex_t rx_rpc_stats;
194 rxi_InitPthread(void)
196 assert(pthread_mutex_init(&rx_clock_mutex, (const pthread_mutexattr_t *)0)
198 assert(pthread_mutex_init(&rx_stats_mutex, (const pthread_mutexattr_t *)0)
200 assert(pthread_mutex_init(&rx_waiting_mutex, (const pthread_mutexattr_t *)0)
202 assert(pthread_mutex_init(&rx_quota_mutex, (const pthread_mutexattr_t *)0)
204 assert(pthread_mutex_init(&rx_pthread_mutex, (const pthread_mutexattr_t *)0)
206 assert(pthread_mutex_init(&rx_packets_mutex, (const pthread_mutexattr_t *)0)
208 assert(pthread_mutex_init
209 (&rxi_connCacheMutex, (const pthread_mutexattr_t *)0) == 0);
210 assert(pthread_mutex_init(&rx_init_mutex, (const pthread_mutexattr_t *)0)
212 assert(pthread_mutex_init(&epoch_mutex, (const pthread_mutexattr_t *)0) ==
214 assert(pthread_mutex_init(&rx_event_mutex, (const pthread_mutexattr_t *)0)
216 assert(pthread_mutex_init(&des_init_mutex, (const pthread_mutexattr_t *)0)
218 assert(pthread_mutex_init
219 (&des_random_mutex, (const pthread_mutexattr_t *)0) == 0);
220 assert(pthread_mutex_init
221 (&osi_malloc_mutex, (const pthread_mutexattr_t *)0) == 0);
222 assert(pthread_mutex_init
223 (&event_handler_mutex, (const pthread_mutexattr_t *)0) == 0);
224 assert(pthread_mutex_init(&listener_mutex, (const pthread_mutexattr_t *)0)
226 assert(pthread_mutex_init
227 (&rx_if_init_mutex, (const pthread_mutexattr_t *)0) == 0);
228 assert(pthread_mutex_init(&rx_if_mutex, (const pthread_mutexattr_t *)0) ==
230 assert(pthread_mutex_init
231 (&rxkad_client_uid_mutex, (const pthread_mutexattr_t *)0) == 0);
232 assert(pthread_mutex_init
233 (&rxkad_random_mutex, (const pthread_mutexattr_t *)0) == 0);
234 assert(pthread_mutex_init(&rx_debug_mutex, (const pthread_mutexattr_t *)0)
237 assert(pthread_cond_init
238 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
239 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
241 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
242 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
244 rxkad_global_stats_init();
246 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
247 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
248 #ifdef RX_ENABLE_LOCKS
251 #endif /* RX_LOCKS_DB */
252 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
253 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
255 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
257 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
259 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
261 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
262 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
263 #endif /* RX_ENABLE_LOCKS */
266 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
267 #define INIT_PTHREAD_LOCKS \
268 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
270 * The rx_stats_mutex mutex protects the following global variables:
271 * rxi_lowConnRefCount
272 * rxi_lowPeerRefCount
281 * The rx_quota_mutex mutex protects the following global variables:
289 * The rx_freePktQ_lock protects the following global variables:
294 * The rx_packets_mutex mutex protects the following global variables:
302 * The rx_pthread_mutex mutex protects the following global variables:
306 #define INIT_PTHREAD_LOCKS
310 /* Variables for handling the minProcs implementation. availProcs gives the
311 * number of threads available in the pool at this moment (not counting dudes
312 * executing right now). totalMin gives the total number of procs required
313 * for handling all minProcs requests. minDeficit is a dynamic variable
314 * tracking the # of procs required to satisfy all of the remaining minProcs
316 * For fine grain locking to work, the quota check and the reservation of
317 * a server thread has to come while rxi_availProcs and rxi_minDeficit
318 * are locked. To this end, the code has been modified under #ifdef
319 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
320 * same time. A new function, ReturnToServerPool() returns the allocation.
322 * A call can be on several queue's (but only one at a time). When
323 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
324 * that no one else is touching the queue. To this end, we store the address
325 * of the queue lock in the call structure (under the call lock) when we
326 * put the call on a queue, and we clear the call_queue_lock when the
327 * call is removed from a queue (once the call lock has been obtained).
328 * This allows rxi_ResetCall to safely synchronize with others wishing
329 * to manipulate the queue.
332 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
333 static afs_kmutex_t rx_rpc_stats;
334 void rxi_StartUnlocked(struct rxevent *event, void *call,
335 void *arg1, int istack);
338 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
339 ** pretty good that the next packet coming in is from the same connection
340 ** as the last packet, since we're send multiple packets in a transmit window.
342 struct rx_connection *rxLastConn = 0;
344 #ifdef RX_ENABLE_LOCKS
345 /* The locking hierarchy for rx fine grain locking is composed of these
348 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
349 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
350 * call->lock - locks call data fields.
351 * These are independent of each other:
352 * rx_freeCallQueue_lock
357 * serverQueueEntry->lock
359 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
360 * peer->lock - locks peer data fields.
361 * conn_data_lock - that more than one thread is not updating a conn data
362 * field at the same time.
370 * Do we need a lock to protect the peer field in the conn structure?
371 * conn->peer was previously a constant for all intents and so has no
372 * lock protecting this field. The multihomed client delta introduced
373 * a RX code change : change the peer field in the connection structure
374 * to that remote inetrface from which the last packet for this
375 * connection was sent out. This may become an issue if further changes
378 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
379 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
381 /* rxdb_fileID is used to identify the lock location, along with line#. */
382 static int rxdb_fileID = RXDB_FILE_RX;
383 #endif /* RX_LOCKS_DB */
384 #else /* RX_ENABLE_LOCKS */
385 #define SET_CALL_QUEUE_LOCK(C, L)
386 #define CLEAR_CALL_QUEUE_LOCK(C)
387 #endif /* RX_ENABLE_LOCKS */
388 struct rx_serverQueueEntry *rx_waitForPacket = 0;
389 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
391 /* ------------Exported Interfaces------------- */
393 /* This function allows rxkad to set the epoch to a suitably random number
394 * which rx_NewConnection will use in the future. The principle purpose is to
395 * get rxnull connections to use the same epoch as the rxkad connections do, at
396 * least once the first rxkad connection is established. This is important now
397 * that the host/port addresses aren't used in FindConnection: the uniqueness
398 * of epoch/cid matters and the start time won't do. */
400 #ifdef AFS_PTHREAD_ENV
402 * This mutex protects the following global variables:
406 #define LOCK_EPOCH assert(pthread_mutex_lock(&epoch_mutex)==0)
407 #define UNLOCK_EPOCH assert(pthread_mutex_unlock(&epoch_mutex)==0)
411 #endif /* AFS_PTHREAD_ENV */
414 rx_SetEpoch(afs_uint32 epoch)
421 /* Initialize rx. A port number may be mentioned, in which case this
422 * becomes the default port number for any service installed later.
423 * If 0 is provided for the port number, a random port will be chosen
424 * by the kernel. Whether this will ever overlap anything in
425 * /etc/services is anybody's guess... Returns 0 on success, -1 on
430 int rxinit_status = 1;
431 #ifdef AFS_PTHREAD_ENV
433 * This mutex protects the following global variables:
437 #define LOCK_RX_INIT assert(pthread_mutex_lock(&rx_init_mutex)==0)
438 #define UNLOCK_RX_INIT assert(pthread_mutex_unlock(&rx_init_mutex)==0)
441 #define UNLOCK_RX_INIT
445 rx_InitHost(u_int host, u_int port)
452 char *htable, *ptable;
459 if (rxinit_status == 0) {
460 tmp_status = rxinit_status;
462 return tmp_status; /* Already started; return previous error code. */
468 if (afs_winsockInit() < 0)
474 * Initialize anything necessary to provide a non-premptive threading
477 rxi_InitializeThreadSupport();
480 /* Allocate and initialize a socket for client and perhaps server
483 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
484 if (rx_socket == OSI_NULLSOCKET) {
488 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
491 #endif /* RX_LOCKS_DB */
492 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
493 MUTEX_INIT(&rx_waiting_mutex, "rx_waiting_mutex", MUTEX_DEFAULT, 0);
494 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
495 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
496 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
497 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
498 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
499 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
500 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
502 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
504 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
506 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
508 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
509 #if defined(AFS_HPUX110_ENV)
511 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
512 #endif /* AFS_HPUX110_ENV */
513 #endif /* RX_ENABLE_LOCKS && KERNEL */
516 rx_connDeadTime = 12;
517 rx_tranquil = 0; /* reset flag */
518 memset((char *)&rx_stats, 0, sizeof(struct rx_statistics));
520 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
521 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
522 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
523 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
524 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
525 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
527 /* Malloc up a bunch of packets & buffers */
529 queue_Init(&rx_freePacketQueue);
530 rxi_NeedMorePackets = FALSE;
531 #ifdef RX_ENABLE_TSFPQ
532 rx_nPackets = 0; /* in TSFPQ version, rx_nPackets is managed by rxi_MorePackets* */
533 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
534 #else /* RX_ENABLE_TSFPQ */
535 rx_nPackets = rx_extraPackets + RX_MAX_QUOTA + 2; /* fudge */
536 rxi_MorePackets(rx_nPackets);
537 #endif /* RX_ENABLE_TSFPQ */
544 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
545 tv.tv_sec = clock_now.sec;
546 tv.tv_usec = clock_now.usec;
547 srand((unsigned int)tv.tv_usec);
554 #if defined(KERNEL) && !defined(UKERNEL)
555 /* Really, this should never happen in a real kernel */
558 struct sockaddr_in addr;
560 int addrlen = sizeof(addr);
562 socklen_t addrlen = sizeof(addr);
564 if (getsockname((int)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
568 rx_port = addr.sin_port;
571 rx_stats.minRtt.sec = 9999999;
573 rx_SetEpoch(tv.tv_sec | 0x80000000);
575 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
576 * will provide a randomer value. */
578 rx_MutexAdd(rxi_dataQuota, rx_extraQuota, rx_stats_quota); /* + extra pkts caller asked to rsrv */
579 /* *Slightly* random start time for the cid. This is just to help
580 * out with the hashing function at the peer */
581 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
582 rx_connHashTable = (struct rx_connection **)htable;
583 rx_peerHashTable = (struct rx_peer **)ptable;
585 rx_lastAckDelay.sec = 0;
586 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
587 rx_hardAckDelay.sec = 0;
588 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
589 rx_softAckDelay.sec = 0;
590 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
592 rxevent_Init(20, rxi_ReScheduleEvents);
594 /* Initialize various global queues */
595 queue_Init(&rx_idleServerQueue);
596 queue_Init(&rx_incomingCallQueue);
597 queue_Init(&rx_freeCallQueue);
599 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
600 /* Initialize our list of usable IP addresses. */
604 /* Start listener process (exact function is dependent on the
605 * implementation environment--kernel or user space) */
609 tmp_status = rxinit_status = 0;
617 return rx_InitHost(htonl(INADDR_ANY), port);
620 /* called with unincremented nRequestsRunning to see if it is OK to start
621 * a new thread in this service. Could be "no" for two reasons: over the
622 * max quota, or would prevent others from reaching their min quota.
624 #ifdef RX_ENABLE_LOCKS
625 /* This verion of QuotaOK reserves quota if it's ok while the
626 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
629 QuotaOK(register struct rx_service *aservice)
631 /* check if over max quota */
632 if (aservice->nRequestsRunning >= aservice->maxProcs) {
636 /* under min quota, we're OK */
637 /* otherwise, can use only if there are enough to allow everyone
638 * to go to their min quota after this guy starts.
641 MUTEX_ENTER(&rx_quota_mutex);
642 if ((aservice->nRequestsRunning < aservice->minProcs)
643 || (rxi_availProcs > rxi_minDeficit)) {
644 aservice->nRequestsRunning++;
645 /* just started call in minProcs pool, need fewer to maintain
647 if (aservice->nRequestsRunning <= aservice->minProcs)
650 MUTEX_EXIT(&rx_quota_mutex);
653 MUTEX_EXIT(&rx_quota_mutex);
659 ReturnToServerPool(register struct rx_service *aservice)
661 aservice->nRequestsRunning--;
662 MUTEX_ENTER(&rx_quota_mutex);
663 if (aservice->nRequestsRunning < aservice->minProcs)
666 MUTEX_EXIT(&rx_quota_mutex);
669 #else /* RX_ENABLE_LOCKS */
671 QuotaOK(register struct rx_service *aservice)
674 /* under min quota, we're OK */
675 if (aservice->nRequestsRunning < aservice->minProcs)
678 /* check if over max quota */
679 if (aservice->nRequestsRunning >= aservice->maxProcs)
682 /* otherwise, can use only if there are enough to allow everyone
683 * to go to their min quota after this guy starts.
685 if (rxi_availProcs > rxi_minDeficit)
689 #endif /* RX_ENABLE_LOCKS */
692 /* Called by rx_StartServer to start up lwp's to service calls.
693 NExistingProcs gives the number of procs already existing, and which
694 therefore needn't be created. */
696 rxi_StartServerProcs(int nExistingProcs)
698 register struct rx_service *service;
703 /* For each service, reserve N processes, where N is the "minimum"
704 * number of processes that MUST be able to execute a request in parallel,
705 * at any time, for that process. Also compute the maximum difference
706 * between any service's maximum number of processes that can run
707 * (i.e. the maximum number that ever will be run, and a guarantee
708 * that this number will run if other services aren't running), and its
709 * minimum number. The result is the extra number of processes that
710 * we need in order to provide the latter guarantee */
711 for (i = 0; i < RX_MAX_SERVICES; i++) {
713 service = rx_services[i];
714 if (service == (struct rx_service *)0)
716 nProcs += service->minProcs;
717 diff = service->maxProcs - service->minProcs;
721 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
722 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
723 for (i = 0; i < nProcs; i++) {
724 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
730 /* This routine is only required on Windows */
732 rx_StartClientThread(void)
734 #ifdef AFS_PTHREAD_ENV
736 pid = pthread_self();
737 #endif /* AFS_PTHREAD_ENV */
739 #endif /* AFS_NT40_ENV */
741 /* This routine must be called if any services are exported. If the
742 * donateMe flag is set, the calling process is donated to the server
745 rx_StartServer(int donateMe)
747 register struct rx_service *service;
753 /* Start server processes, if necessary (exact function is dependent
754 * on the implementation environment--kernel or user space). DonateMe
755 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
756 * case, one less new proc will be created rx_StartServerProcs.
758 rxi_StartServerProcs(donateMe);
760 /* count up the # of threads in minProcs, and add set the min deficit to
761 * be that value, too.
763 for (i = 0; i < RX_MAX_SERVICES; i++) {
764 service = rx_services[i];
765 if (service == (struct rx_service *)0)
767 MUTEX_ENTER(&rx_quota_mutex);
768 rxi_totalMin += service->minProcs;
769 /* below works even if a thread is running, since minDeficit would
770 * still have been decremented and later re-incremented.
772 rxi_minDeficit += service->minProcs;
773 MUTEX_EXIT(&rx_quota_mutex);
776 /* Turn on reaping of idle server connections */
777 rxi_ReapConnections(NULL, NULL, NULL);
786 #ifdef AFS_PTHREAD_ENV
788 pid = (pid_t) pthread_self();
789 #else /* AFS_PTHREAD_ENV */
791 LWP_CurrentProcess(&pid);
792 #endif /* AFS_PTHREAD_ENV */
794 sprintf(name, "srv_%d", ++nProcs);
796 (*registerProgram) (pid, name);
798 #endif /* AFS_NT40_ENV */
799 rx_ServerProc(NULL); /* Never returns */
801 #ifdef RX_ENABLE_TSFPQ
802 /* no use leaving packets around in this thread's local queue if
803 * it isn't getting donated to the server thread pool.
805 rxi_FlushLocalPacketsTSFPQ();
806 #endif /* RX_ENABLE_TSFPQ */
810 /* Create a new client connection to the specified service, using the
811 * specified security object to implement the security model for this
813 struct rx_connection *
814 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
815 struct rx_securityClass *securityObject,
816 int serviceSecurityIndex)
819 afs_int32 cix, nclones;
820 struct rx_connection *conn, *tconn, *ptconn;
825 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %x, serviceSecurityIndex %d)\n", ntohl(shost), ntohs(sport), sservice, securityObject, serviceSecurityIndex));
828 MUTEX_ENTER(&rx_connHashTable_lock);
831 * allocate the connection and all of its clones.
832 * clones are flagged as such and have their
833 * parent set to the 0th connection object.
835 for (nclones = rx_max_clones_per_connection,
839 ++cix, ptconn = tconn) {
841 tconn = rxi_AllocConnection();
842 tconn->cid = (rx_nextCid += RX_MAXCALLS);
843 tconn->type = RX_CLIENT_CONNECTION;
844 tconn->epoch = rx_epoch;
845 tconn->peer = rxi_FindPeer(shost, sport, 0, 1);
846 tconn->serviceId = sservice;
847 tconn->securityObject = securityObject;
848 tconn->securityData = (void *) 0;
849 tconn->securityIndex = serviceSecurityIndex;
850 tconn->ackRate = RX_FAST_ACK_RATE;
851 tconn->nSpecific = 0;
852 tconn->specific = NULL;
853 tconn->challengeEvent = NULL;
854 tconn->delayedAbortEvent = NULL;
855 tconn->abortCount = 0;
858 for (i = 0; i < RX_MAXCALLS; i++) {
859 tconn->twind[i] = rx_initSendWindow;
860 tconn->rwind[i] = rx_initReceiveWindow;
865 conn->nclones = nclones;
867 conn->next_clone = 0;
868 rx_SetConnDeadTime(conn, rx_connDeadTime);
871 tconn->flags |= RX_CLONED_CONNECTION;
872 tconn->parent = conn;
873 ptconn->next_clone = tconn;
874 tconn->secondsUntilDead = 0;
875 tconn->secondsUntilPing = 0;
878 /* generic connection setup */
879 #ifdef RX_ENABLE_LOCKS
880 MUTEX_INIT(&tconn->conn_call_lock, "conn call lock", MUTEX_DEFAULT,
882 MUTEX_INIT(&tconn->conn_data_lock, "conn data lock", MUTEX_DEFAULT,
884 CV_INIT(&tconn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
886 RXS_NewConnection(securityObject, tconn);
888 CONN_HASH(shost, sport, tconn->cid, tconn->epoch,
889 RX_CLIENT_CONNECTION);
890 tconn->refCount++; /* no lock required since only this thread knows */
891 tconn->next = rx_connHashTable[hashindex];
892 rx_connHashTable[hashindex] = tconn;
894 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
897 MUTEX_EXIT(&rx_connHashTable_lock);
903 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
905 /* The idea is to set the dead time to a value that allows several
906 * keepalives to be dropped without timing out the connection. */
907 struct rx_connection *tconn =
908 (rx_IsClonedConn(conn)) ? conn->parent : conn;
910 tconn->secondsUntilDead = MAX(seconds, 6);
911 tconn->secondsUntilPing = rx_ConnSecondsUntilDead(tconn) / 6;
914 int rxi_lowPeerRefCount = 0;
915 int rxi_lowConnRefCount = 0;
918 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
919 * NOTE: must not be called with rx_connHashTable_lock held.
922 rxi_CleanupConnection(struct rx_connection *conn)
924 /* Notify the service exporter, if requested, that this connection
925 * is being destroyed */
926 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
927 (*conn->service->destroyConnProc) (conn);
929 /* Notify the security module that this connection is being destroyed */
930 RXS_DestroyConnection(conn->securityObject, conn);
932 /* If this is the last connection using the rx_peer struct, set its
933 * idle time to now. rxi_ReapConnections will reap it if it's still
934 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
936 MUTEX_ENTER(&rx_peerHashTable_lock);
937 if (conn->peer->refCount < 2) {
938 conn->peer->idleWhen = clock_Sec();
939 if (conn->peer->refCount < 1) {
940 conn->peer->refCount = 1;
942 rx_MutexIncrement(rxi_lowPeerRefCount, rx_stats_mutex);
945 conn->peer->refCount--;
946 MUTEX_EXIT(&rx_peerHashTable_lock);
950 if (conn->type == RX_SERVER_CONNECTION)
951 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
953 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
956 if (conn->specific) {
958 for (i = 0; i < conn->nSpecific; i++) {
959 if (conn->specific[i] && rxi_keyCreate_destructor[i])
960 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
961 conn->specific[i] = NULL;
963 free(conn->specific);
965 conn->specific = NULL;
969 MUTEX_DESTROY(&conn->conn_call_lock);
970 MUTEX_DESTROY(&conn->conn_data_lock);
971 CV_DESTROY(&conn->conn_call_cv);
973 rxi_FreeConnection(conn);
976 /* Destroy the specified connection */
978 rxi_DestroyConnection(register struct rx_connection *conn)
980 register struct rx_connection *tconn, *dtconn;
982 MUTEX_ENTER(&rx_connHashTable_lock);
984 /* destroy any clones that might exist */
985 if (!rx_IsClonedConn(conn)) {
986 tconn = conn->next_clone;
987 conn->next_clone = 0; /* once */
991 tconn = tconn->next_clone;
992 rxi_DestroyConnectionNoLock(dtconn);
994 * if destroyed dtconn will be the head of
995 * rx_connCleanup_list. Remove it and clean
996 * it up now as no one else is holding a
999 if (dtconn == rx_connCleanup_list) {
1000 rx_connCleanup_list = rx_connCleanup_list->next;
1001 MUTEX_EXIT(&rx_connHashTable_lock);
1002 /* rxi_CleanupConnection will free dtconn */
1003 rxi_CleanupConnection(dtconn);
1004 MUTEX_ENTER(&rx_connHashTable_lock);
1007 } /* while(tconn) */
1010 rxi_DestroyConnectionNoLock(conn);
1011 /* conn should be at the head of the cleanup list */
1012 if (conn == rx_connCleanup_list) {
1013 rx_connCleanup_list = rx_connCleanup_list->next;
1014 MUTEX_EXIT(&rx_connHashTable_lock);
1015 rxi_CleanupConnection(conn);
1017 #ifdef RX_ENABLE_LOCKS
1019 MUTEX_EXIT(&rx_connHashTable_lock);
1021 #endif /* RX_ENABLE_LOCKS */
1025 rxi_DestroyConnectionNoLock(register struct rx_connection *conn)
1027 register struct rx_connection **conn_ptr;
1028 register int havecalls = 0;
1029 struct rx_packet *packet;
1036 MUTEX_ENTER(&conn->conn_data_lock);
1037 if (conn->refCount > 0)
1040 if (rx_stats_active) {
1041 MUTEX_ENTER(&rx_stats_mutex);
1042 rxi_lowConnRefCount++;
1043 MUTEX_EXIT(&rx_stats_mutex);
1047 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1048 /* Busy; wait till the last guy before proceeding */
1049 MUTEX_EXIT(&conn->conn_data_lock);
1054 /* If the client previously called rx_NewCall, but it is still
1055 * waiting, treat this as a running call, and wait to destroy the
1056 * connection later when the call completes. */
1057 if ((conn->type == RX_CLIENT_CONNECTION)
1058 && (conn->flags & RX_CONN_MAKECALL_WAITING)) {
1059 conn->flags |= RX_CONN_DESTROY_ME;
1060 MUTEX_EXIT(&conn->conn_data_lock);
1064 MUTEX_EXIT(&conn->conn_data_lock);
1066 /* Check for extant references to this connection */
1067 for (i = 0; i < RX_MAXCALLS; i++) {
1068 register struct rx_call *call = conn->call[i];
1071 if (conn->type == RX_CLIENT_CONNECTION) {
1072 MUTEX_ENTER(&call->lock);
1073 if (call->delayedAckEvent) {
1074 /* Push the final acknowledgment out now--there
1075 * won't be a subsequent call to acknowledge the
1076 * last reply packets */
1077 rxevent_Cancel(call->delayedAckEvent, call,
1078 RX_CALL_REFCOUNT_DELAY);
1079 if (call->state == RX_STATE_PRECALL
1080 || call->state == RX_STATE_ACTIVE) {
1081 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1083 rxi_AckAll(NULL, call, 0);
1086 MUTEX_EXIT(&call->lock);
1090 #ifdef RX_ENABLE_LOCKS
1092 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1093 MUTEX_EXIT(&conn->conn_data_lock);
1095 /* Someone is accessing a packet right now. */
1099 #endif /* RX_ENABLE_LOCKS */
1102 /* Don't destroy the connection if there are any call
1103 * structures still in use */
1104 rx_MutexOr(conn->flags, RX_CONN_DESTROY_ME, conn->conn_data_lock);
1109 if (conn->delayedAbortEvent) {
1110 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1111 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1113 MUTEX_ENTER(&conn->conn_data_lock);
1114 rxi_SendConnectionAbort(conn, packet, 0, 1);
1115 MUTEX_EXIT(&conn->conn_data_lock);
1116 rxi_FreePacket(packet);
1120 /* Remove from connection hash table before proceeding */
1122 &rx_connHashTable[CONN_HASH
1123 (peer->host, peer->port, conn->cid, conn->epoch,
1125 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1126 if (*conn_ptr == conn) {
1127 *conn_ptr = conn->next;
1131 /* if the conn that we are destroying was the last connection, then we
1132 * clear rxLastConn as well */
1133 if (rxLastConn == conn)
1136 /* Make sure the connection is completely reset before deleting it. */
1137 /* get rid of pending events that could zap us later */
1138 if (conn->challengeEvent)
1139 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1140 if (conn->checkReachEvent)
1141 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1143 /* Add the connection to the list of destroyed connections that
1144 * need to be cleaned up. This is necessary to avoid deadlocks
1145 * in the routines we call to inform others that this connection is
1146 * being destroyed. */
1147 conn->next = rx_connCleanup_list;
1148 rx_connCleanup_list = conn;
1151 /* Externally available version */
1153 rx_DestroyConnection(register struct rx_connection *conn)
1158 rxi_DestroyConnection(conn);
1163 rx_GetConnection(register struct rx_connection *conn)
1168 rx_MutexIncrement(conn->refCount, conn->conn_data_lock);
1172 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1173 /* Wait for the transmit queue to no longer be busy.
1174 * requires the call->lock to be held */
1175 static void rxi_WaitforTQBusy(struct rx_call *call) {
1176 while (call->flags & RX_CALL_TQ_BUSY) {
1177 call->flags |= RX_CALL_TQ_WAIT;
1179 #ifdef RX_ENABLE_LOCKS
1180 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1181 CV_WAIT(&call->cv_tq, &call->lock);
1182 #else /* RX_ENABLE_LOCKS */
1183 osi_rxSleep(&call->tq);
1184 #endif /* RX_ENABLE_LOCKS */
1186 if (call->tqWaiters == 0) {
1187 call->flags &= ~RX_CALL_TQ_WAIT;
1193 /* Start a new rx remote procedure call, on the specified connection.
1194 * If wait is set to 1, wait for a free call channel; otherwise return
1195 * 0. Maxtime gives the maximum number of seconds this call may take,
1196 * after rx_NewCall returns. After this time interval, a call to any
1197 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1198 * For fine grain locking, we hold the conn_call_lock in order to
1199 * to ensure that we don't get signalle after we found a call in an active
1200 * state and before we go to sleep.
1203 rx_NewCall(register struct rx_connection *conn)
1206 register struct rx_call *call;
1207 struct clock queueTime;
1211 dpf(("rx_NewCall(conn %x)\n", conn));
1214 clock_GetTime(&queueTime);
1215 MUTEX_ENTER(&conn->conn_call_lock);
1218 * Check if there are others waiting for a new call.
1219 * If so, let them go first to avoid starving them.
1220 * This is a fairly simple scheme, and might not be
1221 * a complete solution for large numbers of waiters.
1223 * makeCallWaiters keeps track of the number of
1224 * threads waiting to make calls and the
1225 * RX_CONN_MAKECALL_WAITING flag bit is used to
1226 * indicate that there are indeed calls waiting.
1227 * The flag is set when the waiter is incremented.
1228 * It is only cleared in rx_EndCall when
1229 * makeCallWaiters is 0. This prevents us from
1230 * accidently destroying the connection while it
1231 * is potentially about to be used.
1233 MUTEX_ENTER(&conn->conn_data_lock);
1234 if (conn->makeCallWaiters) {
1235 conn->flags |= RX_CONN_MAKECALL_WAITING;
1236 conn->makeCallWaiters++;
1237 MUTEX_EXIT(&conn->conn_data_lock);
1239 #ifdef RX_ENABLE_LOCKS
1240 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1244 rx_MutexDecrement(conn->makeCallWaiters, conn->conn_data_lock);
1246 MUTEX_EXIT(&conn->conn_data_lock);
1249 /* search for next free call on this connection or
1250 * its clones, if any */
1252 register struct rx_connection *tconn;
1254 for (tconn = conn; tconn; tconn = tconn->next_clone) {
1255 for (i = 0; i < RX_MAXCALLS; i++) {
1256 call = tconn->call[i];
1258 MUTEX_ENTER(&call->lock);
1259 if (call->state == RX_STATE_DALLY) {
1260 rxi_ResetCall(call, 0);
1261 (*call->callNumber)++;
1264 MUTEX_EXIT(&call->lock);
1266 call = rxi_NewCall(tconn, i);
1269 } /* for i < RX_MAXCALLS */
1273 * to be here, all available calls for this connection (and all
1274 * of its clones) must be in use
1277 MUTEX_ENTER(&conn->conn_data_lock);
1278 conn->flags |= RX_CONN_MAKECALL_WAITING;
1279 conn->makeCallWaiters++;
1280 MUTEX_EXIT(&conn->conn_data_lock);
1282 #ifdef RX_ENABLE_LOCKS
1283 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1287 rx_MutexDecrement(conn->makeCallWaiters, conn->conn_data_lock);
1292 * Wake up anyone else who might be giving us a chance to
1293 * run (see code above that avoids resource starvation).
1295 #ifdef RX_ENABLE_LOCKS
1296 CV_BROADCAST(&conn->conn_call_cv);
1301 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1303 /* Client is initially in send mode */
1304 call->state = RX_STATE_ACTIVE;
1305 call->error = rx_ConnError(conn);
1307 call->mode = RX_MODE_ERROR;
1309 call->mode = RX_MODE_SENDING;
1311 /* remember start time for call in case we have hard dead time limit */
1312 call->queueTime = queueTime;
1313 clock_GetTime(&call->startTime);
1314 hzero(call->bytesSent);
1315 hzero(call->bytesRcvd);
1317 /* Turn on busy protocol. */
1318 rxi_KeepAliveOn(call);
1320 MUTEX_EXIT(&call->lock);
1321 MUTEX_EXIT(&conn->conn_call_lock);
1324 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1325 /* Now, if TQ wasn't cleared earlier, do it now. */
1326 MUTEX_ENTER(&call->lock);
1327 rxi_WaitforTQBusy(call);
1328 if (call->flags & RX_CALL_TQ_CLEARME) {
1329 rxi_ClearTransmitQueue(call, 1);
1330 /*queue_Init(&call->tq);*/
1332 MUTEX_EXIT(&call->lock);
1333 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1335 dpf(("rx_NewCall(call %x)\n", call));
1340 rxi_HasActiveCalls(register struct rx_connection *aconn)
1343 register struct rx_call *tcall;
1347 for (i = 0; i < RX_MAXCALLS; i++) {
1348 if ((tcall = aconn->call[i])) {
1349 if ((tcall->state == RX_STATE_ACTIVE)
1350 || (tcall->state == RX_STATE_PRECALL)) {
1361 rxi_GetCallNumberVector(register struct rx_connection *aconn,
1362 register afs_int32 * aint32s)
1365 register struct rx_call *tcall;
1369 for (i = 0; i < RX_MAXCALLS; i++) {
1370 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1371 aint32s[i] = aconn->callNumber[i] + 1;
1373 aint32s[i] = aconn->callNumber[i];
1380 rxi_SetCallNumberVector(register struct rx_connection *aconn,
1381 register afs_int32 * aint32s)
1384 register struct rx_call *tcall;
1388 for (i = 0; i < RX_MAXCALLS; i++) {
1389 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1390 aconn->callNumber[i] = aint32s[i] - 1;
1392 aconn->callNumber[i] = aint32s[i];
1398 /* Advertise a new service. A service is named locally by a UDP port
1399 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1402 char *serviceName; Name for identification purposes (e.g. the
1403 service name might be used for probing for
1406 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1407 char *serviceName, struct rx_securityClass **securityObjects,
1408 int nSecurityObjects,
1409 afs_int32(*serviceProc) (struct rx_call * acall))
1411 osi_socket socket = OSI_NULLSOCKET;
1412 register struct rx_service *tservice;
1418 if (serviceId == 0) {
1420 "rx_NewService: service id for service %s is not non-zero.\n",
1427 "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",
1435 tservice = rxi_AllocService();
1437 for (i = 0; i < RX_MAX_SERVICES; i++) {
1438 register struct rx_service *service = rx_services[i];
1440 if (port == service->servicePort && host == service->serviceHost) {
1441 if (service->serviceId == serviceId) {
1442 /* The identical service has already been
1443 * installed; if the caller was intending to
1444 * change the security classes used by this
1445 * service, he/she loses. */
1447 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1448 serviceName, serviceId, service->serviceName);
1450 rxi_FreeService(tservice);
1453 /* Different service, same port: re-use the socket
1454 * which is bound to the same port */
1455 socket = service->socket;
1458 if (socket == OSI_NULLSOCKET) {
1459 /* If we don't already have a socket (from another
1460 * service on same port) get a new one */
1461 socket = rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
1462 if (socket == OSI_NULLSOCKET) {
1464 rxi_FreeService(tservice);
1469 service->socket = socket;
1470 service->serviceHost = host;
1471 service->servicePort = port;
1472 service->serviceId = serviceId;
1473 service->serviceName = serviceName;
1474 service->nSecurityObjects = nSecurityObjects;
1475 service->securityObjects = securityObjects;
1476 service->minProcs = 0;
1477 service->maxProcs = 1;
1478 service->idleDeadTime = 60;
1479 service->idleDeadErr = 0;
1480 service->connDeadTime = rx_connDeadTime;
1481 service->executeRequestProc = serviceProc;
1482 service->checkReach = 0;
1483 rx_services[i] = service; /* not visible until now */
1489 rxi_FreeService(tservice);
1490 (osi_Msg "rx_NewService: cannot support > %d services\n",
1495 /* Set configuration options for all of a service's security objects */
1498 rx_SetSecurityConfiguration(struct rx_service *service,
1499 rx_securityConfigVariables type,
1503 for (i = 0; i<service->nSecurityObjects; i++) {
1504 if (service->securityObjects[i]) {
1505 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1513 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1514 struct rx_securityClass **securityObjects, int nSecurityObjects,
1515 afs_int32(*serviceProc) (struct rx_call * acall))
1517 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1520 /* Generic request processing loop. This routine should be called
1521 * by the implementation dependent rx_ServerProc. If socketp is
1522 * non-null, it will be set to the file descriptor that this thread
1523 * is now listening on. If socketp is null, this routine will never
1526 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1528 register struct rx_call *call;
1529 register afs_int32 code;
1530 register struct rx_service *tservice = NULL;
1537 call = rx_GetCall(threadID, tservice, socketp);
1538 if (socketp && *socketp != OSI_NULLSOCKET) {
1539 /* We are now a listener thread */
1544 /* if server is restarting( typically smooth shutdown) then do not
1545 * allow any new calls.
1548 if (rx_tranquil && (call != NULL)) {
1552 MUTEX_ENTER(&call->lock);
1554 rxi_CallError(call, RX_RESTARTING);
1555 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1557 MUTEX_EXIT(&call->lock);
1561 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1562 #ifdef RX_ENABLE_LOCKS
1564 #endif /* RX_ENABLE_LOCKS */
1565 afs_termState = AFSOP_STOP_AFS;
1566 afs_osi_Wakeup(&afs_termState);
1567 #ifdef RX_ENABLE_LOCKS
1569 #endif /* RX_ENABLE_LOCKS */
1574 tservice = call->conn->service;
1576 if (tservice->beforeProc)
1577 (*tservice->beforeProc) (call);
1579 code = call->conn->service->executeRequestProc(call);
1581 if (tservice->afterProc)
1582 (*tservice->afterProc) (call, code);
1584 rx_EndCall(call, code);
1585 if (rx_stats_active)
1586 rx_MutexIncrement(rxi_nCalls, rx_stats_mutex);
1592 rx_WakeupServerProcs(void)
1594 struct rx_serverQueueEntry *np, *tqp;
1598 MUTEX_ENTER(&rx_serverPool_lock);
1600 #ifdef RX_ENABLE_LOCKS
1601 if (rx_waitForPacket)
1602 CV_BROADCAST(&rx_waitForPacket->cv);
1603 #else /* RX_ENABLE_LOCKS */
1604 if (rx_waitForPacket)
1605 osi_rxWakeup(rx_waitForPacket);
1606 #endif /* RX_ENABLE_LOCKS */
1607 MUTEX_ENTER(&freeSQEList_lock);
1608 for (np = rx_FreeSQEList; np; np = tqp) {
1609 tqp = *(struct rx_serverQueueEntry **)np;
1610 #ifdef RX_ENABLE_LOCKS
1611 CV_BROADCAST(&np->cv);
1612 #else /* RX_ENABLE_LOCKS */
1614 #endif /* RX_ENABLE_LOCKS */
1616 MUTEX_EXIT(&freeSQEList_lock);
1617 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1618 #ifdef RX_ENABLE_LOCKS
1619 CV_BROADCAST(&np->cv);
1620 #else /* RX_ENABLE_LOCKS */
1622 #endif /* RX_ENABLE_LOCKS */
1624 MUTEX_EXIT(&rx_serverPool_lock);
1629 * One thing that seems to happen is that all the server threads get
1630 * tied up on some empty or slow call, and then a whole bunch of calls
1631 * arrive at once, using up the packet pool, so now there are more
1632 * empty calls. The most critical resources here are server threads
1633 * and the free packet pool. The "doreclaim" code seems to help in
1634 * general. I think that eventually we arrive in this state: there
1635 * are lots of pending calls which do have all their packets present,
1636 * so they won't be reclaimed, are multi-packet calls, so they won't
1637 * be scheduled until later, and thus are tying up most of the free
1638 * packet pool for a very long time.
1640 * 1. schedule multi-packet calls if all the packets are present.
1641 * Probably CPU-bound operation, useful to return packets to pool.
1642 * Do what if there is a full window, but the last packet isn't here?
1643 * 3. preserve one thread which *only* runs "best" calls, otherwise
1644 * it sleeps and waits for that type of call.
1645 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1646 * the current dataquota business is badly broken. The quota isn't adjusted
1647 * to reflect how many packets are presently queued for a running call.
1648 * So, when we schedule a queued call with a full window of packets queued
1649 * up for it, that *should* free up a window full of packets for other 2d-class
1650 * calls to be able to use from the packet pool. But it doesn't.
1652 * NB. Most of the time, this code doesn't run -- since idle server threads
1653 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1654 * as a new call arrives.
1656 /* Sleep until a call arrives. Returns a pointer to the call, ready
1657 * for an rx_Read. */
1658 #ifdef RX_ENABLE_LOCKS
1660 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1662 struct rx_serverQueueEntry *sq;
1663 register struct rx_call *call = (struct rx_call *)0;
1664 struct rx_service *service = NULL;
1667 MUTEX_ENTER(&freeSQEList_lock);
1669 if ((sq = rx_FreeSQEList)) {
1670 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1671 MUTEX_EXIT(&freeSQEList_lock);
1672 } else { /* otherwise allocate a new one and return that */
1673 MUTEX_EXIT(&freeSQEList_lock);
1674 sq = (struct rx_serverQueueEntry *)
1675 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1676 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1677 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1680 MUTEX_ENTER(&rx_serverPool_lock);
1681 if (cur_service != NULL) {
1682 ReturnToServerPool(cur_service);
1685 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1686 register struct rx_call *tcall, *ncall, *choice2 = NULL;
1688 /* Scan for eligible incoming calls. A call is not eligible
1689 * if the maximum number of calls for its service type are
1690 * already executing */
1691 /* One thread will process calls FCFS (to prevent starvation),
1692 * while the other threads may run ahead looking for calls which
1693 * have all their input data available immediately. This helps
1694 * keep threads from blocking, waiting for data from the client. */
1695 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1696 service = tcall->conn->service;
1697 if (!QuotaOK(service)) {
1700 if (tno == rxi_fcfs_thread_num
1701 || !tcall->queue_item_header.next) {
1702 /* If we're the fcfs thread , then we'll just use
1703 * this call. If we haven't been able to find an optimal
1704 * choice, and we're at the end of the list, then use a
1705 * 2d choice if one has been identified. Otherwise... */
1706 call = (choice2 ? choice2 : tcall);
1707 service = call->conn->service;
1708 } else if (!queue_IsEmpty(&tcall->rq)) {
1709 struct rx_packet *rp;
1710 rp = queue_First(&tcall->rq, rx_packet);
1711 if (rp->header.seq == 1) {
1713 || (rp->header.flags & RX_LAST_PACKET)) {
1715 } else if (rxi_2dchoice && !choice2
1716 && !(tcall->flags & RX_CALL_CLEARED)
1717 && (tcall->rprev > rxi_HardAckRate)) {
1726 ReturnToServerPool(service);
1733 MUTEX_EXIT(&rx_serverPool_lock);
1734 MUTEX_ENTER(&call->lock);
1736 if (call->flags & RX_CALL_WAIT_PROC) {
1737 call->flags &= ~RX_CALL_WAIT_PROC;
1738 rx_MutexDecrement(rx_nWaiting, rx_waiting_mutex);
1741 if (call->state != RX_STATE_PRECALL || call->error) {
1742 MUTEX_EXIT(&call->lock);
1743 MUTEX_ENTER(&rx_serverPool_lock);
1744 ReturnToServerPool(service);
1749 if (queue_IsEmpty(&call->rq)
1750 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1751 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1753 CLEAR_CALL_QUEUE_LOCK(call);
1756 /* If there are no eligible incoming calls, add this process
1757 * to the idle server queue, to wait for one */
1761 *socketp = OSI_NULLSOCKET;
1763 sq->socketp = socketp;
1764 queue_Append(&rx_idleServerQueue, sq);
1765 #ifndef AFS_AIX41_ENV
1766 rx_waitForPacket = sq;
1768 rx_waitingForPacket = sq;
1769 #endif /* AFS_AIX41_ENV */
1771 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1773 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1774 MUTEX_EXIT(&rx_serverPool_lock);
1775 return (struct rx_call *)0;
1778 } while (!(call = sq->newcall)
1779 && !(socketp && *socketp != OSI_NULLSOCKET));
1780 MUTEX_EXIT(&rx_serverPool_lock);
1782 MUTEX_ENTER(&call->lock);
1788 MUTEX_ENTER(&freeSQEList_lock);
1789 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1790 rx_FreeSQEList = sq;
1791 MUTEX_EXIT(&freeSQEList_lock);
1794 clock_GetTime(&call->startTime);
1795 call->state = RX_STATE_ACTIVE;
1796 call->mode = RX_MODE_RECEIVING;
1797 #ifdef RX_KERNEL_TRACE
1798 if (ICL_SETACTIVE(afs_iclSetp)) {
1799 int glockOwner = ISAFS_GLOCK();
1802 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1803 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1810 rxi_calltrace(RX_CALL_START, call);
1811 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1812 call->conn->service->servicePort, call->conn->service->serviceId,
1815 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1816 MUTEX_EXIT(&call->lock);
1818 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1823 #else /* RX_ENABLE_LOCKS */
1825 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1827 struct rx_serverQueueEntry *sq;
1828 register struct rx_call *call = (struct rx_call *)0, *choice2;
1829 struct rx_service *service = NULL;
1833 MUTEX_ENTER(&freeSQEList_lock);
1835 if ((sq = rx_FreeSQEList)) {
1836 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1837 MUTEX_EXIT(&freeSQEList_lock);
1838 } else { /* otherwise allocate a new one and return that */
1839 MUTEX_EXIT(&freeSQEList_lock);
1840 sq = (struct rx_serverQueueEntry *)
1841 rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1842 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1843 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1845 MUTEX_ENTER(&sq->lock);
1847 if (cur_service != NULL) {
1848 cur_service->nRequestsRunning--;
1849 if (cur_service->nRequestsRunning < cur_service->minProcs)
1853 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1854 register struct rx_call *tcall, *ncall;
1855 /* Scan for eligible incoming calls. A call is not eligible
1856 * if the maximum number of calls for its service type are
1857 * already executing */
1858 /* One thread will process calls FCFS (to prevent starvation),
1859 * while the other threads may run ahead looking for calls which
1860 * have all their input data available immediately. This helps
1861 * keep threads from blocking, waiting for data from the client. */
1862 choice2 = (struct rx_call *)0;
1863 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1864 service = tcall->conn->service;
1865 if (QuotaOK(service)) {
1866 if (tno == rxi_fcfs_thread_num
1867 || !tcall->queue_item_header.next) {
1868 /* If we're the fcfs thread, then we'll just use
1869 * this call. If we haven't been able to find an optimal
1870 * choice, and we're at the end of the list, then use a
1871 * 2d choice if one has been identified. Otherwise... */
1872 call = (choice2 ? choice2 : tcall);
1873 service = call->conn->service;
1874 } else if (!queue_IsEmpty(&tcall->rq)) {
1875 struct rx_packet *rp;
1876 rp = queue_First(&tcall->rq, rx_packet);
1877 if (rp->header.seq == 1
1879 || (rp->header.flags & RX_LAST_PACKET))) {
1881 } else if (rxi_2dchoice && !choice2
1882 && !(tcall->flags & RX_CALL_CLEARED)
1883 && (tcall->rprev > rxi_HardAckRate)) {
1896 /* we can't schedule a call if there's no data!!! */
1897 /* send an ack if there's no data, if we're missing the
1898 * first packet, or we're missing something between first
1899 * and last -- there's a "hole" in the incoming data. */
1900 if (queue_IsEmpty(&call->rq)
1901 || queue_First(&call->rq, rx_packet)->header.seq != 1
1902 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1903 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1905 call->flags &= (~RX_CALL_WAIT_PROC);
1906 service->nRequestsRunning++;
1907 /* just started call in minProcs pool, need fewer to maintain
1909 if (service->nRequestsRunning <= service->minProcs)
1913 /* MUTEX_EXIT(&call->lock); */
1915 /* If there are no eligible incoming calls, add this process
1916 * to the idle server queue, to wait for one */
1919 *socketp = OSI_NULLSOCKET;
1921 sq->socketp = socketp;
1922 queue_Append(&rx_idleServerQueue, sq);
1926 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1928 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1929 return (struct rx_call *)0;
1932 } while (!(call = sq->newcall)
1933 && !(socketp && *socketp != OSI_NULLSOCKET));
1935 MUTEX_EXIT(&sq->lock);
1937 MUTEX_ENTER(&freeSQEList_lock);
1938 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1939 rx_FreeSQEList = sq;
1940 MUTEX_EXIT(&freeSQEList_lock);
1943 clock_GetTime(&call->startTime);
1944 call->state = RX_STATE_ACTIVE;
1945 call->mode = RX_MODE_RECEIVING;
1946 #ifdef RX_KERNEL_TRACE
1947 if (ICL_SETACTIVE(afs_iclSetp)) {
1948 int glockOwner = ISAFS_GLOCK();
1951 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1952 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1959 rxi_calltrace(RX_CALL_START, call);
1960 dpf(("rx_GetCall(port=%d, service=%d) ==> call %x\n",
1961 call->conn->service->servicePort, call->conn->service->serviceId,
1964 dpf(("rx_GetCall(socketp=0x%x, *socketp=0x%x)\n", socketp, *socketp));
1971 #endif /* RX_ENABLE_LOCKS */
1975 /* Establish a procedure to be called when a packet arrives for a
1976 * call. This routine will be called at most once after each call,
1977 * and will also be called if there is an error condition on the or
1978 * the call is complete. Used by multi rx to build a selection
1979 * function which determines which of several calls is likely to be a
1980 * good one to read from.
1981 * NOTE: the way this is currently implemented it is probably only a
1982 * good idea to (1) use it immediately after a newcall (clients only)
1983 * and (2) only use it once. Other uses currently void your warranty
1986 rx_SetArrivalProc(register struct rx_call *call,
1987 register void (*proc) (register struct rx_call * call,
1989 register int index),
1990 register void * handle, register int arg)
1992 call->arrivalProc = proc;
1993 call->arrivalProcHandle = handle;
1994 call->arrivalProcArg = arg;
1997 /* Call is finished (possibly prematurely). Return rc to the peer, if
1998 * appropriate, and return the final error code from the conversation
2002 rx_EndCall(register struct rx_call *call, afs_int32 rc)
2004 register struct rx_connection *conn = call->conn;
2005 register struct rx_service *service;
2011 dpf(("rx_EndCall(call %x rc %d error %d abortCode %d)\n", call, rc, call->error, call->abortCode));
2014 MUTEX_ENTER(&call->lock);
2016 if (rc == 0 && call->error == 0) {
2017 call->abortCode = 0;
2018 call->abortCount = 0;
2021 call->arrivalProc = (void (*)())0;
2022 if (rc && call->error == 0) {
2023 rxi_CallError(call, rc);
2024 /* Send an abort message to the peer if this error code has
2025 * only just been set. If it was set previously, assume the
2026 * peer has already been sent the error code or will request it
2028 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2030 if (conn->type == RX_SERVER_CONNECTION) {
2031 /* Make sure reply or at least dummy reply is sent */
2032 if (call->mode == RX_MODE_RECEIVING) {
2033 rxi_WriteProc(call, 0, 0);
2035 if (call->mode == RX_MODE_SENDING) {
2036 rxi_FlushWrite(call);
2038 service = conn->service;
2039 rxi_calltrace(RX_CALL_END, call);
2040 /* Call goes to hold state until reply packets are acknowledged */
2041 if (call->tfirst + call->nSoftAcked < call->tnext) {
2042 call->state = RX_STATE_HOLD;
2044 call->state = RX_STATE_DALLY;
2045 rxi_ClearTransmitQueue(call, 0);
2046 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2047 rxevent_Cancel(call->keepAliveEvent, call,
2048 RX_CALL_REFCOUNT_ALIVE);
2050 } else { /* Client connection */
2052 /* Make sure server receives input packets, in the case where
2053 * no reply arguments are expected */
2054 if ((call->mode == RX_MODE_SENDING)
2055 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2056 (void)rxi_ReadProc(call, &dummy, 1);
2059 /* If we had an outstanding delayed ack, be nice to the server
2060 * and force-send it now.
2062 if (call->delayedAckEvent) {
2063 rxevent_Cancel(call->delayedAckEvent, call,
2064 RX_CALL_REFCOUNT_DELAY);
2065 call->delayedAckEvent = NULL;
2066 rxi_SendDelayedAck(NULL, call, NULL);
2069 /* We need to release the call lock since it's lower than the
2070 * conn_call_lock and we don't want to hold the conn_call_lock
2071 * over the rx_ReadProc call. The conn_call_lock needs to be held
2072 * here for the case where rx_NewCall is perusing the calls on
2073 * the connection structure. We don't want to signal until
2074 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2075 * have checked this call, found it active and by the time it
2076 * goes to sleep, will have missed the signal.
2078 * Do not clear the RX_CONN_MAKECALL_WAITING flag as long as
2079 * there are threads waiting to use the conn object.
2081 MUTEX_EXIT(&call->lock);
2082 MUTEX_ENTER(&conn->conn_call_lock);
2083 MUTEX_ENTER(&call->lock);
2084 MUTEX_ENTER(&conn->conn_data_lock);
2085 conn->flags |= RX_CONN_BUSY;
2086 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2087 if (conn->makeCallWaiters == 0)
2088 conn->flags &= (~RX_CONN_MAKECALL_WAITING);
2089 MUTEX_EXIT(&conn->conn_data_lock);
2090 #ifdef RX_ENABLE_LOCKS
2091 CV_BROADCAST(&conn->conn_call_cv);
2096 #ifdef RX_ENABLE_LOCKS
2098 MUTEX_EXIT(&conn->conn_data_lock);
2100 #endif /* RX_ENABLE_LOCKS */
2101 call->state = RX_STATE_DALLY;
2103 error = call->error;
2105 /* currentPacket, nLeft, and NFree must be zeroed here, because
2106 * ResetCall cannot: ResetCall may be called at splnet(), in the
2107 * kernel version, and may interrupt the macros rx_Read or
2108 * rx_Write, which run at normal priority for efficiency. */
2109 if (call->currentPacket) {
2110 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2111 rxi_FreePacket(call->currentPacket);
2112 call->currentPacket = (struct rx_packet *)0;
2115 call->nLeft = call->nFree = call->curlen = 0;
2117 /* Free any packets from the last call to ReadvProc/WritevProc */
2118 #ifdef RXDEBUG_PACKET
2120 #endif /* RXDEBUG_PACKET */
2121 rxi_FreePackets(0, &call->iovq);
2123 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2124 MUTEX_EXIT(&call->lock);
2125 if (conn->type == RX_CLIENT_CONNECTION) {
2126 MUTEX_EXIT(&conn->conn_call_lock);
2127 conn->flags &= ~RX_CONN_BUSY;
2131 * Map errors to the local host's errno.h format.
2133 error = ntoh_syserr_conv(error);
2137 #if !defined(KERNEL)
2139 /* Call this routine when shutting down a server or client (especially
2140 * clients). This will allow Rx to gracefully garbage collect server
2141 * connections, and reduce the number of retries that a server might
2142 * make to a dead client.
2143 * This is not quite right, since some calls may still be ongoing and
2144 * we can't lock them to destroy them. */
2148 register struct rx_connection **conn_ptr, **conn_end;
2152 if (rxinit_status == 1) {
2154 return; /* Already shutdown. */
2156 rxi_DeleteCachedConnections();
2157 if (rx_connHashTable) {
2158 MUTEX_ENTER(&rx_connHashTable_lock);
2159 for (conn_ptr = &rx_connHashTable[0], conn_end =
2160 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2162 struct rx_connection *conn, *next;
2163 for (conn = *conn_ptr; conn; conn = next) {
2165 if (conn->type == RX_CLIENT_CONNECTION) {
2166 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2168 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2169 #ifdef RX_ENABLE_LOCKS
2170 rxi_DestroyConnectionNoLock(conn);
2171 #else /* RX_ENABLE_LOCKS */
2172 rxi_DestroyConnection(conn);
2173 #endif /* RX_ENABLE_LOCKS */
2177 #ifdef RX_ENABLE_LOCKS
2178 while (rx_connCleanup_list) {
2179 struct rx_connection *conn;
2180 conn = rx_connCleanup_list;
2181 rx_connCleanup_list = rx_connCleanup_list->next;
2182 MUTEX_EXIT(&rx_connHashTable_lock);
2183 rxi_CleanupConnection(conn);
2184 MUTEX_ENTER(&rx_connHashTable_lock);
2186 MUTEX_EXIT(&rx_connHashTable_lock);
2187 #endif /* RX_ENABLE_LOCKS */
2192 afs_winsockCleanup();
2200 /* if we wakeup packet waiter too often, can get in loop with two
2201 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2203 rxi_PacketsUnWait(void)
2205 if (!rx_waitingForPackets) {
2209 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2210 return; /* still over quota */
2213 rx_waitingForPackets = 0;
2214 #ifdef RX_ENABLE_LOCKS
2215 CV_BROADCAST(&rx_waitingForPackets_cv);
2217 osi_rxWakeup(&rx_waitingForPackets);
2223 /* ------------------Internal interfaces------------------------- */
2225 /* Return this process's service structure for the
2226 * specified socket and service */
2228 rxi_FindService(register osi_socket socket, register u_short serviceId)
2230 register struct rx_service **sp;
2231 for (sp = &rx_services[0]; *sp; sp++) {
2232 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2239 #ifdef KDUMP_RX_LOCK
2240 static struct rx_call_rx_lock *rx_allCallsp = 0;
2242 static struct rx_call *rx_allCallsp = 0;
2246 /* Allocate a call structure, for the indicated channel of the
2247 * supplied connection. The mode and state of the call must be set by
2248 * the caller. Returns the call with mutex locked. */
2250 rxi_NewCall(register struct rx_connection *conn, register int channel)
2252 register struct rx_call *call;
2253 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2254 register struct rx_call *cp; /* Call pointer temp */
2255 register struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2256 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2258 dpf(("rxi_NewCall(conn %x, channel %d)\n", conn, channel));
2260 /* Grab an existing call structure, or allocate a new one.
2261 * Existing call structures are assumed to have been left reset by
2263 MUTEX_ENTER(&rx_freeCallQueue_lock);
2265 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2267 * EXCEPT that the TQ might not yet be cleared out.
2268 * Skip over those with in-use TQs.
2271 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2272 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2278 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2279 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2280 call = queue_First(&rx_freeCallQueue, rx_call);
2281 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2283 if (rx_stats_active)
2284 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2285 MUTEX_EXIT(&rx_freeCallQueue_lock);
2286 MUTEX_ENTER(&call->lock);
2287 CLEAR_CALL_QUEUE_LOCK(call);
2288 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2289 /* Now, if TQ wasn't cleared earlier, do it now. */
2290 if (call->flags & RX_CALL_TQ_CLEARME) {
2291 rxi_ClearTransmitQueue(call, 1);
2292 /*queue_Init(&call->tq);*/
2294 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2295 /* Bind the call to its connection structure */
2297 rxi_ResetCall(call, 1);
2300 call = (struct rx_call *)rxi_Alloc(sizeof(struct rx_call));
2301 #ifdef RXDEBUG_PACKET
2302 call->allNextp = rx_allCallsp;
2303 rx_allCallsp = call;
2305 #endif /* RXDEBUG_PACKET */
2306 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2308 MUTEX_EXIT(&rx_freeCallQueue_lock);
2309 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2310 MUTEX_ENTER(&call->lock);
2311 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2312 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2313 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2315 /* Initialize once-only items */
2316 queue_Init(&call->tq);
2317 queue_Init(&call->rq);
2318 queue_Init(&call->iovq);
2319 #ifdef RXDEBUG_PACKET
2320 call->rqc = call->tqc = call->iovqc = 0;
2321 #endif /* RXDEBUG_PACKET */
2322 /* Bind the call to its connection structure (prereq for reset) */
2324 rxi_ResetCall(call, 1);
2326 call->channel = channel;
2327 call->callNumber = &conn->callNumber[channel];
2328 call->rwind = conn->rwind[channel];
2329 call->twind = conn->twind[channel];
2330 /* Note that the next expected call number is retained (in
2331 * conn->callNumber[i]), even if we reallocate the call structure
2333 conn->call[channel] = call;
2334 /* if the channel's never been used (== 0), we should start at 1, otherwise
2335 * the call number is valid from the last time this channel was used */
2336 if (*call->callNumber == 0)
2337 *call->callNumber = 1;
2342 /* A call has been inactive long enough that so we can throw away
2343 * state, including the call structure, which is placed on the call
2345 * Call is locked upon entry.
2346 * haveCTLock set if called from rxi_ReapConnections
2348 #ifdef RX_ENABLE_LOCKS
2350 rxi_FreeCall(register struct rx_call *call, int haveCTLock)
2351 #else /* RX_ENABLE_LOCKS */
2353 rxi_FreeCall(register struct rx_call *call)
2354 #endif /* RX_ENABLE_LOCKS */
2356 register int channel = call->channel;
2357 register struct rx_connection *conn = call->conn;
2360 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2361 (*call->callNumber)++;
2362 rxi_ResetCall(call, 0);
2363 call->conn->call[channel] = (struct rx_call *)0;
2365 MUTEX_ENTER(&rx_freeCallQueue_lock);
2366 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2367 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2368 /* A call may be free even though its transmit queue is still in use.
2369 * Since we search the call list from head to tail, put busy calls at
2370 * the head of the list, and idle calls at the tail.
2372 if (call->flags & RX_CALL_TQ_BUSY)
2373 queue_Prepend(&rx_freeCallQueue, call);
2375 queue_Append(&rx_freeCallQueue, call);
2376 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2377 queue_Append(&rx_freeCallQueue, call);
2378 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2379 if (rx_stats_active)
2380 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2381 MUTEX_EXIT(&rx_freeCallQueue_lock);
2383 /* Destroy the connection if it was previously slated for
2384 * destruction, i.e. the Rx client code previously called
2385 * rx_DestroyConnection (client connections), or
2386 * rxi_ReapConnections called the same routine (server
2387 * connections). Only do this, however, if there are no
2388 * outstanding calls. Note that for fine grain locking, there appears
2389 * to be a deadlock in that rxi_FreeCall has a call locked and
2390 * DestroyConnectionNoLock locks each call in the conn. But note a
2391 * few lines up where we have removed this call from the conn.
2392 * If someone else destroys a connection, they either have no
2393 * call lock held or are going through this section of code.
2395 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2396 rx_MutexIncrement(conn->refCount, conn->conn_data_lock);
2397 #ifdef RX_ENABLE_LOCKS
2399 rxi_DestroyConnectionNoLock(conn);
2401 rxi_DestroyConnection(conn);
2402 #else /* RX_ENABLE_LOCKS */
2403 rxi_DestroyConnection(conn);
2404 #endif /* RX_ENABLE_LOCKS */
2408 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2410 rxi_Alloc(register size_t size)
2414 if (rx_stats_active)
2415 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2418 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2419 afs_osi_Alloc_NoSleep(size);
2424 osi_Panic("rxi_Alloc error");
2430 rxi_Free(void *addr, register size_t size)
2432 if (rx_stats_active)
2433 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2434 osi_Free(addr, size);
2438 rxi_SetPeerMtu(register afs_uint32 host, register afs_uint32 port, int mtu)
2440 struct rx_peer **peer_ptr, **peer_end;
2443 MUTEX_ENTER(&rx_peerHashTable_lock);
2445 for (peer_ptr = &rx_peerHashTable[0], peer_end =
2446 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
2448 struct rx_peer *peer, *next;
2449 for (peer = *peer_ptr; peer; peer = next) {
2451 if (host == peer->host) {
2452 MUTEX_ENTER(&peer->peer_lock);
2453 peer->ifMTU=MIN(mtu, peer->ifMTU);
2454 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2455 MUTEX_EXIT(&peer->peer_lock);
2460 struct rx_peer *peer;
2461 hashIndex = PEER_HASH(host, port);
2462 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2463 if ((peer->host == host) && (peer->port == port)) {
2464 MUTEX_ENTER(&peer->peer_lock);
2465 peer->ifMTU=MIN(mtu, peer->ifMTU);
2466 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2467 MUTEX_EXIT(&peer->peer_lock);
2471 MUTEX_EXIT(&rx_peerHashTable_lock);
2474 /* Find the peer process represented by the supplied (host,port)
2475 * combination. If there is no appropriate active peer structure, a
2476 * new one will be allocated and initialized
2477 * The origPeer, if set, is a pointer to a peer structure on which the
2478 * refcount will be be decremented. This is used to replace the peer
2479 * structure hanging off a connection structure */
2481 rxi_FindPeer(register afs_uint32 host, register u_short port,
2482 struct rx_peer *origPeer, int create)
2484 register struct rx_peer *pp;
2486 hashIndex = PEER_HASH(host, port);
2487 MUTEX_ENTER(&rx_peerHashTable_lock);
2488 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2489 if ((pp->host == host) && (pp->port == port))
2494 pp = rxi_AllocPeer(); /* This bzero's *pp */
2495 pp->host = host; /* set here or in InitPeerParams is zero */
2497 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2498 queue_Init(&pp->congestionQueue);
2499 queue_Init(&pp->rpcStats);
2500 pp->next = rx_peerHashTable[hashIndex];
2501 rx_peerHashTable[hashIndex] = pp;
2502 rxi_InitPeerParams(pp);
2503 if (rx_stats_active)
2504 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2511 origPeer->refCount--;
2512 MUTEX_EXIT(&rx_peerHashTable_lock);
2517 /* Find the connection at (host, port) started at epoch, and with the
2518 * given connection id. Creates the server connection if necessary.
2519 * The type specifies whether a client connection or a server
2520 * connection is desired. In both cases, (host, port) specify the
2521 * peer's (host, pair) pair. Client connections are not made
2522 * automatically by this routine. The parameter socket gives the
2523 * socket descriptor on which the packet was received. This is used,
2524 * in the case of server connections, to check that *new* connections
2525 * come via a valid (port, serviceId). Finally, the securityIndex
2526 * parameter must match the existing index for the connection. If a
2527 * server connection is created, it will be created using the supplied
2528 * index, if the index is valid for this service */
2529 struct rx_connection *
2530 rxi_FindConnection(osi_socket socket, register afs_int32 host,
2531 register u_short port, u_short serviceId, afs_uint32 cid,
2532 afs_uint32 epoch, int type, u_int securityIndex)
2534 int hashindex, flag, i;
2535 register struct rx_connection *conn;
2536 hashindex = CONN_HASH(host, port, cid, epoch, type);
2537 MUTEX_ENTER(&rx_connHashTable_lock);
2538 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2539 rx_connHashTable[hashindex],
2542 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2543 && (epoch == conn->epoch)) {
2544 register struct rx_peer *pp = conn->peer;
2545 if (securityIndex != conn->securityIndex) {
2546 /* this isn't supposed to happen, but someone could forge a packet
2547 * like this, and there seems to be some CM bug that makes this
2548 * happen from time to time -- in which case, the fileserver
2550 MUTEX_EXIT(&rx_connHashTable_lock);
2551 return (struct rx_connection *)0;
2553 if (pp->host == host && pp->port == port)
2555 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2557 /* So what happens when it's a callback connection? */
2558 if ( /*type == RX_CLIENT_CONNECTION && */
2559 (conn->epoch & 0x80000000))
2563 /* the connection rxLastConn that was used the last time is not the
2564 ** one we are looking for now. Hence, start searching in the hash */
2566 conn = rx_connHashTable[hashindex];
2571 struct rx_service *service;
2572 if (type == RX_CLIENT_CONNECTION) {
2573 MUTEX_EXIT(&rx_connHashTable_lock);
2574 return (struct rx_connection *)0;
2576 service = rxi_FindService(socket, serviceId);
2577 if (!service || (securityIndex >= service->nSecurityObjects)
2578 || (service->securityObjects[securityIndex] == 0)) {
2579 MUTEX_EXIT(&rx_connHashTable_lock);
2580 return (struct rx_connection *)0;
2582 conn = rxi_AllocConnection(); /* This bzero's the connection */
2583 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2584 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2585 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2586 conn->next = rx_connHashTable[hashindex];
2587 rx_connHashTable[hashindex] = conn;
2588 conn->peer = rxi_FindPeer(host, port, 0, 1);
2589 conn->type = RX_SERVER_CONNECTION;
2590 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2591 conn->epoch = epoch;
2592 conn->cid = cid & RX_CIDMASK;
2593 /* conn->serial = conn->lastSerial = 0; */
2594 /* conn->timeout = 0; */
2595 conn->ackRate = RX_FAST_ACK_RATE;
2596 conn->service = service;
2597 conn->serviceId = serviceId;
2598 conn->securityIndex = securityIndex;
2599 conn->securityObject = service->securityObjects[securityIndex];
2600 conn->nSpecific = 0;
2601 conn->specific = NULL;
2602 rx_SetConnDeadTime(conn, service->connDeadTime);
2603 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2604 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2605 for (i = 0; i < RX_MAXCALLS; i++) {
2606 conn->twind[i] = rx_initSendWindow;
2607 conn->rwind[i] = rx_initReceiveWindow;
2609 /* Notify security object of the new connection */
2610 RXS_NewConnection(conn->securityObject, conn);
2611 /* XXXX Connection timeout? */
2612 if (service->newConnProc)
2613 (*service->newConnProc) (conn);
2614 if (rx_stats_active)
2615 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2618 rx_MutexIncrement(conn->refCount, conn->conn_data_lock);
2620 rxLastConn = conn; /* store this connection as the last conn used */
2621 MUTEX_EXIT(&rx_connHashTable_lock);
2625 /* There are two packet tracing routines available for testing and monitoring
2626 * Rx. One is called just after every packet is received and the other is
2627 * called just before every packet is sent. Received packets, have had their
2628 * headers decoded, and packets to be sent have not yet had their headers
2629 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2630 * containing the network address. Both can be modified. The return value, if
2631 * non-zero, indicates that the packet should be dropped. */
2633 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2634 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2636 /* A packet has been received off the interface. Np is the packet, socket is
2637 * the socket number it was received from (useful in determining which service
2638 * this packet corresponds to), and (host, port) reflect the host,port of the
2639 * sender. This call returns the packet to the caller if it is finished with
2640 * it, rather than de-allocating it, just as a small performance hack */
2643 rxi_ReceivePacket(register struct rx_packet *np, osi_socket socket,
2644 afs_uint32 host, u_short port, int *tnop,
2645 struct rx_call **newcallp)
2647 register struct rx_call *call;
2648 register struct rx_connection *conn;
2650 afs_uint32 currentCallNumber;
2656 struct rx_packet *tnp;
2659 /* We don't print out the packet until now because (1) the time may not be
2660 * accurate enough until now in the lwp implementation (rx_Listener only gets
2661 * the time after the packet is read) and (2) from a protocol point of view,
2662 * this is the first time the packet has been seen */
2663 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2664 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2665 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %x",
2666 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2667 np->header.epoch, np->header.cid, np->header.callNumber,
2668 np->header.seq, np->header.flags, np));
2671 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2672 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2675 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2676 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2679 /* If an input tracer function is defined, call it with the packet and
2680 * network address. Note this function may modify its arguments. */
2681 if (rx_justReceived) {
2682 struct sockaddr_in addr;
2684 addr.sin_family = AF_INET;
2685 addr.sin_port = port;
2686 addr.sin_addr.s_addr = host;
2687 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2688 addr.sin_len = sizeof(addr);
2689 #endif /* AFS_OSF_ENV */
2690 drop = (*rx_justReceived) (np, &addr);
2691 /* drop packet if return value is non-zero */
2694 port = addr.sin_port; /* in case fcn changed addr */
2695 host = addr.sin_addr.s_addr;
2699 /* If packet was not sent by the client, then *we* must be the client */
2700 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2701 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2703 /* Find the connection (or fabricate one, if we're the server & if
2704 * necessary) associated with this packet */
2706 rxi_FindConnection(socket, host, port, np->header.serviceId,
2707 np->header.cid, np->header.epoch, type,
2708 np->header.securityIndex);
2711 /* If no connection found or fabricated, just ignore the packet.
2712 * (An argument could be made for sending an abort packet for
2717 MUTEX_ENTER(&conn->conn_data_lock);
2718 if (conn->maxSerial < np->header.serial)
2719 conn->maxSerial = np->header.serial;
2720 MUTEX_EXIT(&conn->conn_data_lock);
2722 /* If the connection is in an error state, send an abort packet and ignore
2723 * the incoming packet */
2724 if (rx_ConnError(conn)) {
2725 /* Don't respond to an abort packet--we don't want loops! */
2726 MUTEX_ENTER(&conn->conn_data_lock);
2727 if (np->header.type != RX_PACKET_TYPE_ABORT)
2728 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2730 MUTEX_EXIT(&conn->conn_data_lock);
2734 /* Check for connection-only requests (i.e. not call specific). */
2735 if (np->header.callNumber == 0) {
2736 switch (np->header.type) {
2737 case RX_PACKET_TYPE_ABORT: {
2738 /* What if the supplied error is zero? */
2739 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2740 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2741 rxi_ConnectionError(conn, errcode);
2742 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2745 case RX_PACKET_TYPE_CHALLENGE:
2746 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2747 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2749 case RX_PACKET_TYPE_RESPONSE:
2750 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2751 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2753 case RX_PACKET_TYPE_PARAMS:
2754 case RX_PACKET_TYPE_PARAMS + 1:
2755 case RX_PACKET_TYPE_PARAMS + 2:
2756 /* ignore these packet types for now */
2757 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2762 /* Should not reach here, unless the peer is broken: send an
2764 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2765 MUTEX_ENTER(&conn->conn_data_lock);
2766 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2768 MUTEX_EXIT(&conn->conn_data_lock);
2773 channel = np->header.cid & RX_CHANNELMASK;
2774 call = conn->call[channel];
2775 #ifdef RX_ENABLE_LOCKS
2777 MUTEX_ENTER(&call->lock);
2778 /* Test to see if call struct is still attached to conn. */
2779 if (call != conn->call[channel]) {
2781 MUTEX_EXIT(&call->lock);
2782 if (type == RX_SERVER_CONNECTION) {
2783 call = conn->call[channel];
2784 /* If we started with no call attached and there is one now,
2785 * another thread is also running this routine and has gotten
2786 * the connection channel. We should drop this packet in the tests
2787 * below. If there was a call on this connection and it's now
2788 * gone, then we'll be making a new call below.
2789 * If there was previously a call and it's now different then
2790 * the old call was freed and another thread running this routine
2791 * has created a call on this channel. One of these two threads
2792 * has a packet for the old call and the code below handles those
2796 MUTEX_ENTER(&call->lock);
2798 /* This packet can't be for this call. If the new call address is
2799 * 0 then no call is running on this channel. If there is a call
2800 * then, since this is a client connection we're getting data for
2801 * it must be for the previous call.
2803 if (rx_stats_active)
2804 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2805 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2810 currentCallNumber = conn->callNumber[channel];
2812 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2813 if (np->header.callNumber < currentCallNumber) {
2814 if (rx_stats_active)
2815 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2816 #ifdef RX_ENABLE_LOCKS
2818 MUTEX_EXIT(&call->lock);
2820 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2824 MUTEX_ENTER(&conn->conn_call_lock);
2825 call = rxi_NewCall(conn, channel);
2826 MUTEX_EXIT(&conn->conn_call_lock);
2827 *call->callNumber = np->header.callNumber;
2828 if (np->header.callNumber == 0)
2829 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));
2831 call->state = RX_STATE_PRECALL;
2832 clock_GetTime(&call->queueTime);
2833 hzero(call->bytesSent);
2834 hzero(call->bytesRcvd);
2836 * If the number of queued calls exceeds the overload
2837 * threshold then abort this call.
2839 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2840 struct rx_packet *tp;
2842 rxi_CallError(call, rx_BusyError);
2843 tp = rxi_SendCallAbort(call, np, 1, 0);
2844 MUTEX_EXIT(&call->lock);
2845 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2846 if (rx_stats_active)
2847 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2850 rxi_KeepAliveOn(call);
2851 } else if (np->header.callNumber != currentCallNumber) {
2852 /* Wait until the transmit queue is idle before deciding
2853 * whether to reset the current call. Chances are that the
2854 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2857 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2858 while ((call->state == RX_STATE_ACTIVE)
2859 && (call->flags & RX_CALL_TQ_BUSY)) {
2860 call->flags |= RX_CALL_TQ_WAIT;
2862 #ifdef RX_ENABLE_LOCKS
2863 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2864 CV_WAIT(&call->cv_tq, &call->lock);
2865 #else /* RX_ENABLE_LOCKS */
2866 osi_rxSleep(&call->tq);
2867 #endif /* RX_ENABLE_LOCKS */
2869 if (call->tqWaiters == 0)
2870 call->flags &= ~RX_CALL_TQ_WAIT;
2872 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2873 /* If the new call cannot be taken right now send a busy and set
2874 * the error condition in this call, so that it terminates as
2875 * quickly as possible */
2876 if (call->state == RX_STATE_ACTIVE) {
2877 struct rx_packet *tp;
2879 rxi_CallError(call, RX_CALL_DEAD);
2880 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2882 MUTEX_EXIT(&call->lock);
2883 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2886 rxi_ResetCall(call, 0);
2887 *call->callNumber = np->header.callNumber;
2888 if (np->header.callNumber == 0)
2889 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));
2891 call->state = RX_STATE_PRECALL;
2892 clock_GetTime(&call->queueTime);
2893 hzero(call->bytesSent);
2894 hzero(call->bytesRcvd);
2896 * If the number of queued calls exceeds the overload
2897 * threshold then abort this call.
2899 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2900 struct rx_packet *tp;
2902 rxi_CallError(call, rx_BusyError);
2903 tp = rxi_SendCallAbort(call, np, 1, 0);
2904 MUTEX_EXIT(&call->lock);
2905 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2906 if (rx_stats_active)
2907 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2910 rxi_KeepAliveOn(call);
2912 /* Continuing call; do nothing here. */
2914 } else { /* we're the client */
2915 /* Ignore all incoming acknowledgements for calls in DALLY state */
2916 if (call && (call->state == RX_STATE_DALLY)
2917 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2918 if (rx_stats_active)
2919 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2920 #ifdef RX_ENABLE_LOCKS
2922 MUTEX_EXIT(&call->lock);
2925 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2929 /* Ignore anything that's not relevant to the current call. If there
2930 * isn't a current call, then no packet is relevant. */
2931 if (!call || (np->header.callNumber != currentCallNumber)) {
2932 if (rx_stats_active)
2933 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2934 #ifdef RX_ENABLE_LOCKS
2936 MUTEX_EXIT(&call->lock);
2939 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2942 /* If the service security object index stamped in the packet does not
2943 * match the connection's security index, ignore the packet */
2944 if (np->header.securityIndex != conn->securityIndex) {
2945 #ifdef RX_ENABLE_LOCKS
2946 MUTEX_EXIT(&call->lock);
2948 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
2952 /* If we're receiving the response, then all transmit packets are
2953 * implicitly acknowledged. Get rid of them. */
2954 if (np->header.type == RX_PACKET_TYPE_DATA) {
2955 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2956 /* XXX Hack. Because we must release the global rx lock when
2957 * sending packets (osi_NetSend) we drop all acks while we're
2958 * traversing the tq in rxi_Start sending packets out because
2959 * packets may move to the freePacketQueue as result of being here!
2960 * So we drop these packets until we're safely out of the
2961 * traversing. Really ugly!
2962 * For fine grain RX locking, we set the acked field in the
2963 * packets and let rxi_Start remove them from the transmit queue.
2965 if (call->flags & RX_CALL_TQ_BUSY) {
2966 #ifdef RX_ENABLE_LOCKS
2967 rxi_SetAcksInTransmitQueue(call);
2970 return np; /* xmitting; drop packet */
2973 rxi_ClearTransmitQueue(call, 0);
2975 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2976 rxi_ClearTransmitQueue(call, 0);
2977 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2979 if (np->header.type == RX_PACKET_TYPE_ACK) {
2980 /* now check to see if this is an ack packet acknowledging that the
2981 * server actually *lost* some hard-acked data. If this happens we
2982 * ignore this packet, as it may indicate that the server restarted in
2983 * the middle of a call. It is also possible that this is an old ack
2984 * packet. We don't abort the connection in this case, because this
2985 * *might* just be an old ack packet. The right way to detect a server
2986 * restart in the midst of a call is to notice that the server epoch
2988 /* XXX I'm not sure this is exactly right, since tfirst **IS**
2989 * XXX unacknowledged. I think that this is off-by-one, but
2990 * XXX I don't dare change it just yet, since it will
2991 * XXX interact badly with the server-restart detection
2992 * XXX code in receiveackpacket. */
2993 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
2994 if (rx_stats_active)
2995 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2996 MUTEX_EXIT(&call->lock);
2997 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3001 } /* else not a data packet */
3004 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3005 /* Set remote user defined status from packet */
3006 call->remoteStatus = np->header.userStatus;
3008 /* Note the gap between the expected next packet and the actual
3009 * packet that arrived, when the new packet has a smaller serial number
3010 * than expected. Rioses frequently reorder packets all by themselves,
3011 * so this will be quite important with very large window sizes.
3012 * Skew is checked against 0 here to avoid any dependence on the type of
3013 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3015 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3016 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3017 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3019 MUTEX_ENTER(&conn->conn_data_lock);
3020 skew = conn->lastSerial - np->header.serial;
3021 conn->lastSerial = np->header.serial;
3022 MUTEX_EXIT(&conn->conn_data_lock);
3024 register struct rx_peer *peer;
3026 if (skew > peer->inPacketSkew) {
3027 dpf(("*** In skew changed from %d to %d\n", peer->inPacketSkew,
3029 peer->inPacketSkew = skew;
3033 /* Now do packet type-specific processing */
3034 switch (np->header.type) {
3035 case RX_PACKET_TYPE_DATA:
3036 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3039 case RX_PACKET_TYPE_ACK:
3040 /* Respond immediately to ack packets requesting acknowledgement
3042 if (np->header.flags & RX_REQUEST_ACK) {
3044 (void)rxi_SendCallAbort(call, 0, 1, 0);
3046 (void)rxi_SendAck(call, 0, np->header.serial,
3047 RX_ACK_PING_RESPONSE, 1);
3049 np = rxi_ReceiveAckPacket(call, np, 1);
3051 case RX_PACKET_TYPE_ABORT: {
3052 /* An abort packet: reset the call, passing the error up to the user. */
3053 /* What if error is zero? */
3054 /* What if the error is -1? the application will treat it as a timeout. */
3055 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3056 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3057 rxi_CallError(call, errdata);
3058 MUTEX_EXIT(&call->lock);
3059 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3060 return np; /* xmitting; drop packet */
3062 case RX_PACKET_TYPE_BUSY:
3065 case RX_PACKET_TYPE_ACKALL:
3066 /* All packets acknowledged, so we can drop all packets previously
3067 * readied for sending */
3068 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3069 /* XXX Hack. We because we can't release the global rx lock when
3070 * sending packets (osi_NetSend) we drop all ack pkts while we're
3071 * traversing the tq in rxi_Start sending packets out because
3072 * packets may move to the freePacketQueue as result of being
3073 * here! So we drop these packets until we're safely out of the
3074 * traversing. Really ugly!
3075 * For fine grain RX locking, we set the acked field in the packets
3076 * and let rxi_Start remove the packets from the transmit queue.
3078 if (call->flags & RX_CALL_TQ_BUSY) {
3079 #ifdef RX_ENABLE_LOCKS
3080 rxi_SetAcksInTransmitQueue(call);
3082 #else /* RX_ENABLE_LOCKS */
3083 MUTEX_EXIT(&call->lock);
3084 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3085 return np; /* xmitting; drop packet */
3086 #endif /* RX_ENABLE_LOCKS */
3088 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3089 rxi_ClearTransmitQueue(call, 0);
3090 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3093 /* Should not reach here, unless the peer is broken: send an abort
3095 rxi_CallError(call, RX_PROTOCOL_ERROR);
3096 np = rxi_SendCallAbort(call, np, 1, 0);
3099 /* Note when this last legitimate packet was received, for keep-alive
3100 * processing. Note, we delay getting the time until now in the hope that
3101 * the packet will be delivered to the user before any get time is required
3102 * (if not, then the time won't actually be re-evaluated here). */
3103 call->lastReceiveTime = clock_Sec();
3104 MUTEX_EXIT(&call->lock);
3105 rx_MutexDecrement(conn->refCount, conn->conn_data_lock);
3109 /* return true if this is an "interesting" connection from the point of view
3110 of someone trying to debug the system */
3112 rxi_IsConnInteresting(struct rx_connection *aconn)
3115 register struct rx_call *tcall;
3117 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3119 for (i = 0; i < RX_MAXCALLS; i++) {
3120 tcall = aconn->call[i];
3122 if ((tcall->state == RX_STATE_PRECALL)
3123 || (tcall->state == RX_STATE_ACTIVE))
3125 if ((tcall->mode == RX_MODE_SENDING)
3126 || (tcall->mode == RX_MODE_RECEIVING))
3134 /* if this is one of the last few packets AND it wouldn't be used by the
3135 receiving call to immediately satisfy a read request, then drop it on
3136 the floor, since accepting it might prevent a lock-holding thread from
3137 making progress in its reading. If a call has been cleared while in
3138 the precall state then ignore all subsequent packets until the call
3139 is assigned to a thread. */
3142 TooLow(struct rx_packet *ap, struct rx_call *acall)
3146 MUTEX_ENTER(&rx_quota_mutex);
3147 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3148 && (acall->state == RX_STATE_PRECALL))
3149 || ((rx_nFreePackets < rxi_dataQuota + 2)
3150 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3151 && (acall->flags & RX_CALL_READER_WAIT)))) {
3154 MUTEX_EXIT(&rx_quota_mutex);
3160 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3162 struct rx_connection *conn = arg1;
3163 struct rx_call *acall = arg2;
3164 struct rx_call *call = acall;
3165 struct clock when, now;
3168 MUTEX_ENTER(&conn->conn_data_lock);
3169 conn->checkReachEvent = NULL;
3170 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3173 MUTEX_EXIT(&conn->conn_data_lock);
3177 MUTEX_ENTER(&conn->conn_call_lock);
3178 MUTEX_ENTER(&conn->conn_data_lock);
3179 for (i = 0; i < RX_MAXCALLS; i++) {
3180 struct rx_call *tc = conn->call[i];
3181 if (tc && tc->state == RX_STATE_PRECALL) {
3187 /* Indicate that rxi_CheckReachEvent is no longer running by
3188 * clearing the flag. Must be atomic under conn_data_lock to
3189 * avoid a new call slipping by: rxi_CheckConnReach holds
3190 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3192 conn->flags &= ~RX_CONN_ATTACHWAIT;
3193 MUTEX_EXIT(&conn->conn_data_lock);
3194 MUTEX_EXIT(&conn->conn_call_lock);
3199 MUTEX_ENTER(&call->lock);
3200 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3202 MUTEX_EXIT(&call->lock);
3204 clock_GetTime(&now);
3206 when.sec += RX_CHECKREACH_TIMEOUT;
3207 MUTEX_ENTER(&conn->conn_data_lock);
3208 if (!conn->checkReachEvent) {
3210 conn->checkReachEvent =
3211 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3214 MUTEX_EXIT(&conn->conn_data_lock);
3220 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3222 struct rx_service *service = conn->service;
3223 struct rx_peer *peer = conn->peer;
3224 afs_uint32 now, lastReach;
3226 if (service->checkReach == 0)
3230 MUTEX_ENTER(&peer->peer_lock);
3231 lastReach = peer->lastReachTime;
3232 MUTEX_EXIT(&peer->peer_lock);
3233 if (now - lastReach < RX_CHECKREACH_TTL)
3236 MUTEX_ENTER(&conn->conn_data_lock);
3237 if (conn->flags & RX_CONN_ATTACHWAIT) {
3238 MUTEX_EXIT(&conn->conn_data_lock);
3241 conn->flags |= RX_CONN_ATTACHWAIT;
3242 MUTEX_EXIT(&conn->conn_data_lock);
3243 if (!conn->checkReachEvent)
3244 rxi_CheckReachEvent(NULL, conn, call);
3249 /* try to attach call, if authentication is complete */
3251 TryAttach(register struct rx_call *acall, register osi_socket socket,
3252 register int *tnop, register struct rx_call **newcallp,
3255 struct rx_connection *conn = acall->conn;
3257 if (conn->type == RX_SERVER_CONNECTION
3258 && acall->state == RX_STATE_PRECALL) {
3259 /* Don't attach until we have any req'd. authentication. */
3260 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3261 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3262 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3263 /* Note: this does not necessarily succeed; there
3264 * may not any proc available
3267 rxi_ChallengeOn(acall->conn);
3272 /* A data packet has been received off the interface. This packet is
3273 * appropriate to the call (the call is in the right state, etc.). This
3274 * routine can return a packet to the caller, for re-use */
3277 rxi_ReceiveDataPacket(register struct rx_call *call,
3278 register struct rx_packet *np, int istack,
3279 osi_socket socket, afs_uint32 host, u_short port,
3280 int *tnop, struct rx_call **newcallp)
3282 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3286 afs_uint32 seq, serial, flags;
3288 struct rx_packet *tnp;
3289 struct clock when, now;
3290 if (rx_stats_active)
3291 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3294 /* If there are no packet buffers, drop this new packet, unless we can find
3295 * packet buffers from inactive calls */
3297 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3298 MUTEX_ENTER(&rx_freePktQ_lock);
3299 rxi_NeedMorePackets = TRUE;
3300 MUTEX_EXIT(&rx_freePktQ_lock);
3301 if (rx_stats_active)
3302 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3303 call->rprev = np->header.serial;
3304 rxi_calltrace(RX_TRACE_DROP, call);
3305 dpf(("packet %x dropped on receipt - quota problems", np));
3307 rxi_ClearReceiveQueue(call);
3308 clock_GetTime(&now);
3310 clock_Add(&when, &rx_softAckDelay);
3311 if (!call->delayedAckEvent
3312 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3313 rxevent_Cancel(call->delayedAckEvent, call,
3314 RX_CALL_REFCOUNT_DELAY);
3315 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3316 call->delayedAckEvent =
3317 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3319 /* we've damaged this call already, might as well do it in. */
3325 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3326 * packet is one of several packets transmitted as a single
3327 * datagram. Do not send any soft or hard acks until all packets
3328 * in a jumbogram have been processed. Send negative acks right away.
3330 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3331 /* tnp is non-null when there are more packets in the
3332 * current jumbo gram */
3339 seq = np->header.seq;
3340 serial = np->header.serial;
3341 flags = np->header.flags;
3343 /* If the call is in an error state, send an abort message */
3345 return rxi_SendCallAbort(call, np, istack, 0);
3347 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3348 * AFS 3.5 jumbogram. */
3349 if (flags & RX_JUMBO_PACKET) {
3350 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3355 if (np->header.spare != 0) {
3356 MUTEX_ENTER(&call->conn->conn_data_lock);
3357 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3358 MUTEX_EXIT(&call->conn->conn_data_lock);
3361 /* The usual case is that this is the expected next packet */
3362 if (seq == call->rnext) {
3364 /* Check to make sure it is not a duplicate of one already queued */
3365 if (queue_IsNotEmpty(&call->rq)
3366 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3367 if (rx_stats_active)
3368 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3369 dpf(("packet %x dropped on receipt - duplicate", np));
3370 rxevent_Cancel(call->delayedAckEvent, call,
3371 RX_CALL_REFCOUNT_DELAY);
3372 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3378 /* It's the next packet. Stick it on the receive queue
3379 * for this call. Set newPackets to make sure we wake
3380 * the reader once all packets have been processed */
3381 np->flags |= RX_PKTFLAG_RQ;
3382 queue_Prepend(&call->rq, np);
3383 #ifdef RXDEBUG_PACKET
3385 #endif /* RXDEBUG_PACKET */
3387 np = NULL; /* We can't use this anymore */
3390 /* If an ack is requested then set a flag to make sure we
3391 * send an acknowledgement for this packet */
3392 if (flags & RX_REQUEST_ACK) {
3393 ackNeeded = RX_ACK_REQUESTED;
3396 /* Keep track of whether we have received the last packet */
3397 if (flags & RX_LAST_PACKET) {
3398 call->flags |= RX_CALL_HAVE_LAST;
3402 /* Check whether we have all of the packets for this call */
3403 if (call->flags & RX_CALL_HAVE_LAST) {
3404 afs_uint32 tseq; /* temporary sequence number */
3405 struct rx_packet *tp; /* Temporary packet pointer */
3406 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3408 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3409 if (tseq != tp->header.seq)
3411 if (tp->header.flags & RX_LAST_PACKET) {
3412 call->flags |= RX_CALL_RECEIVE_DONE;
3419 /* Provide asynchronous notification for those who want it
3420 * (e.g. multi rx) */
3421 if (call->arrivalProc) {
3422 (*call->arrivalProc) (call, call->arrivalProcHandle,
3423 call->arrivalProcArg);
3424 call->arrivalProc = (void (*)())0;
3427 /* Update last packet received */
3430 /* If there is no server process serving this call, grab
3431 * one, if available. We only need to do this once. If a
3432 * server thread is available, this thread becomes a server
3433 * thread and the server thread becomes a listener thread. */
3435 TryAttach(call, socket, tnop, newcallp, 0);
3438 /* This is not the expected next packet. */
3440 /* Determine whether this is a new or old packet, and if it's
3441 * a new one, whether it fits into the current receive window.
3442 * Also figure out whether the packet was delivered in sequence.
3443 * We use the prev variable to determine whether the new packet
3444 * is the successor of its immediate predecessor in the
3445 * receive queue, and the missing flag to determine whether
3446 * any of this packets predecessors are missing. */
3448 afs_uint32 prev; /* "Previous packet" sequence number */
3449 struct rx_packet *tp; /* Temporary packet pointer */
3450 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3451 int missing; /* Are any predecessors missing? */
3453 /* If the new packet's sequence number has been sent to the
3454 * application already, then this is a duplicate */
3455 if (seq < call->rnext) {
3456 if (rx_stats_active)
3457 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3458 rxevent_Cancel(call->delayedAckEvent, call,
3459 RX_CALL_REFCOUNT_DELAY);
3460 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3466 /* If the sequence number is greater than what can be
3467 * accomodated by the current window, then send a negative
3468 * acknowledge and drop the packet */
3469 if ((call->rnext + call->rwind) <= seq) {
3470 rxevent_Cancel(call->delayedAckEvent, call,
3471 RX_CALL_REFCOUNT_DELAY);
3472 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3479 /* Look for the packet in the queue of old received packets */
3480 for (prev = call->rnext - 1, missing =
3481 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3482 /*Check for duplicate packet */
3483 if (seq == tp->header.seq) {
3484 if (rx_stats_active)
3485 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3486 rxevent_Cancel(call->delayedAckEvent, call,
3487 RX_CALL_REFCOUNT_DELAY);
3488 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3494 /* If we find a higher sequence packet, break out and
3495 * insert the new packet here. */
3496 if (seq < tp->header.seq)
3498 /* Check for missing packet */
3499 if (tp->header.seq != prev + 1) {
3503 prev = tp->header.seq;
3506 /* Keep track of whether we have received the last packet. */
3507 if (flags & RX_LAST_PACKET) {
3508 call->flags |= RX_CALL_HAVE_LAST;
3511 /* It's within the window: add it to the the receive queue.
3512 * tp is left by the previous loop either pointing at the
3513 * packet before which to insert the new packet, or at the
3514 * queue head if the queue is empty or the packet should be
3516 np->flags |= RX_PKTFLAG_RQ;
3517 #ifdef RXDEBUG_PACKET
3519 #endif /* RXDEBUG_PACKET */
3520 queue_InsertBefore(tp, np);
3524 /* Check whether we have all of the packets for this call */
3525 if ((call->flags & RX_CALL_HAVE_LAST)
3526 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3527 afs_uint32 tseq; /* temporary sequence number */
3530 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3531 if (tseq != tp->header.seq)
3533 if (tp->header.flags & RX_LAST_PACKET) {
3534 call->flags |= RX_CALL_RECEIVE_DONE;
3541 /* We need to send an ack of the packet is out of sequence,
3542 * or if an ack was requested by the peer. */
3543 if (seq != prev + 1 || missing) {
3544 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3545 } else if (flags & RX_REQUEST_ACK) {
3546 ackNeeded = RX_ACK_REQUESTED;
3549 /* Acknowledge the last packet for each call */
3550 if (flags & RX_LAST_PACKET) {
3561 * If the receiver is waiting for an iovec, fill the iovec
3562 * using the data from the receive queue */
3563 if (call->flags & RX_CALL_IOVEC_WAIT) {
3564 didHardAck = rxi_FillReadVec(call, serial);
3565 /* the call may have been aborted */
3574 /* Wakeup the reader if any */
3575 if ((call->flags & RX_CALL_READER_WAIT)
3576 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3577 || (call->iovNext >= call->iovMax)
3578 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3579 call->flags &= ~RX_CALL_READER_WAIT;
3580 #ifdef RX_ENABLE_LOCKS
3581 CV_BROADCAST(&call->cv_rq);
3583 osi_rxWakeup(&call->rq);
3589 * Send an ack when requested by the peer, or once every
3590 * rxi_SoftAckRate packets until the last packet has been
3591 * received. Always send a soft ack for the last packet in
3592 * the server's reply. */
3594 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3595 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3596 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3597 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3598 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3599 } else if (call->nSoftAcks) {
3600 clock_GetTime(&now);
3602 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3603 clock_Add(&when, &rx_lastAckDelay);
3605 clock_Add(&when, &rx_softAckDelay);
3607 if (!call->delayedAckEvent
3608 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3609 rxevent_Cancel(call->delayedAckEvent, call,
3610 RX_CALL_REFCOUNT_DELAY);
3611 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3612 call->delayedAckEvent =
3613 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3615 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3616 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3623 static void rxi_ComputeRate();
3627 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3629 struct rx_peer *peer = conn->peer;
3631 MUTEX_ENTER(&peer->peer_lock);
3632 peer->lastReachTime = clock_Sec();
3633 MUTEX_EXIT(&peer->peer_lock);
3635 MUTEX_ENTER(&conn->conn_data_lock);
3636 if (conn->flags & RX_CONN_ATTACHWAIT) {
3639 conn->flags &= ~RX_CONN_ATTACHWAIT;
3640 MUTEX_EXIT(&conn->conn_data_lock);
3642 for (i = 0; i < RX_MAXCALLS; i++) {
3643 struct rx_call *call = conn->call[i];
3646 MUTEX_ENTER(&call->lock);
3647 /* tnop can be null if newcallp is null */
3648 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3650 MUTEX_EXIT(&call->lock);
3654 MUTEX_EXIT(&conn->conn_data_lock);
3658 rx_ack_reason(int reason)
3661 case RX_ACK_REQUESTED:
3663 case RX_ACK_DUPLICATE:
3665 case RX_ACK_OUT_OF_SEQUENCE:
3667 case RX_ACK_EXCEEDS_WINDOW:
3669 case RX_ACK_NOSPACE:
3673 case RX_ACK_PING_RESPONSE:
3685 /* rxi_ComputePeerNetStats
3687 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3688 * estimates (like RTT and throughput) based on ack packets. Caller
3689 * must ensure that the packet in question is the right one (i.e.
3690 * serial number matches).
3693 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3694 struct rx_ackPacket *ap, struct rx_packet *np)
3696 struct rx_peer *peer = call->conn->peer;
3698 /* Use RTT if not delayed by client. */
3699 if (ap->reason != RX_ACK_DELAY)
3700 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3702 rxi_ComputeRate(peer, call, p, np, ap->reason);
3706 /* The real smarts of the whole thing. */
3708 rxi_ReceiveAckPacket(register struct rx_call *call, struct rx_packet *np,
3711 struct rx_ackPacket *ap;
3713 register struct rx_packet *tp;
3714 register struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3715 register struct rx_connection *conn = call->conn;
3716 struct rx_peer *peer = conn->peer;
3719 /* because there are CM's that are bogus, sending weird values for this. */
3720 afs_uint32 skew = 0;
3725 int newAckCount = 0;
3726 u_short maxMTU = 0; /* Set if peer supports AFS 3.4a jumbo datagrams */
3727 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3729 if (rx_stats_active)
3730 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3731 ap = (struct rx_ackPacket *)rx_DataOf(np);
3732 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3734 return np; /* truncated ack packet */
3736 /* depends on ack packet struct */
3737 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3738 first = ntohl(ap->firstPacket);
3739 serial = ntohl(ap->serial);
3740 /* temporarily disabled -- needs to degrade over time
3741 * skew = ntohs(ap->maxSkew); */
3743 /* Ignore ack packets received out of order */
3744 if (first < call->tfirst) {
3748 if (np->header.flags & RX_SLOW_START_OK) {
3749 call->flags |= RX_CALL_SLOW_START_OK;
3752 if (ap->reason == RX_ACK_PING_RESPONSE)
3753 rxi_UpdatePeerReach(conn, call);
3757 if (rxdebug_active) {
3761 len = _snprintf(msg, sizeof(msg),
3762 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3763 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3764 ntohl(ap->serial), ntohl(ap->previousPacket),
3765 (unsigned int)np->header.seq, (unsigned int)skew,
3766 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3770 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3771 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3775 OutputDebugString(msg);
3777 #else /* AFS_NT40_ENV */
3780 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3781 ap->reason, ntohl(ap->previousPacket),
3782 (unsigned int)np->header.seq, (unsigned int)serial,
3783 (unsigned int)skew, ntohl(ap->firstPacket));
3786 for (offset = 0; offset < nAcks; offset++)
3787 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3792 #endif /* AFS_NT40_ENV */
3795 /* Update the outgoing packet skew value to the latest value of
3796 * the peer's incoming packet skew value. The ack packet, of
3797 * course, could arrive out of order, but that won't affect things
3799 MUTEX_ENTER(&peer->peer_lock);
3800 peer->outPacketSkew = skew;
3802 /* Check for packets that no longer need to be transmitted, and
3803 * discard them. This only applies to packets positively
3804 * acknowledged as having been sent to the peer's upper level.
3805 * All other packets must be retained. So only packets with
3806 * sequence numbers < ap->firstPacket are candidates. */
3807 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3808 if (tp->header.seq >= first)
3810 call->tfirst = tp->header.seq + 1;
3812 && (tp->header.serial == serial || tp->firstSerial == serial))
3813 rxi_ComputePeerNetStats(call, tp, ap, np);
3814 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3817 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3818 /* XXX Hack. Because we have to release the global rx lock when sending
3819 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3820 * in rxi_Start sending packets out because packets may move to the
3821 * freePacketQueue as result of being here! So we drop these packets until
3822 * we're safely out of the traversing. Really ugly!
3823 * To make it even uglier, if we're using fine grain locking, we can
3824 * set the ack bits in the packets and have rxi_Start remove the packets
3825 * when it's done transmitting.
3827 if (call->flags & RX_CALL_TQ_BUSY) {
3828 #ifdef RX_ENABLE_LOCKS
3829 tp->flags |= RX_PKTFLAG_ACKED;
3830 call->flags |= RX_CALL_TQ_SOME_ACKED;
3831 #else /* RX_ENABLE_LOCKS */
3833 #endif /* RX_ENABLE_LOCKS */
3835 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3838 tp->flags &= ~RX_PKTFLAG_TQ;
3839 #ifdef RXDEBUG_PACKET
3841 #endif /* RXDEBUG_PACKET */
3842 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3847 /* Give rate detector a chance to respond to ping requests */
3848 if (ap->reason == RX_ACK_PING_RESPONSE) {
3849 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3853 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
3855 /* Now go through explicit acks/nacks and record the results in
3856 * the waiting packets. These are packets that can't be released
3857 * yet, even with a positive acknowledge. This positive
3858 * acknowledge only means the packet has been received by the
3859 * peer, not that it will be retained long enough to be sent to
3860 * the peer's upper level. In addition, reset the transmit timers
3861 * of any missing packets (those packets that must be missing
3862 * because this packet was out of sequence) */
3864 call->nSoftAcked = 0;
3865 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3866 /* Update round trip time if the ack was stimulated on receipt
3868 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3869 #ifdef RX_ENABLE_LOCKS
3870 if (tp->header.seq >= first)
3871 #endif /* RX_ENABLE_LOCKS */
3872 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3874 && (tp->header.serial == serial || tp->firstSerial == serial))
3875 rxi_ComputePeerNetStats(call, tp, ap, np);
3877 /* Set the acknowledge flag per packet based on the
3878 * information in the ack packet. An acknowlegded packet can
3879 * be downgraded when the server has discarded a packet it
3880 * soacked previously, or when an ack packet is received
3881 * out of sequence. */
3882 if (tp->header.seq < first) {
3883 /* Implicit ack information */
3884 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3887 tp->flags |= RX_PKTFLAG_ACKED;
3888 } else if (tp->header.seq < first + nAcks) {
3889 /* Explicit ack information: set it in the packet appropriately */
3890 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
3891 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3893 tp->flags |= RX_PKTFLAG_ACKED;
3900 } else /* RX_ACK_TYPE_NACK */ {
3901 tp->flags &= ~RX_PKTFLAG_ACKED;
3905 tp->flags &= ~RX_PKTFLAG_ACKED;
3909 /* If packet isn't yet acked, and it has been transmitted at least
3910 * once, reset retransmit time using latest timeout
3911 * ie, this should readjust the retransmit timer for all outstanding
3912 * packets... So we don't just retransmit when we should know better*/
3914 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
3915 tp->retryTime = tp->timeSent;
3916 clock_Add(&tp->retryTime, &peer->timeout);
3917 /* shift by eight because one quarter-sec ~ 256 milliseconds */
3918 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
3922 /* If the window has been extended by this acknowledge packet,
3923 * then wakeup a sender waiting in alloc for window space, or try
3924 * sending packets now, if he's been sitting on packets due to
3925 * lack of window space */
3926 if (call->tnext < (call->tfirst + call->twind)) {
3927 #ifdef RX_ENABLE_LOCKS
3928 CV_SIGNAL(&call->cv_twind);
3930 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
3931 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
3932 osi_rxWakeup(&call->twind);
3935 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
3936 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
3940 /* if the ack packet has a receivelen field hanging off it,
3941 * update our state */
3942 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
3945 /* If the ack packet has a "recommended" size that is less than
3946 * what I am using now, reduce my size to match */
3947 rx_packetread(np, rx_AckDataSize(ap->nAcks) + sizeof(afs_int32),
3948 (int)sizeof(afs_int32), &tSize);
3949 tSize = (afs_uint32) ntohl(tSize);
3950 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
3952 /* Get the maximum packet size to send to this peer */
3953 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
3955 tSize = (afs_uint32) ntohl(tSize);
3956 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
3957 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
3959 /* sanity check - peer might have restarted with different params.
3960 * If peer says "send less", dammit, send less... Peer should never
3961 * be unable to accept packets of the size that prior AFS versions would
3962 * send without asking. */
3963 if (peer->maxMTU != tSize) {
3964 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
3966 peer->maxMTU = tSize;
3967 peer->MTU = MIN(tSize, peer->MTU);
3968 call->MTU = MIN(call->MTU, tSize);
3971 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
3974 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3975 (int)sizeof(afs_int32), &tSize);
3976 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
3977 if (tSize < call->twind) { /* smaller than our send */
3978 call->twind = tSize; /* window, we must send less... */
3979 call->ssthresh = MIN(call->twind, call->ssthresh);
3980 call->conn->twind[call->channel] = call->twind;
3983 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
3984 * network MTU confused with the loopback MTU. Calculate the
3985 * maximum MTU here for use in the slow start code below.
3987 maxMTU = peer->maxMTU;
3988 /* Did peer restart with older RX version? */
3989 if (peer->maxDgramPackets > 1) {
3990 peer->maxDgramPackets = 1;
3992 } else if (np->length >=
3993 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
3996 rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32),
3997 sizeof(afs_int32), &tSize);
3998 tSize = (afs_uint32) ntohl(tSize);
4000 * As of AFS 3.5 we set the send window to match the receive window.
4002 if (tSize < call->twind) {
4003 call->twind = tSize;
4004 call->conn->twind[call->channel] = call->twind;
4005 call->ssthresh = MIN(call->twind, call->ssthresh);
4006 } else if (tSize > call->twind) {
4007 call->twind = tSize;
4008 call->conn->twind[call->channel] = call->twind;
4012 * As of AFS 3.5, a jumbogram is more than one fixed size
4013 * packet transmitted in a single UDP datagram. If the remote
4014 * MTU is smaller than our local MTU then never send a datagram
4015 * larger than the natural MTU.
4018 rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32),
4019 sizeof(afs_int32), &tSize);
4020 maxDgramPackets = (afs_uint32) ntohl(tSize);
4021 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4022 maxDgramPackets = MIN(maxDgramPackets, peer->ifDgramPackets);
4023 if (peer->natMTU < peer->ifMTU)
4024 maxDgramPackets = MIN(maxDgramPackets, rxi_AdjustDgramPackets(1, peer->natMTU));
4025 if (maxDgramPackets > 1) {
4026 peer->maxDgramPackets = maxDgramPackets;
4027 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4029 peer->maxDgramPackets = 1;
4030 call->MTU = peer->natMTU;
4032 } else if (peer->maxDgramPackets > 1) {
4033 /* Restarted with lower version of RX */
4034 peer->maxDgramPackets = 1;
4036 } else if (peer->maxDgramPackets > 1
4037 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4038 /* Restarted with lower version of RX */
4039 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4040 peer->natMTU = OLD_MAX_PACKET_SIZE;
4041 peer->MTU = OLD_MAX_PACKET_SIZE;
4042 peer->maxDgramPackets = 1;
4043 peer->nDgramPackets = 1;
4045 call->MTU = OLD_MAX_PACKET_SIZE;
4050 * Calculate how many datagrams were successfully received after
4051 * the first missing packet and adjust the negative ack counter
4056 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4057 if (call->nNacks < nNacked) {
4058 call->nNacks = nNacked;
4061 call->nAcks += newAckCount;
4065 if (call->flags & RX_CALL_FAST_RECOVER) {
4067 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4069 call->flags &= ~RX_CALL_FAST_RECOVER;
4070 call->cwind = call->nextCwind;
4071 call->nextCwind = 0;
4074 call->nCwindAcks = 0;
4075 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4076 /* Three negative acks in a row trigger congestion recovery */
4077 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4078 MUTEX_EXIT(&peer->peer_lock);
4079 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4080 /* someone else is waiting to start recovery */
4083 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4084 rxi_WaitforTQBusy(call);
4085 MUTEX_ENTER(&peer->peer_lock);
4086 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4087 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4088 call->flags |= RX_CALL_FAST_RECOVER;
4089 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4091 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4092 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4093 call->nextCwind = call->ssthresh;
4096 peer->MTU = call->MTU;
4097 peer->cwind = call->nextCwind;
4098 peer->nDgramPackets = call->nDgramPackets;
4100 call->congestSeq = peer->congestSeq;
4101 /* Reset the resend times on the packets that were nacked
4102 * so we will retransmit as soon as the window permits*/
4103 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4105 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4106 clock_Zero(&tp->retryTime);
4108 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4113 /* If cwind is smaller than ssthresh, then increase
4114 * the window one packet for each ack we receive (exponential
4116 * If cwind is greater than or equal to ssthresh then increase
4117 * the congestion window by one packet for each cwind acks we
4118 * receive (linear growth). */
4119 if (call->cwind < call->ssthresh) {
4121 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4122 call->nCwindAcks = 0;
4124 call->nCwindAcks += newAckCount;
4125 if (call->nCwindAcks >= call->cwind) {
4126 call->nCwindAcks = 0;
4127 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4131 * If we have received several acknowledgements in a row then
4132 * it is time to increase the size of our datagrams
4134 if ((int)call->nAcks > rx_nDgramThreshold) {
4135 if (peer->maxDgramPackets > 1) {
4136 if (call->nDgramPackets < peer->maxDgramPackets) {
4137 call->nDgramPackets++;
4139 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4140 } else if (call->MTU < peer->maxMTU) {
4141 call->MTU += peer->natMTU;
4142 call->MTU = MIN(call->MTU, peer->maxMTU);
4148 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4150 /* Servers need to hold the call until all response packets have
4151 * been acknowledged. Soft acks are good enough since clients
4152 * are not allowed to clear their receive queues. */
4153 if (call->state == RX_STATE_HOLD
4154 && call->tfirst + call->nSoftAcked >= call->tnext) {
4155 call->state = RX_STATE_DALLY;
4156 rxi_ClearTransmitQueue(call, 0);
4157 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4158 } else if (!queue_IsEmpty(&call->tq)) {
4159 rxi_Start(0, call, 0, istack);
4164 /* Received a response to a challenge packet */
4166 rxi_ReceiveResponsePacket(register struct rx_connection *conn,
4167 register struct rx_packet *np, int istack)
4171 /* Ignore the packet if we're the client */
4172 if (conn->type == RX_CLIENT_CONNECTION)
4175 /* If already authenticated, ignore the packet (it's probably a retry) */
4176 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4179 /* Otherwise, have the security object evaluate the response packet */
4180 error = RXS_CheckResponse(conn->securityObject, conn, np);
4182 /* If the response is invalid, reset the connection, sending
4183 * an abort to the peer */
4187 rxi_ConnectionError(conn, error);
4188 MUTEX_ENTER(&conn->conn_data_lock);
4189 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4190 MUTEX_EXIT(&conn->conn_data_lock);
4193 /* If the response is valid, any calls waiting to attach
4194 * servers can now do so */
4197 for (i = 0; i < RX_MAXCALLS; i++) {
4198 struct rx_call *call = conn->call[i];
4200 MUTEX_ENTER(&call->lock);
4201 if (call->state == RX_STATE_PRECALL)
4202 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4203 /* tnop can be null if newcallp is null */
4204 MUTEX_EXIT(&call->lock);
4208 /* Update the peer reachability information, just in case
4209 * some calls went into attach-wait while we were waiting
4210 * for authentication..
4212 rxi_UpdatePeerReach(conn, NULL);
4217 /* A client has received an authentication challenge: the security
4218 * object is asked to cough up a respectable response packet to send
4219 * back to the server. The server is responsible for retrying the
4220 * challenge if it fails to get a response. */
4223 rxi_ReceiveChallengePacket(register struct rx_connection *conn,
4224 register struct rx_packet *np, int istack)
4228 /* Ignore the challenge if we're the server */
4229 if (conn->type == RX_SERVER_CONNECTION)
4232 /* Ignore the challenge if the connection is otherwise idle; someone's
4233 * trying to use us as an oracle. */
4234 if (!rxi_HasActiveCalls(conn))
4237 /* Send the security object the challenge packet. It is expected to fill
4238 * in the response. */
4239 error = RXS_GetResponse(conn->securityObject, conn, np);
4241 /* If the security object is unable to return a valid response, reset the
4242 * connection and send an abort to the peer. Otherwise send the response
4243 * packet to the peer connection. */
4245 rxi_ConnectionError(conn, error);
4246 MUTEX_ENTER(&conn->conn_data_lock);
4247 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4248 MUTEX_EXIT(&conn->conn_data_lock);
4250 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4251 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4257 /* Find an available server process to service the current request in
4258 * the given call structure. If one isn't available, queue up this
4259 * call so it eventually gets one */
4261 rxi_AttachServerProc(register struct rx_call *call,
4262 register osi_socket socket, register int *tnop,
4263 register struct rx_call **newcallp)
4265 register struct rx_serverQueueEntry *sq;
4266 register struct rx_service *service = call->conn->service;
4267 register int haveQuota = 0;
4269 /* May already be attached */
4270 if (call->state == RX_STATE_ACTIVE)
4273 MUTEX_ENTER(&rx_serverPool_lock);
4275 haveQuota = QuotaOK(service);
4276 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4277 /* If there are no processes available to service this call,
4278 * put the call on the incoming call queue (unless it's
4279 * already on the queue).
4281 #ifdef RX_ENABLE_LOCKS
4283 ReturnToServerPool(service);
4284 #endif /* RX_ENABLE_LOCKS */
4286 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4287 call->flags |= RX_CALL_WAIT_PROC;
4288 MUTEX_ENTER(&rx_waiting_mutex);
4291 MUTEX_EXIT(&rx_waiting_mutex);
4292 rxi_calltrace(RX_CALL_ARRIVAL, call);
4293 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4294 queue_Append(&rx_incomingCallQueue, call);
4297 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
4299 /* If hot threads are enabled, and both newcallp and sq->socketp
4300 * are non-null, then this thread will process the call, and the
4301 * idle server thread will start listening on this threads socket.
4304 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4307 *sq->socketp = socket;
4308 clock_GetTime(&call->startTime);
4309 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4313 if (call->flags & RX_CALL_WAIT_PROC) {
4314 /* Conservative: I don't think this should happen */
4315 call->flags &= ~RX_CALL_WAIT_PROC;
4316 if (queue_IsOnQueue(call)) {
4319 MUTEX_ENTER(&rx_waiting_mutex);
4321 MUTEX_EXIT(&rx_waiting_mutex);
4324 call->state = RX_STATE_ACTIVE;
4325 call->mode = RX_MODE_RECEIVING;
4326 #ifdef RX_KERNEL_TRACE
4328 int glockOwner = ISAFS_GLOCK();
4331 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4332 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4338 if (call->flags & RX_CALL_CLEARED) {
4339 /* send an ack now to start the packet flow up again */
4340 call->flags &= ~RX_CALL_CLEARED;
4341 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4343 #ifdef RX_ENABLE_LOCKS
4346 service->nRequestsRunning++;
4347 if (service->nRequestsRunning <= service->minProcs)
4353 MUTEX_EXIT(&rx_serverPool_lock);
4356 /* Delay the sending of an acknowledge event for a short while, while
4357 * a new call is being prepared (in the case of a client) or a reply
4358 * is being prepared (in the case of a server). Rather than sending
4359 * an ack packet, an ACKALL packet is sent. */
4361 rxi_AckAll(struct rxevent *event, register struct rx_call *call, char *dummy)
4363 #ifdef RX_ENABLE_LOCKS
4365 MUTEX_ENTER(&call->lock);
4366 call->delayedAckEvent = NULL;
4367 CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4369 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4370 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4372 MUTEX_EXIT(&call->lock);
4373 #else /* RX_ENABLE_LOCKS */
4375 call->delayedAckEvent = NULL;
4376 rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4377 RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4378 #endif /* RX_ENABLE_LOCKS */
4382 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused)
4384 struct rx_call *call = arg1;
4385 #ifdef RX_ENABLE_LOCKS
4387 MUTEX_ENTER(&call->lock);
4388 if (event == call->delayedAckEvent)
4389 call->delayedAckEvent = NULL;
4390 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4392 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4394 MUTEX_EXIT(&call->lock);
4395 #else /* RX_ENABLE_LOCKS */
4397 call->delayedAckEvent = NULL;
4398 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4399 #endif /* RX_ENABLE_LOCKS */
4403 #ifdef RX_ENABLE_LOCKS
4404 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4405 * clearing them out.
4408 rxi_SetAcksInTransmitQueue(register struct rx_call *call)
4410 register struct rx_packet *p, *tp;
4413 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4414 p->flags |= RX_PKTFLAG_ACKED;
4418 call->flags |= RX_CALL_TQ_CLEARME;
4419 call->flags |= RX_CALL_TQ_SOME_ACKED;
4422 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4423 call->tfirst = call->tnext;
4424 call->nSoftAcked = 0;
4426 if (call->flags & RX_CALL_FAST_RECOVER) {
4427 call->flags &= ~RX_CALL_FAST_RECOVER;
4428 call->cwind = call->nextCwind;
4429 call->nextCwind = 0;
4432 CV_SIGNAL(&call->cv_twind);
4434 #endif /* RX_ENABLE_LOCKS */
4436 /* Clear out the transmit queue for the current call (all packets have
4437 * been received by peer) */
4439 rxi_ClearTransmitQueue(register struct rx_call *call, register int force)
4441 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4442 register struct rx_packet *p, *tp;
4444 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4446 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4447 p->flags |= RX_PKTFLAG_ACKED;
4451 call->flags |= RX_CALL_TQ_CLEARME;
4452 call->flags |= RX_CALL_TQ_SOME_ACKED;
4455 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4456 #ifdef RXDEBUG_PACKET
4458 #endif /* RXDEBUG_PACKET */
4459 rxi_FreePackets(0, &call->tq);
4460 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4461 call->flags &= ~RX_CALL_TQ_CLEARME;
4463 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4465 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
4466 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
4467 call->nSoftAcked = 0;
4469 if (call->flags & RX_CALL_FAST_RECOVER) {
4470 call->flags &= ~RX_CALL_FAST_RECOVER;
4471 call->cwind = call->nextCwind;
4473 #ifdef RX_ENABLE_LOCKS
4474 CV_SIGNAL(&call->cv_twind);
4476 osi_rxWakeup(&call->twind);
4481 rxi_ClearReceiveQueue(register struct rx_call *call)
4483 if (queue_IsNotEmpty(&call->rq)) {
4486 count = rxi_FreePackets(0, &call->rq);
4487 rx_packetReclaims += count;
4488 #ifdef RXDEBUG_PACKET
4490 if ( call->rqc != 0 )
4491 dpf(("rxi_ClearReceiveQueue call %x rqc %u != 0", call, call->rqc));
4493 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
4495 if (call->state == RX_STATE_PRECALL) {
4496 call->flags |= RX_CALL_CLEARED;
4500 /* Send an abort packet for the specified call */
4502 rxi_SendCallAbort(register struct rx_call *call, struct rx_packet *packet,
4503 int istack, int force)
4506 struct clock when, now;
4511 /* Clients should never delay abort messages */
4512 if (rx_IsClientConn(call->conn))
4515 if (call->abortCode != call->error) {
4516 call->abortCode = call->error;
4517 call->abortCount = 0;
4520 if (force || rxi_callAbortThreshhold == 0
4521 || call->abortCount < rxi_callAbortThreshhold) {
4522 if (call->delayedAbortEvent) {
4523 rxevent_Cancel(call->delayedAbortEvent, call,
4524 RX_CALL_REFCOUNT_ABORT);
4526 error = htonl(call->error);
4529 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
4530 (char *)&error, sizeof(error), istack);
4531 } else if (!call->delayedAbortEvent) {
4532 clock_GetTime(&now);
4534 clock_Addmsec(&when, rxi_callAbortDelay);
4535 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
4536 call->delayedAbortEvent =
4537 rxevent_PostNow(&when, &now, rxi_SendDelayedCallAbort, call, 0);
4542 /* Send an abort packet for the specified connection. Packet is an
4543 * optional pointer to a packet that can be used to send the abort.
4544 * Once the number of abort messages reaches the threshhold, an
4545 * event is scheduled to send the abort. Setting the force flag
4546 * overrides sending delayed abort messages.
4548 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
4549 * to send the abort packet.
4552 rxi_SendConnectionAbort(register struct rx_connection *conn,
4553 struct rx_packet *packet, int istack, int force)
4556 struct clock when, now;
4558 if (!rx_ConnError(conn))
4561 /* Clients should never delay abort messages */
4562 if (rx_IsClientConn(conn))
4565 if (force || rxi_connAbortThreshhold == 0
4566 || conn->abortCount < rxi_connAbortThreshhold) {
4567 if (conn->delayedAbortEvent) {
4568 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
4570 error = htonl(rx_ConnError(conn));
4572 MUTEX_EXIT(&conn->conn_data_lock);
4574 rxi_SendSpecial((struct rx_call *)0, conn, packet,
4575 RX_PACKET_TYPE_ABORT, (char *)&error,
4576 sizeof(error), istack);
4577 MUTEX_ENTER(&conn->conn_data_lock);
4578 } else if (!conn->delayedAbortEvent) {
4579 clock_GetTime(&now);
4581 clock_Addmsec(&when, rxi_connAbortDelay);
4582 conn->delayedAbortEvent =
4583 rxevent_PostNow(&when, &now, rxi_SendDelayedConnAbort, conn, 0);
4589 * Associate an error all of the calls owned by a connection. Called
4590 * with error non-zero. This is only for really fatal things, like
4591 * bad authentication responses. The connection itself is set in
4592 * error at this point, so that future packets received will be
4596 rxi_ConnectionError(register struct rx_connection *conn,
4597 register afs_int32 error)
4601 struct rx_connection *tconn;
4603 dpf(("rxi_ConnectionError conn %x error %d", conn, error));
4605 MUTEX_ENTER(&conn->conn_data_lock);
4606 if (conn->challengeEvent)
4607 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
4608 if (conn->checkReachEvent) {
4609 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
4610 conn->checkReachEvent = 0;
4611 conn->flags &= ~RX_CONN_ATTACHWAIT;
4614 MUTEX_EXIT(&conn->conn_data_lock);
4616 for ( tconn = rx_IsClonedConn(conn) ? conn->parent : conn;
4618 tconn = tconn->next_clone) {
4619 for (i = 0; i < RX_MAXCALLS; i++) {
4620 struct rx_call *call = tconn->call[i];
4622 MUTEX_ENTER(&call->lock);
4623 rxi_CallError(call, error);
4624 MUTEX_EXIT(&call->lock);
4628 rx_SetConnError(conn, error);
4629 if (rx_stats_active)
4630 rx_MutexIncrement(rx_stats.fatalErrors, rx_stats_mutex);
4635 rxi_CallError(register struct rx_call *call, afs_int32 error)
4638 osirx_AssertMine(&call->lock, "rxi_CallError");
4640 dpf(("rxi_CallError call %x error %d call->error %d", call, error, call->error));
4642 error = call->error;
4644 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4645 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
4646 rxi_ResetCall(call, 0);
4649 rxi_ResetCall(call, 0);
4651 call->error = error;
4652 call->mode = RX_MODE_ERROR;
4655 /* Reset various fields in a call structure, and wakeup waiting
4656 * processes. Some fields aren't changed: state & mode are not
4657 * touched (these must be set by the caller), and bufptr, nLeft, and
4658 * nFree are not reset, since these fields are manipulated by
4659 * unprotected macros, and may only be reset by non-interrupting code.
4662 /* this code requires that call->conn be set properly as a pre-condition. */
4663 #endif /* ADAPT_WINDOW */
4666 rxi_ResetCall(register struct rx_call *call, register int newcall)
4669 register struct rx_peer *peer;
4670 struct rx_packet *packet;
4672 osirx_AssertMine(&call->lock, "rxi_ResetCall");
4674 dpf(("rxi_ResetCall(call %x, newcall %d)\n", call, newcall));
4676 /* Notify anyone who is waiting for asynchronous packet arrival */
4677 if (call->arrivalProc) {
4678 (*call->arrivalProc) (call, call->arrivalProcHandle,
4679 call->arrivalProcArg);
4680 call->arrivalProc = (void (*)())0;
4683 if (call->delayedAbortEvent) {
4684 rxevent_Cancel(call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
4685 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
4687 rxi_SendCallAbort(call, packet, 0, 1);
4688 rxi_FreePacket(packet);
4693 * Update the peer with the congestion information in this call
4694 * so other calls on this connection can pick up where this call
4695 * left off. If the congestion sequence numbers don't match then
4696 * another call experienced a retransmission.
4698 peer = call->conn->peer;
4699 MUTEX_ENTER(&peer->peer_lock);
4701 if (call->congestSeq == peer->congestSeq) {
4702 peer->cwind = MAX(peer->cwind, call->cwind);
4703 peer->MTU = MAX(peer->MTU, call->MTU);
4704 peer->nDgramPackets =
4705 MAX(peer->nDgramPackets, call->nDgramPackets);
4708 call->abortCode = 0;
4709 call->abortCount = 0;
4711 if (peer->maxDgramPackets > 1) {
4712 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4714 call->MTU = peer->MTU;
4716 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
4717 call->ssthresh = rx_maxSendWindow;
4718 call->nDgramPackets = peer->nDgramPackets;
4719 call->congestSeq = peer->congestSeq;
4720 MUTEX_EXIT(&peer->peer_lock);
4722 flags = call->flags;
4723 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4724 if (flags & RX_CALL_TQ_BUSY) {
4725 call->flags = RX_CALL_TQ_CLEARME | RX_CALL_TQ_BUSY;
4726 call->flags |= (flags & RX_CALL_TQ_WAIT);
4728 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4730 rxi_ClearTransmitQueue(call, 1);
4731 /* why init the queue if you just emptied it? queue_Init(&call->tq); */
4732 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
4733 dpf(("rcall %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
4736 while (call->tqWaiters) {
4737 #ifdef RX_ENABLE_LOCKS
4738 CV_BROADCAST(&call->cv_tq);
4739 #else /* RX_ENABLE_LOCKS */
4740 osi_rxWakeup(&call->tq);
4741 #endif /* RX_ENABLE_LOCKS */
4746 rxi_ClearReceiveQueue(call);
4747 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
4749 if (call->currentPacket) {
4750 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
4751 call->currentPacket->flags |= RX_PKTFLAG_IOVQ;
4752 queue_Prepend(&call->iovq, call->currentPacket);
4753 #ifdef RXDEBUG_PACKET
4755 #endif /* RXDEBUG_PACKET */
4756 call->currentPacket = (struct rx_packet *)0;
4758 call->curlen = call->nLeft = call->nFree = 0;
4760 #ifdef RXDEBUG_PACKET
4763 rxi_FreePackets(0, &call->iovq);
4766 call->twind = call->conn->twind[call->channel];
4767 call->rwind = call->conn->rwind[call->channel];
4768 call->nSoftAcked = 0;
4769 call->nextCwind = 0;
4772 call->nCwindAcks = 0;
4773 call->nSoftAcks = 0;
4774 call->nHardAcks = 0;
4776 call->tfirst = call->rnext = call->tnext = 1;
4778 call->lastAcked = 0;
4779 call->localStatus = call->remoteStatus = 0;
4781 if (flags & RX_CALL_READER_WAIT) {
4782 #ifdef RX_ENABLE_LOCKS
4783 CV_BROADCAST(&call->cv_rq);
4785 osi_rxWakeup(&call->rq);
4788 if (flags & RX_CALL_WAIT_PACKETS) {
4789 MUTEX_ENTER(&rx_freePktQ_lock);
4790 rxi_PacketsUnWait(); /* XXX */
4791 MUTEX_EXIT(&rx_freePktQ_lock);
4793 #ifdef RX_ENABLE_LOCKS
4794 CV_SIGNAL(&call->cv_twind);
4796 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
4797 osi_rxWakeup(&call->twind);
4800 #ifdef RX_ENABLE_LOCKS
4801 /* The following ensures that we don't mess with any queue while some
4802 * other thread might also be doing so. The call_queue_lock field is
4803 * is only modified under the call lock. If the call is in the process
4804 * of being removed from a queue, the call is not locked until the
4805 * the queue lock is dropped and only then is the call_queue_lock field
4806 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
4807 * Note that any other routine which removes a call from a queue has to
4808 * obtain the queue lock before examing the queue and removing the call.
4810 if (call->call_queue_lock) {
4811 MUTEX_ENTER(call->call_queue_lock);
4812 if (queue_IsOnQueue(call)) {
4814 if (flags & RX_CALL_WAIT_PROC) {
4816 MUTEX_ENTER(&rx_waiting_mutex);
4818 MUTEX_EXIT(&rx_waiting_mutex);
4821 MUTEX_EXIT(call->call_queue_lock);
4822 CLEAR_CALL_QUEUE_LOCK(call);
4824 #else /* RX_ENABLE_LOCKS */
4825 if (queue_IsOnQueue(call)) {
4827 if (flags & RX_CALL_WAIT_PROC)
4830 #endif /* RX_ENABLE_LOCKS */
4832 rxi_KeepAliveOff(call);
4833 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4836 /* Send an acknowledge for the indicated packet (seq,serial) of the
4837 * indicated call, for the indicated reason (reason). This
4838 * acknowledge will specifically acknowledge receiving the packet, and
4839 * will also specify which other packets for this call have been
4840 * received. This routine returns the packet that was used to the
4841 * caller. The caller is responsible for freeing it or re-using it.
4842 * This acknowledgement also returns the highest sequence number
4843 * actually read out by the higher level to the sender; the sender
4844 * promises to keep around packets that have not been read by the
4845 * higher level yet (unless, of course, the sender decides to abort
4846 * the call altogether). Any of p, seq, serial, pflags, or reason may
4847 * be set to zero without ill effect. That is, if they are zero, they
4848 * will not convey any information.
4849 * NOW there is a trailer field, after the ack where it will safely be
4850 * ignored by mundanes, which indicates the maximum size packet this
4851 * host can swallow. */
4853 register struct rx_packet *optionalPacket; use to send ack (or null)
4854 int seq; Sequence number of the packet we are acking
4855 int serial; Serial number of the packet
4856 int pflags; Flags field from packet header
4857 int reason; Reason an acknowledge was prompted
4861 rxi_SendAck(register struct rx_call *call,
4862 register struct rx_packet *optionalPacket, int serial, int reason,
4865 struct rx_ackPacket *ap;
4866 register struct rx_packet *rqp;
4867 register struct rx_packet *nxp; /* For queue_Scan */
4868 register struct rx_packet *p;
4871 #ifdef RX_ENABLE_TSFPQ
4872 struct rx_ts_info_t * rx_ts_info;
4876 * Open the receive window once a thread starts reading packets
4878 if (call->rnext > 1) {
4879 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
4882 call->nHardAcks = 0;
4883 call->nSoftAcks = 0;
4884 if (call->rnext > call->lastAcked)
4885 call->lastAcked = call->rnext;
4889 rx_computelen(p, p->length); /* reset length, you never know */
4890 } /* where that's been... */
4891 #ifdef RX_ENABLE_TSFPQ
4893 RX_TS_INFO_GET(rx_ts_info);
4894 if ((p = rx_ts_info->local_special_packet)) {
4895 rx_computelen(p, p->length);
4896 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4897 rx_ts_info->local_special_packet = p;
4898 } else { /* We won't send the ack, but don't panic. */
4899 return optionalPacket;
4903 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
4904 /* We won't send the ack, but don't panic. */
4905 return optionalPacket;
4910 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
4913 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
4914 #ifndef RX_ENABLE_TSFPQ
4915 if (!optionalPacket)
4918 return optionalPacket;
4920 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
4921 if (rx_Contiguous(p) < templ) {
4922 #ifndef RX_ENABLE_TSFPQ
4923 if (!optionalPacket)
4926 return optionalPacket;
4931 /* MTUXXX failing to send an ack is very serious. We should */
4932 /* try as hard as possible to send even a partial ack; it's */
4933 /* better than nothing. */
4934 ap = (struct rx_ackPacket *)rx_DataOf(p);
4935 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
4936 ap->reason = reason;
4938 /* The skew computation used to be bogus, I think it's better now. */
4939 /* We should start paying attention to skew. XXX */
4940 ap->serial = htonl(serial);
4941 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
4943 ap->firstPacket = htonl(call->rnext); /* First packet not yet forwarded to reader */
4944 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
4946 /* No fear of running out of ack packet here because there can only be at most
4947 * one window full of unacknowledged packets. The window size must be constrained
4948 * to be less than the maximum ack size, of course. Also, an ack should always
4949 * fit into a single packet -- it should not ever be fragmented. */
4950 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
4951 if (!rqp || !call->rq.next
4952 || (rqp->header.seq > (call->rnext + call->rwind))) {
4953 #ifndef RX_ENABLE_TSFPQ
4954 if (!optionalPacket)
4957 rxi_CallError(call, RX_CALL_DEAD);
4958 return optionalPacket;
4961 while (rqp->header.seq > call->rnext + offset)
4962 ap->acks[offset++] = RX_ACK_TYPE_NACK;
4963 ap->acks[offset++] = RX_ACK_TYPE_ACK;
4965 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
4966 #ifndef RX_ENABLE_TSFPQ
4967 if (!optionalPacket)
4970 rxi_CallError(call, RX_CALL_DEAD);
4971 return optionalPacket;
4976 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
4978 /* these are new for AFS 3.3 */
4979 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
4980 templ = htonl(templ);
4981 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
4982 templ = htonl(call->conn->peer->ifMTU);
4983 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
4984 sizeof(afs_int32), &templ);
4986 /* new for AFS 3.4 */
4987 templ = htonl(call->rwind);
4988 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
4989 sizeof(afs_int32), &templ);
4991 /* new for AFS 3.5 */
4992 templ = htonl(call->conn->peer->ifDgramPackets);
4993 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
4994 sizeof(afs_int32), &templ);
4996 p->header.serviceId = call->conn->serviceId;
4997 p->header.cid = (call->conn->cid | call->channel);
4998 p->header.callNumber = *call->callNumber;
5000 p->header.securityIndex = call->conn->securityIndex;
5001 p->header.epoch = call->conn->epoch;
5002 p->header.type = RX_PACKET_TYPE_ACK;
5003 p->header.flags = RX_SLOW_START_OK;
5004 if (reason == RX_ACK_PING) {
5005 p->header.flags |= RX_REQUEST_ACK;
5007 clock_GetTime(&call->pingRequestTime);
5010 if (call->conn->type == RX_CLIENT_CONNECTION)
5011 p->header.flags |= RX_CLIENT_INITIATED;
5015 if (rxdebug_active) {
5019 len = _snprintf(msg, sizeof(msg),
5020 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5021 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5022 ntohl(ap->serial), ntohl(ap->previousPacket),
5023 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5024 ap->nAcks, ntohs(ap->bufferSpace) );
5028 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5029 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5033 OutputDebugString(msg);
5035 #else /* AFS_NT40_ENV */
5037 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5038 ap->reason, ntohl(ap->previousPacket),
5039 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5041 for (offset = 0; offset < ap->nAcks; offset++)
5042 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5047 #endif /* AFS_NT40_ENV */
5050 register int i, nbytes = p->length;
5052 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5053 if (nbytes <= p->wirevec[i].iov_len) {
5054 register int savelen, saven;
5056 savelen = p->wirevec[i].iov_len;
5058 p->wirevec[i].iov_len = nbytes;
5060 rxi_Send(call, p, istack);
5061 p->wirevec[i].iov_len = savelen;
5065 nbytes -= p->wirevec[i].iov_len;
5068 if (rx_stats_active)
5069 rx_MutexIncrement(rx_stats.ackPacketsSent, rx_stats_mutex);
5070 #ifndef RX_ENABLE_TSFPQ
5071 if (!optionalPacket)
5074 return optionalPacket; /* Return packet for re-use by caller */
5077 /* Send all of the packets in the list in single datagram */
5079 rxi_SendList(struct rx_call *call, struct rx_packet **list, int len,
5080 int istack, int moreFlag, struct clock *now,
5081 struct clock *retryTime, int resending)
5086 struct rx_connection *conn = call->conn;
5087 struct rx_peer *peer = conn->peer;
5089 MUTEX_ENTER(&peer->peer_lock);
5092 peer->reSends += len;
5093 if (rx_stats_active)
5094 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5095 MUTEX_EXIT(&peer->peer_lock);
5097 if (list[len - 1]->header.flags & RX_LAST_PACKET) {
5101 /* Set the packet flags and schedule the resend events */
5102 /* Only request an ack for the last packet in the list */
5103 for (i = 0; i < len; i++) {
5104 list[i]->retryTime = *retryTime;
5105 if (list[i]->header.serial) {
5106 /* Exponentially backoff retry times */
5107 if (list[i]->backoff < MAXBACKOFF) {
5108 /* so it can't stay == 0 */
5109 list[i]->backoff = (list[i]->backoff << 1) + 1;
5112 clock_Addmsec(&(list[i]->retryTime),
5113 ((afs_uint32) list[i]->backoff) << 8);
5116 /* Wait a little extra for the ack on the last packet */
5117 if (lastPacket && !(list[i]->header.flags & RX_CLIENT_INITIATED)) {
5118 clock_Addmsec(&(list[i]->retryTime), 400);
5121 /* Record the time sent */
5122 list[i]->timeSent = *now;
5124 /* Ask for an ack on retransmitted packets, on every other packet
5125 * if the peer doesn't support slow start. Ask for an ack on every
5126 * packet until the congestion window reaches the ack rate. */
5127 if (list[i]->header.serial) {
5129 if (rx_stats_active)
5130 rx_MutexIncrement(rx_stats.dataPacketsReSent, rx_stats_mutex);
5132 /* improved RTO calculation- not Karn */
5133 list[i]->firstSent = *now;
5134 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5135 || (!(call->flags & RX_CALL_SLOW_START_OK)
5136 && (list[i]->header.seq & 1)))) {
5141 MUTEX_ENTER(&peer->peer_lock);
5145 if (rx_stats_active)
5146 rx_MutexIncrement(rx_stats.dataPacketsSent, rx_stats_mutex);
5147 MUTEX_EXIT(&peer->peer_lock);
5149 /* Tag this packet as not being the last in this group,
5150 * for the receiver's benefit */
5151 if (i < len - 1 || moreFlag) {
5152 list[i]->header.flags |= RX_MORE_PACKETS;
5155 /* Install the new retransmit time for the packet, and
5156 * record the time sent */
5157 list[i]->timeSent = *now;
5161 list[len - 1]->header.flags |= RX_REQUEST_ACK;
5164 /* Since we're about to send a data packet to the peer, it's
5165 * safe to nuke any scheduled end-of-packets ack */
5166 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5168 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5169 MUTEX_EXIT(&call->lock);
5171 rxi_SendPacketList(call, conn, list, len, istack);
5173 rxi_SendPacket(call, conn, list[0], istack);
5175 MUTEX_ENTER(&call->lock);
5176 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5178 /* Update last send time for this call (for keep-alive
5179 * processing), and for the connection (so that we can discover
5180 * idle connections) */
5181 call->lastSendData = conn->lastSendTime = call->lastSendTime = clock_Sec();
5184 /* When sending packets we need to follow these rules:
5185 * 1. Never send more than maxDgramPackets in a jumbogram.
5186 * 2. Never send a packet with more than two iovecs in a jumbogram.
5187 * 3. Never send a retransmitted packet in a jumbogram.
5188 * 4. Never send more than cwind/4 packets in a jumbogram
5189 * We always keep the last list we should have sent so we
5190 * can set the RX_MORE_PACKETS flags correctly.
5193 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5194 int istack, struct clock *now, struct clock *retryTime,
5197 int i, cnt, lastCnt = 0;
5198 struct rx_packet **listP, **lastP = 0;
5199 struct rx_peer *peer = call->conn->peer;
5200 int morePackets = 0;
5202 for (cnt = 0, listP = &list[0], i = 0; i < len; i++) {
5203 /* Does the current packet force us to flush the current list? */
5205 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5206 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5208 rxi_SendList(call, lastP, lastCnt, istack, 1, now, retryTime,
5210 /* If the call enters an error state stop sending, or if
5211 * we entered congestion recovery mode, stop sending */
5212 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5220 /* Add the current packet to the list if it hasn't been acked.
5221 * Otherwise adjust the list pointer to skip the current packet. */
5222 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5224 /* Do we need to flush the list? */
5225 if (cnt >= (int)peer->maxDgramPackets
5226 || cnt >= (int)call->nDgramPackets || cnt >= (int)call->cwind
5227 || list[i]->header.serial
5228 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5230 rxi_SendList(call, lastP, lastCnt, istack, 1, now,
5231 retryTime, resending);
5232 /* If the call enters an error state stop sending, or if
5233 * we entered congestion recovery mode, stop sending */
5235 || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5240 listP = &list[i + 1];
5245 osi_Panic("rxi_SendList error");
5247 listP = &list[i + 1];
5251 /* Send the whole list when the call is in receive mode, when
5252 * the call is in eof mode, when we are in fast recovery mode,
5253 * and when we have the last packet */
5254 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5255 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5256 || (call->flags & RX_CALL_FAST_RECOVER)) {
5257 /* Check for the case where the current list contains
5258 * an acked packet. Since we always send retransmissions
5259 * in a separate packet, we only need to check the first
5260 * packet in the list */
5261 if (cnt > 0 && !(listP[0]->flags & RX_PKTFLAG_ACKED)) {
5265 rxi_SendList(call, lastP, lastCnt, istack, morePackets, now,
5266 retryTime, resending);
5267 /* If the call enters an error state stop sending, or if
5268 * we entered congestion recovery mode, stop sending */
5269 if (call->error || (call->flags & RX_CALL_FAST_RECOVER_WAIT))
5273 rxi_SendList(call, listP, cnt, istack, 0, now, retryTime,
5276 } else if (lastCnt > 0) {
5277 rxi_SendList(call, lastP, lastCnt, istack, 0, now, retryTime,
5282 #ifdef RX_ENABLE_LOCKS
5283 /* Call rxi_Start, below, but with the call lock held. */
5285 rxi_StartUnlocked(struct rxevent *event,
5286 void *arg0, void *arg1, int istack)
5288 struct rx_call *call = arg0;
5290 MUTEX_ENTER(&call->lock);
5291 rxi_Start(event, call, arg1, istack);
5292 MUTEX_EXIT(&call->lock);
5294 #endif /* RX_ENABLE_LOCKS */
5296 /* This routine is called when new packets are readied for
5297 * transmission and when retransmission may be necessary, or when the
5298 * transmission window or burst count are favourable. This should be
5299 * better optimized for new packets, the usual case, now that we've
5300 * got rid of queues of send packets. XXXXXXXXXXX */
5302 rxi_Start(struct rxevent *event,
5303 void *arg0, void *arg1, int istack)
5305 struct rx_call *call = arg0;
5307 struct rx_packet *p;
5308 register struct rx_packet *nxp; /* Next pointer for queue_Scan */
5309 struct rx_peer *peer = call->conn->peer;
5310 struct clock now, usenow, retryTime;
5314 struct rx_packet **xmitList;
5317 /* If rxi_Start is being called as a result of a resend event,
5318 * then make sure that the event pointer is removed from the call
5319 * structure, since there is no longer a per-call retransmission
5321 if (event && event == call->resendEvent) {
5322 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5323 call->resendEvent = NULL;
5325 if (queue_IsEmpty(&call->tq)) {
5329 /* Timeouts trigger congestion recovery */
5330 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5331 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5332 /* someone else is waiting to start recovery */
5335 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
5336 rxi_WaitforTQBusy(call);
5337 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5338 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
5339 call->flags |= RX_CALL_FAST_RECOVER;
5340 if (peer->maxDgramPackets > 1) {
5341 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5343 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5345 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5346 call->nDgramPackets = 1;
5348 call->nextCwind = 1;
5351 MUTEX_ENTER(&peer->peer_lock);
5352 peer->MTU = call->MTU;
5353 peer->cwind = call->cwind;
5354 peer->nDgramPackets = 1;
5356 call->congestSeq = peer->congestSeq;
5357 MUTEX_EXIT(&peer->peer_lock);
5358 /* Clear retry times on packets. Otherwise, it's possible for
5359 * some packets in the queue to force resends at rates faster
5360 * than recovery rates.
5362 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5363 if (!(p->flags & RX_PKTFLAG_ACKED)) {
5364 clock_Zero(&p->retryTime);
5369 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5370 if (rx_stats_active)
5371 rx_MutexIncrement(rx_tq_debug.rxi_start_in_error, rx_stats_mutex);
5376 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5377 /* Get clock to compute the re-transmit time for any packets
5378 * in this burst. Note, if we back off, it's reasonable to
5379 * back off all of the packets in the same manner, even if
5380 * some of them have been retransmitted more times than more
5382 * Do a dance to avoid blocking after setting now. */
5383 clock_Zero(&retryTime);
5384 MUTEX_ENTER(&peer->peer_lock);
5385 clock_Add(&retryTime, &peer->timeout);
5386 MUTEX_EXIT(&peer->peer_lock);
5387 clock_GetTime(&now);
5388 clock_Add(&retryTime, &now);
5390 /* Send (or resend) any packets that need it, subject to
5391 * window restrictions and congestion burst control
5392 * restrictions. Ask for an ack on the last packet sent in
5393 * this burst. For now, we're relying upon the window being
5394 * considerably bigger than the largest number of packets that
5395 * are typically sent at once by one initial call to
5396 * rxi_Start. This is probably bogus (perhaps we should ask
5397 * for an ack when we're half way through the current
5398 * window?). Also, for non file transfer applications, this
5399 * may end up asking for an ack for every packet. Bogus. XXXX
5402 * But check whether we're here recursively, and let the other guy
5405 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5406 if (!(call->flags & RX_CALL_TQ_BUSY)) {
5407 call->flags |= RX_CALL_TQ_BUSY;
5409 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5411 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5412 call->flags &= ~RX_CALL_NEED_START;
5413 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5415 maxXmitPackets = MIN(call->twind, call->cwind);
5416 xmitList = (struct rx_packet **)
5417 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
5418 /* XXXX else we must drop any mtx we hold */
5419 afs_osi_Alloc_NoSleep(maxXmitPackets * sizeof(struct rx_packet *));
5421 osi_Alloc(maxXmitPackets * sizeof(struct rx_packet *));
5423 if (xmitList == NULL)
5424 osi_Panic("rxi_Start, failed to allocate xmit list");
5425 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5426 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5427 /* We shouldn't be sending packets if a thread is waiting
5428 * to initiate congestion recovery */
5432 && (call->flags & RX_CALL_FAST_RECOVER)) {
5433 /* Only send one packet during fast recovery */
5436 if ((p->flags & RX_PKTFLAG_FREE)
5437 || (!queue_IsEnd(&call->tq, nxp)
5438 && (nxp->flags & RX_PKTFLAG_FREE))
5439 || (p == (struct rx_packet *)&rx_freePacketQueue)
5440 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
5441 osi_Panic("rxi_Start: xmit queue clobbered");
5443 if (p->flags & RX_PKTFLAG_ACKED) {
5444 /* Since we may block, don't trust this */
5445 usenow.sec = usenow.usec = 0;
5446 if (rx_stats_active)
5447 rx_MutexIncrement(rx_stats.ignoreAckedPacket, rx_stats_mutex);
5448 continue; /* Ignore this packet if it has been acknowledged */
5451 /* Turn off all flags except these ones, which are the same
5452 * on each transmission */
5453 p->header.flags &= RX_PRESET_FLAGS;
5455 if (p->header.seq >=
5456 call->tfirst + MIN((int)call->twind,
5457 (int)(call->nSoftAcked +
5459 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
5460 /* Note: if we're waiting for more window space, we can
5461 * still send retransmits; hence we don't return here, but
5462 * break out to schedule a retransmit event */
5463 dpf(("call %d waiting for window",
5464 *(call->callNumber)));
5468 /* Transmit the packet if it needs to be sent. */
5469 if (!clock_Lt(&now, &p->retryTime)) {
5470 if (nXmitPackets == maxXmitPackets) {
5471 rxi_SendXmitList(call, xmitList, nXmitPackets,
5472 istack, &now, &retryTime,
5474 osi_Free(xmitList, maxXmitPackets *
5475 sizeof(struct rx_packet *));
5478 xmitList[nXmitPackets++] = p;
5482 /* xmitList now hold pointers to all of the packets that are
5483 * ready to send. Now we loop to send the packets */
5484 if (nXmitPackets > 0) {
5485 rxi_SendXmitList(call, xmitList, nXmitPackets, istack,
5486 &now, &retryTime, resending);
5489 maxXmitPackets * sizeof(struct rx_packet *));
5491 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5493 * TQ references no longer protected by this flag; they must remain
5494 * protected by the global lock.
5496 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
5497 call->flags &= ~RX_CALL_TQ_BUSY;
5498 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5499 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5500 #ifdef RX_ENABLE_LOCKS
5501 osirx_AssertMine(&call->lock, "rxi_Start start");
5502 CV_BROADCAST(&call->cv_tq);
5503 #else /* RX_ENABLE_LOCKS */
5504 osi_rxWakeup(&call->tq);
5505 #endif /* RX_ENABLE_LOCKS */
5510 /* We went into the error state while sending packets. Now is
5511 * the time to reset the call. This will also inform the using
5512 * process that the call is in an error state.
5514 if (rx_stats_active)
5515 rx_MutexIncrement(rx_tq_debug.rxi_start_aborted, rx_stats_mutex);
5516 call->flags &= ~RX_CALL_TQ_BUSY;
5517 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5518 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5519 #ifdef RX_ENABLE_LOCKS
5520 osirx_AssertMine(&call->lock, "rxi_Start middle");
5521 CV_BROADCAST(&call->cv_tq);
5522 #else /* RX_ENABLE_LOCKS */
5523 osi_rxWakeup(&call->tq);
5524 #endif /* RX_ENABLE_LOCKS */
5526 rxi_CallError(call, call->error);
5529 #ifdef RX_ENABLE_LOCKS
5530 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
5531 register int missing;
5532 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
5533 /* Some packets have received acks. If they all have, we can clear
5534 * the transmit queue.
5537 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5538 if (p->header.seq < call->tfirst
5539 && (p->flags & RX_PKTFLAG_ACKED)) {
5541 p->flags &= ~RX_PKTFLAG_TQ;
5542 #ifdef RXDEBUG_PACKET
5550 call->flags |= RX_CALL_TQ_CLEARME;
5552 #endif /* RX_ENABLE_LOCKS */
5553 /* Don't bother doing retransmits if the TQ is cleared. */
5554 if (call->flags & RX_CALL_TQ_CLEARME) {
5555 rxi_ClearTransmitQueue(call, 1);
5557 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5560 /* Always post a resend event, if there is anything in the
5561 * queue, and resend is possible. There should be at least
5562 * one unacknowledged packet in the queue ... otherwise none
5563 * of these packets should be on the queue in the first place.
5565 if (call->resendEvent) {
5566 /* Cancel the existing event and post a new one */
5567 rxevent_Cancel(call->resendEvent, call,
5568 RX_CALL_REFCOUNT_RESEND);
5571 /* The retry time is the retry time on the first unacknowledged
5572 * packet inside the current window */
5574 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
5575 /* Don't set timers for packets outside the window */
5576 if (p->header.seq >= call->tfirst + call->twind) {
5580 if (!(p->flags & RX_PKTFLAG_ACKED)
5581 && !clock_IsZero(&p->retryTime)) {
5583 retryTime = p->retryTime;
5588 /* Post a new event to re-run rxi_Start when retries may be needed */
5589 if (haveEvent && !(call->flags & RX_CALL_NEED_START)) {
5590 #ifdef RX_ENABLE_LOCKS
5591 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
5593 rxevent_PostNow2(&retryTime, &usenow,
5595 (void *)call, 0, istack);
5596 #else /* RX_ENABLE_LOCKS */
5598 rxevent_PostNow2(&retryTime, &usenow, rxi_Start,
5599 (void *)call, 0, istack);
5600 #endif /* RX_ENABLE_LOCKS */
5603 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5604 } while (call->flags & RX_CALL_NEED_START);
5606 * TQ references no longer protected by this flag; they must remain
5607 * protected by the global lock.
5609 call->flags &= ~RX_CALL_TQ_BUSY;
5610 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
5611 dpf(("call %x has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5612 #ifdef RX_ENABLE_LOCKS
5613 osirx_AssertMine(&call->lock, "rxi_Start end");
5614 CV_BROADCAST(&call->cv_tq);
5615 #else /* RX_ENABLE_LOCKS */
5616 osi_rxWakeup(&call->tq);
5617 #endif /* RX_ENABLE_LOCKS */
5620 call->flags |= RX_CALL_NEED_START;
5622 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5624 if (call->resendEvent) {
5625 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5630 /* Also adjusts the keep alive parameters for the call, to reflect
5631 * that we have just sent a packet (so keep alives aren't sent
5634 rxi_Send(register struct rx_call *call, register struct rx_packet *p,
5637 register struct rx_connection *conn = call->conn;
5639 /* Stamp each packet with the user supplied status */
5640 p->header.userStatus = call->localStatus;
5642 /* Allow the security object controlling this call's security to
5643 * make any last-minute changes to the packet */
5644 RXS_SendPacket(conn->securityObject, call, p);
5646 /* Since we're about to send SOME sort of packet to the peer, it's
5647 * safe to nuke any scheduled end-of-packets ack */
5648 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5650 /* Actually send the packet, filling in more connection-specific fields */
5651 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5652 MUTEX_EXIT(&call->lock);
5653 rxi_SendPacket(call, conn, p, istack);
5654 MUTEX_ENTER(&call->lock);
5655 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5657 /* Update last send time for this call (for keep-alive
5658 * processing), and for the connection (so that we can discover
5659 * idle connections) */
5660 conn->lastSendTime = call->lastSendTime = clock_Sec();
5661 /* Don't count keepalives here, so idleness can be tracked. */
5662 if ((p->header.type != RX_PACKET_TYPE_ACK) || (((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING))
5663 call->lastSendData = call->lastSendTime;
5667 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
5668 * that things are fine. Also called periodically to guarantee that nothing
5669 * falls through the cracks (e.g. (error + dally) connections have keepalive
5670 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
5672 * haveCTLock Set if calling from rxi_ReapConnections
5674 #ifdef RX_ENABLE_LOCKS
5676 rxi_CheckCall(register struct rx_call *call, int haveCTLock)
5677 #else /* RX_ENABLE_LOCKS */
5679 rxi_CheckCall(register struct rx_call *call)
5680 #endif /* RX_ENABLE_LOCKS */
5682 register struct rx_connection *conn = call->conn;
5684 afs_uint32 deadTime;
5686 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5687 if (call->flags & RX_CALL_TQ_BUSY) {
5688 /* Call is active and will be reset by rxi_Start if it's
5689 * in an error state.
5694 /* dead time + RTT + 8*MDEV, rounded up to next second. */
5696 (((afs_uint32) rx_ConnSecondsUntilDead(conn) << 10) +
5697 ((afs_uint32) conn->peer->rtt >> 3) +
5698 ((afs_uint32) conn->peer->rtt_dev << 1) + 1023) >> 10;
5700 /* These are computed to the second (+- 1 second). But that's
5701 * good enough for these values, which should be a significant
5702 * number of seconds. */
5703 if (now > (call->lastReceiveTime + deadTime)) {
5704 if (call->state == RX_STATE_ACTIVE) {
5706 #if defined(KERNEL) && defined(AFS_SUN57_ENV)
5708 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5709 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
5710 ip_stack_t *ipst = ns->netstack_ip;
5712 ire = ire_cache_lookup(call->conn->peer->host
5713 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
5715 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
5717 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
5724 if (ire && ire->ire_max_frag > 0)
5725 rxi_SetPeerMtu(call->conn->peer->host, 0, ire->ire_max_frag);
5726 #if defined(GLOBAL_NETSTACKID)
5730 #endif /* ADAPT_PMTU */
5731 rxi_CallError(call, RX_CALL_DEAD);
5734 #ifdef RX_ENABLE_LOCKS
5735 /* Cancel pending events */
5736 rxevent_Cancel(call->delayedAckEvent, call,
5737 RX_CALL_REFCOUNT_DELAY);
5738 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
5739 rxevent_Cancel(call->keepAliveEvent, call,
5740 RX_CALL_REFCOUNT_ALIVE);
5741 if (call->refCount == 0) {
5742 rxi_FreeCall(call, haveCTLock);
5746 #else /* RX_ENABLE_LOCKS */
5749 #endif /* RX_ENABLE_LOCKS */
5751 /* Non-active calls are destroyed if they are not responding
5752 * to pings; active calls are simply flagged in error, so the
5753 * attached process can die reasonably gracefully. */
5755 /* see if we have a non-activity timeout */
5756 if (call->startWait && rx_ConnIdleDeadTime(conn)
5757 && ((call->startWait + rx_ConnIdleDeadTime(conn)) < now)) {
5758 if (call->state == RX_STATE_ACTIVE) {
5759 rxi_CallError(call, RX_CALL_TIMEOUT);
5763 if (call->lastSendData && rx_ConnIdleDeadTime(conn)
5764 && (rx_ConnIdleDeadErr(conn) != 0)
5765 && ((call->lastSendData + rx_ConnIdleDeadTime(conn)) < now)) {
5766 if (call->state == RX_STATE_ACTIVE) {
5767 rxi_CallError(call, conn->idleDeadErr);
5771 /* see if we have a hard timeout */
5772 if (rx_ConnHardDeadTime(conn)
5773 && (now > (rx_ConnHardDeadTime(conn) + call->startTime.sec))) {
5774 if (call->state == RX_STATE_ACTIVE)
5775 rxi_CallError(call, RX_CALL_TIMEOUT);
5782 /* When a call is in progress, this routine is called occasionally to
5783 * make sure that some traffic has arrived (or been sent to) the peer.
5784 * If nothing has arrived in a reasonable amount of time, the call is
5785 * declared dead; if nothing has been sent for a while, we send a
5786 * keep-alive packet (if we're actually trying to keep the call alive)
5789 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy)
5791 struct rx_call *call = arg1;
5792 struct rx_connection *conn;
5795 MUTEX_ENTER(&call->lock);
5796 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
5797 if (event == call->keepAliveEvent)
5798 call->keepAliveEvent = NULL;
5801 #ifdef RX_ENABLE_LOCKS
5802 if (rxi_CheckCall(call, 0)) {
5803 MUTEX_EXIT(&call->lock);
5806 #else /* RX_ENABLE_LOCKS */
5807 if (rxi_CheckCall(call))
5809 #endif /* RX_ENABLE_LOCKS */
5811 /* Don't try to keep alive dallying calls */
5812 if (call->state == RX_STATE_DALLY) {
5813 MUTEX_EXIT(&call->lock);
5818 if ((now - call->lastSendTime) > rx_ConnSecondsUntilPing(conn)) {
5819 /* Don't try to send keepalives if there is unacknowledged data */
5820 /* the rexmit code should be good enough, this little hack
5821 * doesn't quite work XXX */
5822 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
5824 rxi_ScheduleKeepAliveEvent(call);
5825 MUTEX_EXIT(&call->lock);
5830 rxi_ScheduleKeepAliveEvent(register struct rx_call *call)
5832 if (!call->keepAliveEvent) {
5833 struct clock when, now;
5834 clock_GetTime(&now);
5836 when.sec += rx_ConnSecondsUntilPing(call->conn);
5837 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
5838 call->keepAliveEvent =
5839 rxevent_PostNow(&when, &now, rxi_KeepAliveEvent, call, 0);
5843 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
5845 rxi_KeepAliveOn(register struct rx_call *call)
5847 /* Pretend last packet received was received now--i.e. if another
5848 * packet isn't received within the keep alive time, then the call
5849 * will die; Initialize last send time to the current time--even
5850 * if a packet hasn't been sent yet. This will guarantee that a
5851 * keep-alive is sent within the ping time */
5852 call->lastReceiveTime = call->lastSendTime = clock_Sec();
5853 rxi_ScheduleKeepAliveEvent(call);
5856 /* This routine is called to send connection abort messages
5857 * that have been delayed to throttle looping clients. */
5859 rxi_SendDelayedConnAbort(struct rxevent *event,
5860 void *arg1, void *unused)
5862 struct rx_connection *conn = arg1;
5865 struct rx_packet *packet;
5867 MUTEX_ENTER(&conn->conn_data_lock);
5868 conn->delayedAbortEvent = NULL;
5869 error = htonl(rx_ConnError(conn));
5871 MUTEX_EXIT(&conn->conn_data_lock);
5872 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5875 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5876 RX_PACKET_TYPE_ABORT, (char *)&error,
5878 rxi_FreePacket(packet);
5882 /* This routine is called to send call abort messages
5883 * that have been delayed to throttle looping clients. */
5885 rxi_SendDelayedCallAbort(struct rxevent *event,
5886 void *arg1, void *dummy)
5888 struct rx_call *call = arg1;
5891 struct rx_packet *packet;
5893 MUTEX_ENTER(&call->lock);
5894 call->delayedAbortEvent = NULL;
5895 error = htonl(call->error);
5897 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5900 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5901 (char *)&error, sizeof(error), 0);
5902 rxi_FreePacket(packet);
5904 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5905 MUTEX_EXIT(&call->lock);
5908 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
5909 * seconds) to ask the client to authenticate itself. The routine
5910 * issues a challenge to the client, which is obtained from the
5911 * security object associated with the connection */
5913 rxi_ChallengeEvent(struct rxevent *event,
5914 void *arg0, void *arg1, int tries)
5916 struct rx_connection *conn = arg0;
5918 conn->challengeEvent = NULL;
5919 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
5920 register struct rx_packet *packet;
5921 struct clock when, now;
5924 /* We've failed to authenticate for too long.
5925 * Reset any calls waiting for authentication;
5926 * they are all in RX_STATE_PRECALL.
5930 MUTEX_ENTER(&conn->conn_call_lock);
5931 for (i = 0; i < RX_MAXCALLS; i++) {
5932 struct rx_call *call = conn->call[i];
5934 MUTEX_ENTER(&call->lock);
5935 if (call->state == RX_STATE_PRECALL) {
5936 rxi_CallError(call, RX_CALL_DEAD);
5937 rxi_SendCallAbort(call, NULL, 0, 0);
5939 MUTEX_EXIT(&call->lock);
5942 MUTEX_EXIT(&conn->conn_call_lock);
5946 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5948 /* If there's no packet available, do this later. */
5949 RXS_GetChallenge(conn->securityObject, conn, packet);
5950 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5951 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
5952 rxi_FreePacket(packet);
5954 clock_GetTime(&now);
5956 when.sec += RX_CHALLENGE_TIMEOUT;
5957 conn->challengeEvent =
5958 rxevent_PostNow2(&when, &now, rxi_ChallengeEvent, conn, 0,
5963 /* Call this routine to start requesting the client to authenticate
5964 * itself. This will continue until authentication is established,
5965 * the call times out, or an invalid response is returned. The
5966 * security object associated with the connection is asked to create
5967 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
5968 * defined earlier. */
5970 rxi_ChallengeOn(register struct rx_connection *conn)
5972 if (!conn->challengeEvent) {
5973 RXS_CreateChallenge(conn->securityObject, conn);
5974 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
5979 /* Compute round trip time of the packet provided, in *rttp.
5982 /* rxi_ComputeRoundTripTime is called with peer locked. */
5983 /* sentp and/or peer may be null */
5985 rxi_ComputeRoundTripTime(register struct rx_packet *p,
5986 register struct clock *sentp,
5987 register struct rx_peer *peer)
5989 struct clock thisRtt, *rttp = &thisRtt;
5991 register int rtt_timeout;
5993 clock_GetTime(rttp);
5995 if (clock_Lt(rttp, sentp)) {
5997 return; /* somebody set the clock back, don't count this time. */
5999 clock_Sub(rttp, sentp);
6000 if (rx_stats_active) {
6001 MUTEX_ENTER(&rx_stats_mutex);
6002 if (clock_Lt(rttp, &rx_stats.minRtt))
6003 rx_stats.minRtt = *rttp;
6004 if (clock_Gt(rttp, &rx_stats.maxRtt)) {
6005 if (rttp->sec > 60) {
6006 MUTEX_EXIT(&rx_stats_mutex);
6007 return; /* somebody set the clock ahead */
6009 rx_stats.maxRtt = *rttp;
6011 clock_Add(&rx_stats.totalRtt, rttp);
6012 rx_stats.nRttSamples++;
6013 MUTEX_EXIT(&rx_stats_mutex);
6016 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6018 /* Apply VanJacobson round-trip estimations */
6023 * srtt (peer->rtt) is in units of one-eighth-milliseconds.
6024 * srtt is stored as fixed point with 3 bits after the binary
6025 * point (i.e., scaled by 8). The following magic is
6026 * equivalent to the smoothing algorithm in rfc793 with an
6027 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6028 * srtt*8 = srtt*8 + rtt - srtt
6029 * srtt = srtt + rtt/8 - srtt/8
6032 delta = MSEC(rttp) - (peer->rtt >> 3);
6036 * We accumulate a smoothed rtt variance (actually, a smoothed
6037 * mean difference), then set the retransmit timer to smoothed
6038 * rtt + 4 times the smoothed variance (was 2x in van's original
6039 * paper, but 4x works better for me, and apparently for him as
6041 * rttvar is stored as
6042 * fixed point with 2 bits after the binary point (scaled by
6043 * 4). The following is equivalent to rfc793 smoothing with
6044 * an alpha of .75 (rttvar = rttvar*3/4 + |delta| / 4). This
6045 * replaces rfc793's wired-in beta.
6046 * dev*4 = dev*4 + (|actual - expected| - dev)
6052 delta -= (peer->rtt_dev >> 2);
6053 peer->rtt_dev += delta;
6055 /* I don't have a stored RTT so I start with this value. Since I'm
6056 * probably just starting a call, and will be pushing more data down
6057 * this, I expect congestion to increase rapidly. So I fudge a
6058 * little, and I set deviance to half the rtt. In practice,
6059 * deviance tends to approach something a little less than
6060 * half the smoothed rtt. */
6061 peer->rtt = (MSEC(rttp) << 3) + 8;
6062 peer->rtt_dev = peer->rtt >> 2; /* rtt/2: they're scaled differently */
6064 /* the timeout is RTT + 4*MDEV + 0.35 sec This is because one end or
6065 * the other of these connections is usually in a user process, and can
6066 * be switched and/or swapped out. So on fast, reliable networks, the
6067 * timeout would otherwise be too short.
6069 rtt_timeout = (peer->rtt >> 3) + peer->rtt_dev + 350;
6070 clock_Zero(&(peer->timeout));
6071 clock_Addmsec(&(peer->timeout), rtt_timeout);
6073 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)));
6077 /* Find all server connections that have not been active for a long time, and
6080 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2)
6082 struct clock now, when;
6083 clock_GetTime(&now);
6085 /* Find server connection structures that haven't been used for
6086 * greater than rx_idleConnectionTime */
6088 struct rx_connection **conn_ptr, **conn_end;
6089 int i, havecalls = 0;
6090 MUTEX_ENTER(&rx_connHashTable_lock);
6091 for (conn_ptr = &rx_connHashTable[0], conn_end =
6092 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6094 struct rx_connection *conn, *next;
6095 struct rx_call *call;
6099 for (conn = *conn_ptr; conn; conn = next) {
6100 /* XXX -- Shouldn't the connection be locked? */
6103 for (i = 0; i < RX_MAXCALLS; i++) {
6104 call = conn->call[i];
6107 MUTEX_ENTER(&call->lock);
6108 #ifdef RX_ENABLE_LOCKS
6109 result = rxi_CheckCall(call, 1);
6110 #else /* RX_ENABLE_LOCKS */
6111 result = rxi_CheckCall(call);
6112 #endif /* RX_ENABLE_LOCKS */
6113 MUTEX_EXIT(&call->lock);
6115 /* If CheckCall freed the call, it might
6116 * have destroyed the connection as well,
6117 * which screws up the linked lists.
6123 if (conn->type == RX_SERVER_CONNECTION) {
6124 /* This only actually destroys the connection if
6125 * there are no outstanding calls */
6126 MUTEX_ENTER(&conn->conn_data_lock);
6127 if (!havecalls && !conn->refCount
6128 && ((conn->lastSendTime + rx_idleConnectionTime) <
6130 conn->refCount++; /* it will be decr in rx_DestroyConn */
6131 MUTEX_EXIT(&conn->conn_data_lock);
6132 #ifdef RX_ENABLE_LOCKS
6133 rxi_DestroyConnectionNoLock(conn);
6134 #else /* RX_ENABLE_LOCKS */
6135 rxi_DestroyConnection(conn);
6136 #endif /* RX_ENABLE_LOCKS */
6138 #ifdef RX_ENABLE_LOCKS
6140 MUTEX_EXIT(&conn->conn_data_lock);
6142 #endif /* RX_ENABLE_LOCKS */
6146 #ifdef RX_ENABLE_LOCKS
6147 while (rx_connCleanup_list) {
6148 struct rx_connection *conn;
6149 conn = rx_connCleanup_list;
6150 rx_connCleanup_list = rx_connCleanup_list->next;
6151 MUTEX_EXIT(&rx_connHashTable_lock);
6152 rxi_CleanupConnection(conn);
6153 MUTEX_ENTER(&rx_connHashTable_lock);
6155 MUTEX_EXIT(&rx_connHashTable_lock);
6156 #endif /* RX_ENABLE_LOCKS */
6159 /* Find any peer structures that haven't been used (haven't had an
6160 * associated connection) for greater than rx_idlePeerTime */
6162 struct rx_peer **peer_ptr, **peer_end;
6164 MUTEX_ENTER(&rx_rpc_stats);
6165 MUTEX_ENTER(&rx_peerHashTable_lock);
6166 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6167 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6169 struct rx_peer *peer, *next, *prev;
6170 for (prev = peer = *peer_ptr; peer; peer = next) {
6172 code = MUTEX_TRYENTER(&peer->peer_lock);
6173 if ((code) && (peer->refCount == 0)
6174 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6175 rx_interface_stat_p rpc_stat, nrpc_stat;
6177 MUTEX_EXIT(&peer->peer_lock);
6178 MUTEX_DESTROY(&peer->peer_lock);
6180 (&peer->rpcStats, rpc_stat, nrpc_stat,
6181 rx_interface_stat)) {
6182 unsigned int num_funcs;
6185 queue_Remove(&rpc_stat->queue_header);
6186 queue_Remove(&rpc_stat->all_peers);
6187 num_funcs = rpc_stat->stats[0].func_total;
6189 sizeof(rx_interface_stat_t) +
6190 rpc_stat->stats[0].func_total *
6191 sizeof(rx_function_entry_v1_t);
6193 rxi_Free(rpc_stat, space);
6194 rxi_rpc_peer_stat_cnt -= num_funcs;
6197 if (rx_stats_active)
6198 rx_MutexDecrement(rx_stats.nPeerStructs, rx_stats_mutex);
6199 if (peer == *peer_ptr) {
6206 MUTEX_EXIT(&peer->peer_lock);
6212 MUTEX_EXIT(&rx_peerHashTable_lock);
6213 MUTEX_EXIT(&rx_rpc_stats);
6216 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
6217 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
6218 * GC, just below. Really, we shouldn't have to keep moving packets from
6219 * one place to another, but instead ought to always know if we can
6220 * afford to hold onto a packet in its particular use. */
6221 MUTEX_ENTER(&rx_freePktQ_lock);
6222 if (rx_waitingForPackets) {
6223 rx_waitingForPackets = 0;
6224 #ifdef RX_ENABLE_LOCKS
6225 CV_BROADCAST(&rx_waitingForPackets_cv);
6227 osi_rxWakeup(&rx_waitingForPackets);
6230 MUTEX_EXIT(&rx_freePktQ_lock);
6233 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
6234 rxevent_Post(&when, rxi_ReapConnections, 0, 0);
6238 /* rxs_Release - This isn't strictly necessary but, since the macro name from
6239 * rx.h is sort of strange this is better. This is called with a security
6240 * object before it is discarded. Each connection using a security object has
6241 * its own refcount to the object so it won't actually be freed until the last
6242 * connection is destroyed.
6244 * This is the only rxs module call. A hold could also be written but no one
6248 rxs_Release(struct rx_securityClass *aobj)
6250 return RXS_Close(aobj);
6254 #define RXRATE_PKT_OH (RX_HEADER_SIZE + RX_IPUDP_SIZE)
6255 #define RXRATE_SMALL_PKT (RXRATE_PKT_OH + sizeof(struct rx_ackPacket))
6256 #define RXRATE_AVG_SMALL_PKT (RXRATE_PKT_OH + (sizeof(struct rx_ackPacket)/2))
6257 #define RXRATE_LARGE_PKT (RXRATE_SMALL_PKT + 256)
6259 /* Adjust our estimate of the transmission rate to this peer, given
6260 * that the packet p was just acked. We can adjust peer->timeout and
6261 * call->twind. Pragmatically, this is called
6262 * only with packets of maximal length.
6263 * Called with peer and call locked.
6267 rxi_ComputeRate(register struct rx_peer *peer, register struct rx_call *call,
6268 struct rx_packet *p, struct rx_packet *ackp, u_char ackReason)
6270 afs_int32 xferSize, xferMs;
6271 register afs_int32 minTime;
6274 /* Count down packets */
6275 if (peer->rateFlag > 0)
6277 /* Do nothing until we're enabled */
6278 if (peer->rateFlag != 0)
6283 /* Count only when the ack seems legitimate */
6284 switch (ackReason) {
6285 case RX_ACK_REQUESTED:
6287 p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize;
6291 case RX_ACK_PING_RESPONSE:
6292 if (p) /* want the response to ping-request, not data send */
6294 clock_GetTime(&newTO);
6295 if (clock_Gt(&newTO, &call->pingRequestTime)) {
6296 clock_Sub(&newTO, &call->pingRequestTime);
6297 xferMs = (newTO.sec * 1000) + (newTO.usec / 1000);
6301 xferSize = rx_AckDataSize(rx_Window) + RX_HEADER_SIZE;
6308 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));
6310 /* Track only packets that are big enough. */
6311 if ((p->length + RX_HEADER_SIZE + call->conn->securityMaxTrailerSize) <
6315 /* absorb RTT data (in milliseconds) for these big packets */
6316 if (peer->smRtt == 0) {
6317 peer->smRtt = xferMs;
6319 peer->smRtt = ((peer->smRtt * 15) + xferMs + 4) >> 4;
6324 if (peer->countDown) {
6328 peer->countDown = 10; /* recalculate only every so often */
6330 /* In practice, we can measure only the RTT for full packets,
6331 * because of the way Rx acks the data that it receives. (If it's
6332 * smaller than a full packet, it often gets implicitly acked
6333 * either by the call response (from a server) or by the next call
6334 * (from a client), and either case confuses transmission times
6335 * with processing times.) Therefore, replace the above
6336 * more-sophisticated processing with a simpler version, where the
6337 * smoothed RTT is kept for full-size packets, and the time to
6338 * transmit a windowful of full-size packets is simply RTT *
6339 * windowSize. Again, we take two steps:
6340 - ensure the timeout is large enough for a single packet's RTT;
6341 - ensure that the window is small enough to fit in the desired timeout.*/
6343 /* First, the timeout check. */
6344 minTime = peer->smRtt;
6345 /* Get a reasonable estimate for a timeout period */
6347 newTO.sec = minTime / 1000;
6348 newTO.usec = (minTime - (newTO.sec * 1000)) * 1000;
6350 /* Increase the timeout period so that we can always do at least
6351 * one packet exchange */
6352 if (clock_Gt(&newTO, &peer->timeout)) {
6354 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));
6356 peer->timeout = newTO;
6359 /* Now, get an estimate for the transmit window size. */
6360 minTime = peer->timeout.sec * 1000 + (peer->timeout.usec / 1000);
6361 /* Now, convert to the number of full packets that could fit in a
6362 * reasonable fraction of that interval */
6363 minTime /= (peer->smRtt << 1);
6364 xferSize = minTime; /* (make a copy) */
6366 /* Now clamp the size to reasonable bounds. */
6369 else if (minTime > rx_Window)
6370 minTime = rx_Window;
6371 /* if (minTime != peer->maxWindow) {
6372 dpf(("CONG peer %lx/%u: windowsize %lu ==> %lu (to %lu.%06lu, rtt %u, ps %u)",
6373 ntohl(peer->host), ntohs(peer->port), peer->maxWindow, minTime,
6374 peer->timeout.sec, peer->timeout.usec, peer->smRtt,
6376 peer->maxWindow = minTime;
6377 elide... call->twind = minTime;
6381 /* Cut back on the peer timeout if it had earlier grown unreasonably.
6382 * Discern this by calculating the timeout necessary for rx_Window
6384 if ((xferSize > rx_Window) && (peer->timeout.sec >= 3)) {
6385 /* calculate estimate for transmission interval in milliseconds */
6386 minTime = rx_Window * peer->smRtt;
6387 if (minTime < 1000) {
6388 dpf(("CONG peer %lx/%u: cut TO %lu.%06lu by 0.5 (rtt %u, ps %u)",
6389 ntohl(peer->host), ntohs(peer->port), peer->timeout.sec,
6390 peer->timeout.usec, peer->smRtt, peer->packetSize));
6392 newTO.sec = 0; /* cut back on timeout by half a second */
6393 newTO.usec = 500000;
6394 clock_Sub(&peer->timeout, &newTO);
6399 } /* end of rxi_ComputeRate */
6400 #endif /* ADAPT_WINDOW */
6408 #define TRACE_OPTION_DEBUGLOG 4
6416 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
6417 0, KEY_QUERY_VALUE, &parmKey);
6418 if (code != ERROR_SUCCESS)
6421 dummyLen = sizeof(TraceOption);
6422 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
6423 (BYTE *) &TraceOption, &dummyLen);
6424 if (code == ERROR_SUCCESS) {
6425 rxdebug_active = (TraceOption & TRACE_OPTION_DEBUGLOG) ? 1 : 0;
6427 RegCloseKey (parmKey);
6428 #endif /* AFS_NT40_ENV */
6433 rx_DebugOnOff(int on)
6435 rxdebug_active = on;
6439 rx_StatsOnOff(int on)
6441 rx_stats_active = on;
6443 #endif /* AFS_NT40_ENV */
6446 /* Don't call this debugging routine directly; use dpf */
6448 rxi_DebugPrint(char *format, ...)
6456 va_start(ap, format);
6458 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
6461 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
6463 if (msg[len-1] != '\n') {
6467 OutputDebugString(msg);
6474 va_start(ap, format);
6476 clock_GetTime(&now);
6477 fprintf(rx_Log, " %u.%.3u:", (unsigned int)now.sec,
6478 (unsigned int)now.usec / 1000);
6479 vfprintf(rx_Log, format, ap);
6486 * This function is used to process the rx_stats structure that is local
6487 * to a process as well as an rx_stats structure received from a remote
6488 * process (via rxdebug). Therefore, it needs to do minimal version
6492 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
6493 afs_int32 freePackets, char version)
6497 if (size != sizeof(struct rx_statistics)) {
6499 "Unexpected size of stats structure: was %d, expected %lud\n",
6500 size, sizeof(struct rx_statistics));
6503 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
6506 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6507 fprintf(file, "alloc-failures(rcv %d/%d,send %d/%d,ack %d)\n",
6508 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
6509 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
6510 s->specialPktAllocFailures);
6512 fprintf(file, "alloc-failures(rcv %d,send %d,ack %d)\n",
6513 s->receivePktAllocFailures, s->sendPktAllocFailures,
6514 s->specialPktAllocFailures);
6518 " greedy %d, " "bogusReads %d (last from host %x), "
6519 "noPackets %d, " "noBuffers %d, " "selects %d, "
6520 "sendSelects %d\n", s->socketGreedy, s->bogusPacketOnRead,
6521 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
6522 s->selects, s->sendSelects);
6524 fprintf(file, " packets read: ");
6525 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6526 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsRead[i]);
6528 fprintf(file, "\n");
6531 " other read counters: data %d, " "ack %d, " "dup %d "
6532 "spurious %d " "dally %d\n", s->dataPacketsRead,
6533 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
6534 s->ignorePacketDally);
6536 fprintf(file, " packets sent: ");
6537 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
6538 fprintf(file, "%s %d ", rx_packetTypes[i], s->packetsSent[i]);
6540 fprintf(file, "\n");
6543 " other send counters: ack %d, " "data %d (not resends), "
6544 "resends %d, " "pushed %d, " "acked&ignored %d\n",
6545 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
6546 s->dataPacketsPushed, s->ignoreAckedPacket);
6549 " \t(these should be small) sendFailed %d, " "fatalErrors %d\n",
6550 s->netSendFailures, (int)s->fatalErrors);
6552 if (s->nRttSamples) {
6553 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
6554 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
6556 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
6557 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
6561 " %d server connections, " "%d client connections, "
6562 "%d peer structs, " "%d call structs, " "%d free call structs\n",
6563 s->nServerConns, s->nClientConns, s->nPeerStructs,
6564 s->nCallStructs, s->nFreeCallStructs);
6566 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
6567 fprintf(file, " %d clock updates\n", clock_nUpdates);
6572 /* for backward compatibility */
6574 rx_PrintStats(FILE * file)
6576 MUTEX_ENTER(&rx_stats_mutex);
6577 rx_PrintTheseStats(file, &rx_stats, sizeof(rx_stats), rx_nFreePackets,
6579 MUTEX_EXIT(&rx_stats_mutex);
6583 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
6585 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %u.%d.\n",
6586 ntohl(peer->host), (int)peer->port, (int)peer->burstSize,
6587 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
6590 " Rtt %d, " "retry time %u.%06d, " "total sent %d, "
6591 "resent %d\n", peer->rtt, (int)peer->timeout.sec,
6592 (int)peer->timeout.usec, peer->nSent, peer->reSends);
6595 " Packet size %d, " "max in packet skew %d, "
6596 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
6597 (int)peer->outPacketSkew);
6600 #ifdef AFS_PTHREAD_ENV
6602 * This mutex protects the following static variables:
6606 #define LOCK_RX_DEBUG assert(pthread_mutex_lock(&rx_debug_mutex)==0)
6607 #define UNLOCK_RX_DEBUG assert(pthread_mutex_unlock(&rx_debug_mutex)==0)
6609 #define LOCK_RX_DEBUG
6610 #define UNLOCK_RX_DEBUG
6611 #endif /* AFS_PTHREAD_ENV */
6614 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
6615 u_char type, void *inputData, size_t inputLength,
6616 void *outputData, size_t outputLength)
6618 static afs_int32 counter = 100;
6619 time_t waitTime, waitCount, startTime;
6620 struct rx_header theader;
6622 register afs_int32 code;
6623 struct timeval tv_now, tv_wake, tv_delta;
6624 struct sockaddr_in taddr, faddr;
6633 startTime = time(0);
6639 tp = &tbuffer[sizeof(struct rx_header)];
6640 taddr.sin_family = AF_INET;
6641 taddr.sin_port = remotePort;
6642 taddr.sin_addr.s_addr = remoteAddr;
6643 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6644 taddr.sin_len = sizeof(struct sockaddr_in);
6647 memset(&theader, 0, sizeof(theader));
6648 theader.epoch = htonl(999);
6650 theader.callNumber = htonl(counter);
6653 theader.type = type;
6654 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
6655 theader.serviceId = 0;
6657 memcpy(tbuffer, &theader, sizeof(theader));
6658 memcpy(tp, inputData, inputLength);
6660 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
6661 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
6663 /* see if there's a packet available */
6664 gettimeofday(&tv_wake,0);
6665 tv_wake.tv_sec += waitTime;
6668 FD_SET(socket, &imask);
6669 tv_delta.tv_sec = tv_wake.tv_sec;
6670 tv_delta.tv_usec = tv_wake.tv_usec;
6671 gettimeofday(&tv_now, 0);
6673 if (tv_delta.tv_usec < tv_now.tv_usec) {
6675 tv_delta.tv_usec += 1000000;
6678 tv_delta.tv_usec -= tv_now.tv_usec;
6680 if (tv_delta.tv_sec < tv_now.tv_sec) {
6684 tv_delta.tv_sec -= tv_now.tv_sec;
6686 code = select(socket + 1, &imask, 0, 0, &tv_delta);
6687 if (code == 1 && FD_ISSET(socket, &imask)) {
6688 /* now receive a packet */
6689 faddrLen = sizeof(struct sockaddr_in);
6691 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
6692 (struct sockaddr *)&faddr, &faddrLen);
6695 memcpy(&theader, tbuffer, sizeof(struct rx_header));
6696 if (counter == ntohl(theader.callNumber))
6704 /* see if we've timed out */
6712 code -= sizeof(struct rx_header);
6713 if (code > outputLength)
6714 code = outputLength;
6715 memcpy(outputData, tp, code);
6720 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
6721 afs_uint16 remotePort, struct rx_debugStats * stat,
6722 afs_uint32 * supportedValues)
6724 struct rx_debugIn in;
6727 *supportedValues = 0;
6728 in.type = htonl(RX_DEBUGI_GETSTATS);
6731 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6732 &in, sizeof(in), stat, sizeof(*stat));
6735 * If the call was successful, fixup the version and indicate
6736 * what contents of the stat structure are valid.
6737 * Also do net to host conversion of fields here.
6741 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
6742 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
6744 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
6745 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
6747 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
6748 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
6750 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
6751 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
6753 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
6754 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
6756 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
6757 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
6759 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
6760 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
6762 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
6763 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
6765 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
6766 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
6768 stat->nFreePackets = ntohl(stat->nFreePackets);
6769 stat->packetReclaims = ntohl(stat->packetReclaims);
6770 stat->callsExecuted = ntohl(stat->callsExecuted);
6771 stat->nWaiting = ntohl(stat->nWaiting);
6772 stat->idleThreads = ntohl(stat->idleThreads);
6773 stat->nWaited = ntohl(stat->nWaited);
6774 stat->nPackets = ntohl(stat->nPackets);
6781 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
6782 afs_uint16 remotePort, struct rx_statistics * stat,
6783 afs_uint32 * supportedValues)
6785 struct rx_debugIn in;
6787 afs_int32 *lp = (afs_int32 *) stat;
6791 * supportedValues is currently unused, but added to allow future
6792 * versioning of this function.
6795 *supportedValues = 0;
6796 in.type = htonl(RX_DEBUGI_RXSTATS);
6798 memset(stat, 0, sizeof(*stat));
6800 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6801 &in, sizeof(in), stat, sizeof(*stat));
6806 * Do net to host conversion here
6809 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
6818 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
6819 afs_uint16 remotePort, size_t version_length,
6823 return MakeDebugCall(socket, remoteAddr, remotePort,
6824 RX_PACKET_TYPE_VERSION, a, 1, version,
6829 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
6830 afs_uint16 remotePort, afs_int32 * nextConnection,
6831 int allConnections, afs_uint32 debugSupportedValues,
6832 struct rx_debugConn * conn,
6833 afs_uint32 * supportedValues)
6835 struct rx_debugIn in;
6840 * supportedValues is currently unused, but added to allow future
6841 * versioning of this function.
6844 *supportedValues = 0;
6845 if (allConnections) {
6846 in.type = htonl(RX_DEBUGI_GETALLCONN);
6848 in.type = htonl(RX_DEBUGI_GETCONN);
6850 in.index = htonl(*nextConnection);
6851 memset(conn, 0, sizeof(*conn));
6853 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6854 &in, sizeof(in), conn, sizeof(*conn));
6857 *nextConnection += 1;
6860 * Convert old connection format to new structure.
6863 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
6864 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
6865 #define MOVEvL(a) (conn->a = vL->a)
6867 /* any old or unrecognized version... */
6868 for (i = 0; i < RX_MAXCALLS; i++) {
6869 MOVEvL(callState[i]);
6870 MOVEvL(callMode[i]);
6871 MOVEvL(callFlags[i]);
6872 MOVEvL(callOther[i]);
6874 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
6875 MOVEvL(secStats.type);
6876 MOVEvL(secStats.level);
6877 MOVEvL(secStats.flags);
6878 MOVEvL(secStats.expires);
6879 MOVEvL(secStats.packetsReceived);
6880 MOVEvL(secStats.packetsSent);
6881 MOVEvL(secStats.bytesReceived);
6882 MOVEvL(secStats.bytesSent);
6887 * Do net to host conversion here
6889 * I don't convert host or port since we are most likely
6890 * going to want these in NBO.
6892 conn->cid = ntohl(conn->cid);
6893 conn->serial = ntohl(conn->serial);
6894 for (i = 0; i < RX_MAXCALLS; i++) {
6895 conn->callNumber[i] = ntohl(conn->callNumber[i]);
6897 rx_SetConnError(conn, ntohl(rx_ConnError(conn)));
6898 conn->secStats.flags = ntohl(conn->secStats.flags);
6899 conn->secStats.expires = ntohl(conn->secStats.expires);
6900 conn->secStats.packetsReceived =
6901 ntohl(conn->secStats.packetsReceived);
6902 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
6903 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
6904 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
6905 conn->epoch = ntohl(conn->epoch);
6906 conn->natMTU = ntohl(conn->natMTU);
6913 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
6914 afs_uint16 remotePort, afs_int32 * nextPeer,
6915 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
6916 afs_uint32 * supportedValues)
6918 struct rx_debugIn in;
6922 * supportedValues is currently unused, but added to allow future
6923 * versioning of this function.
6926 *supportedValues = 0;
6927 in.type = htonl(RX_DEBUGI_GETPEER);
6928 in.index = htonl(*nextPeer);
6929 memset(peer, 0, sizeof(*peer));
6931 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
6932 &in, sizeof(in), peer, sizeof(*peer));
6938 * Do net to host conversion here
6940 * I don't convert host or port since we are most likely
6941 * going to want these in NBO.
6943 peer->ifMTU = ntohs(peer->ifMTU);
6944 peer->idleWhen = ntohl(peer->idleWhen);
6945 peer->refCount = ntohs(peer->refCount);
6946 peer->burstWait.sec = ntohl(peer->burstWait.sec);
6947 peer->burstWait.usec = ntohl(peer->burstWait.usec);
6948 peer->rtt = ntohl(peer->rtt);
6949 peer->rtt_dev = ntohl(peer->rtt_dev);
6950 peer->timeout.sec = ntohl(peer->timeout.sec);
6951 peer->timeout.usec = ntohl(peer->timeout.usec);
6952 peer->nSent = ntohl(peer->nSent);
6953 peer->reSends = ntohl(peer->reSends);
6954 peer->inPacketSkew = ntohl(peer->inPacketSkew);
6955 peer->outPacketSkew = ntohl(peer->outPacketSkew);
6956 peer->rateFlag = ntohl(peer->rateFlag);
6957 peer->natMTU = ntohs(peer->natMTU);
6958 peer->maxMTU = ntohs(peer->maxMTU);
6959 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
6960 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
6961 peer->MTU = ntohs(peer->MTU);
6962 peer->cwind = ntohs(peer->cwind);
6963 peer->nDgramPackets = ntohs(peer->nDgramPackets);
6964 peer->congestSeq = ntohs(peer->congestSeq);
6965 peer->bytesSent.high = ntohl(peer->bytesSent.high);
6966 peer->bytesSent.low = ntohl(peer->bytesSent.low);
6967 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
6968 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
6973 #endif /* RXDEBUG */
6978 struct rx_serverQueueEntry *np;
6981 register struct rx_call *call;
6982 register struct rx_serverQueueEntry *sq;
6986 if (rxinit_status == 1) {
6988 return; /* Already shutdown. */
6992 #ifndef AFS_PTHREAD_ENV
6993 FD_ZERO(&rx_selectMask);
6994 #endif /* AFS_PTHREAD_ENV */
6995 rxi_dataQuota = RX_MAX_QUOTA;
6996 #ifndef AFS_PTHREAD_ENV
6998 #endif /* AFS_PTHREAD_ENV */
7001 #ifndef AFS_PTHREAD_ENV
7002 #ifndef AFS_USE_GETTIMEOFDAY
7004 #endif /* AFS_USE_GETTIMEOFDAY */
7005 #endif /* AFS_PTHREAD_ENV */
7007 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7008 call = queue_First(&rx_freeCallQueue, rx_call);
7010 rxi_Free(call, sizeof(struct rx_call));
7013 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7014 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7020 struct rx_peer **peer_ptr, **peer_end;
7021 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7022 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7024 struct rx_peer *peer, *next;
7025 for (peer = *peer_ptr; peer; peer = next) {
7026 rx_interface_stat_p rpc_stat, nrpc_stat;
7029 (&peer->rpcStats, rpc_stat, nrpc_stat,
7030 rx_interface_stat)) {
7031 unsigned int num_funcs;
7034 queue_Remove(&rpc_stat->queue_header);
7035 queue_Remove(&rpc_stat->all_peers);
7036 num_funcs = rpc_stat->stats[0].func_total;
7038 sizeof(rx_interface_stat_t) +
7039 rpc_stat->stats[0].func_total *
7040 sizeof(rx_function_entry_v1_t);
7042 rxi_Free(rpc_stat, space);
7043 rx_MutexAdd(rxi_rpc_peer_stat_cnt, -num_funcs, 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 register 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 struct rx_connection *tconn =
7138 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7140 MUTEX_ENTER(&tconn->conn_data_lock);
7141 if (!tconn->specific) {
7142 tconn->specific = (void **)malloc((key + 1) * sizeof(void *));
7143 for (i = 0; i < key; i++)
7144 tconn->specific[i] = NULL;
7145 tconn->nSpecific = key + 1;
7146 tconn->specific[key] = ptr;
7147 } else if (key >= tconn->nSpecific) {
7148 tconn->specific = (void **)
7149 realloc(tconn->specific, (key + 1) * sizeof(void *));
7150 for (i = tconn->nSpecific; i < key; i++)
7151 tconn->specific[i] = NULL;
7152 tconn->nSpecific = key + 1;
7153 tconn->specific[key] = ptr;
7155 if (tconn->specific[key] && rxi_keyCreate_destructor[key])
7156 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7157 tconn->specific[key] = ptr;
7159 MUTEX_EXIT(&tconn->conn_data_lock);
7163 rx_GetSpecific(struct rx_connection *conn, int key)
7166 struct rx_connection *tconn =
7167 (rx_IsClonedConn(conn)) ? conn->parent : conn;
7169 MUTEX_ENTER(&tconn->conn_data_lock);
7170 if (key >= tconn->nSpecific)
7173 ptr = tconn->specific[key];
7174 MUTEX_EXIT(&tconn->conn_data_lock);
7178 #endif /* !KERNEL */
7181 * processStats is a queue used to store the statistics for the local
7182 * process. Its contents are similar to the contents of the rpcStats
7183 * queue on a rx_peer structure, but the actual data stored within
7184 * this queue contains totals across the lifetime of the process (assuming
7185 * the stats have not been reset) - unlike the per peer structures
7186 * which can come and go based upon the peer lifetime.
7189 static struct rx_queue processStats = { &processStats, &processStats };
7192 * peerStats is a queue used to store the statistics for all peer structs.
7193 * Its contents are the union of all the peer rpcStats queues.
7196 static struct rx_queue peerStats = { &peerStats, &peerStats };
7199 * rxi_monitor_processStats is used to turn process wide stat collection
7203 static int rxi_monitor_processStats = 0;
7206 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
7209 static int rxi_monitor_peerStats = 0;
7212 * rxi_AddRpcStat - given all of the information for a particular rpc
7213 * call, create (if needed) and update the stat totals for the rpc.
7217 * IN stats - the queue of stats that will be updated with the new value
7219 * IN rxInterface - a unique number that identifies the rpc interface
7221 * IN currentFunc - the index of the function being invoked
7223 * IN totalFunc - the total number of functions in this interface
7225 * IN queueTime - the amount of time this function waited for a thread
7227 * IN execTime - the amount of time this function invocation took to execute
7229 * IN bytesSent - the number bytes sent by this invocation
7231 * IN bytesRcvd - the number bytes received by this invocation
7233 * IN isServer - if true, this invocation was made to a server
7235 * IN remoteHost - the ip address of the remote host
7237 * IN remotePort - the port of the remote host
7239 * IN addToPeerList - if != 0, add newly created stat to the global peer list
7241 * INOUT counter - if a new stats structure is allocated, the counter will
7242 * be updated with the new number of allocated stat structures
7250 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
7251 afs_uint32 currentFunc, afs_uint32 totalFunc,
7252 struct clock *queueTime, struct clock *execTime,
7253 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
7254 afs_uint32 remoteHost, afs_uint32 remotePort,
7255 int addToPeerList, unsigned int *counter)
7258 rx_interface_stat_p rpc_stat, nrpc_stat;
7261 * See if there's already a structure for this interface
7264 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7265 if ((rpc_stat->stats[0].interfaceId == rxInterface)
7266 && (rpc_stat->stats[0].remote_is_server == isServer))
7271 * Didn't find a match so allocate a new structure and add it to the
7275 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
7276 || (rpc_stat->stats[0].interfaceId != rxInterface)
7277 || (rpc_stat->stats[0].remote_is_server != isServer)) {
7282 sizeof(rx_interface_stat_t) +
7283 totalFunc * sizeof(rx_function_entry_v1_t);
7285 rpc_stat = (rx_interface_stat_p) rxi_Alloc(space);
7286 if (rpc_stat == NULL) {
7290 *counter += totalFunc;
7291 for (i = 0; i < totalFunc; i++) {
7292 rpc_stat->stats[i].remote_peer = remoteHost;
7293 rpc_stat->stats[i].remote_port = remotePort;
7294 rpc_stat->stats[i].remote_is_server = isServer;
7295 rpc_stat->stats[i].interfaceId = rxInterface;
7296 rpc_stat->stats[i].func_total = totalFunc;
7297 rpc_stat->stats[i].func_index = i;
7298 hzero(rpc_stat->stats[i].invocations);
7299 hzero(rpc_stat->stats[i].bytes_sent);
7300 hzero(rpc_stat->stats[i].bytes_rcvd);
7301 rpc_stat->stats[i].queue_time_sum.sec = 0;
7302 rpc_stat->stats[i].queue_time_sum.usec = 0;
7303 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7304 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7305 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7306 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7307 rpc_stat->stats[i].queue_time_max.sec = 0;
7308 rpc_stat->stats[i].queue_time_max.usec = 0;
7309 rpc_stat->stats[i].execution_time_sum.sec = 0;
7310 rpc_stat->stats[i].execution_time_sum.usec = 0;
7311 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7312 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7313 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7314 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7315 rpc_stat->stats[i].execution_time_max.sec = 0;
7316 rpc_stat->stats[i].execution_time_max.usec = 0;
7318 queue_Prepend(stats, rpc_stat);
7319 if (addToPeerList) {
7320 queue_Prepend(&peerStats, &rpc_stat->all_peers);
7325 * Increment the stats for this function
7328 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
7329 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
7330 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
7331 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
7332 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
7333 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
7334 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
7336 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
7337 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
7339 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
7340 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
7342 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
7343 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
7345 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
7346 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
7354 * rx_IncrementTimeAndCount - increment the times and count for a particular
7359 * IN peer - the peer who invoked the rpc
7361 * IN rxInterface - a unique number that identifies the rpc interface
7363 * IN currentFunc - the index of the function being invoked
7365 * IN totalFunc - the total number of functions in this interface
7367 * IN queueTime - the amount of time this function waited for a thread
7369 * IN execTime - the amount of time this function invocation took to execute
7371 * IN bytesSent - the number bytes sent by this invocation
7373 * IN bytesRcvd - the number bytes received by this invocation
7375 * IN isServer - if true, this invocation was made to a server
7383 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
7384 afs_uint32 currentFunc, afs_uint32 totalFunc,
7385 struct clock *queueTime, struct clock *execTime,
7386 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
7390 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
7393 MUTEX_ENTER(&rx_rpc_stats);
7394 MUTEX_ENTER(&peer->peer_lock);
7396 if (rxi_monitor_peerStats) {
7397 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
7398 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7399 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
7402 if (rxi_monitor_processStats) {
7403 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
7404 queueTime, execTime, bytesSent, bytesRcvd, isServer,
7405 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
7408 MUTEX_EXIT(&peer->peer_lock);
7409 MUTEX_EXIT(&rx_rpc_stats);
7414 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
7418 * IN callerVersion - the rpc stat version of the caller.
7420 * IN count - the number of entries to marshall.
7422 * IN stats - pointer to stats to be marshalled.
7424 * OUT ptr - Where to store the marshalled data.
7431 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
7432 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
7438 * We only support the first version
7440 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
7441 *(ptr++) = stats->remote_peer;
7442 *(ptr++) = stats->remote_port;
7443 *(ptr++) = stats->remote_is_server;
7444 *(ptr++) = stats->interfaceId;
7445 *(ptr++) = stats->func_total;
7446 *(ptr++) = stats->func_index;
7447 *(ptr++) = hgethi(stats->invocations);
7448 *(ptr++) = hgetlo(stats->invocations);
7449 *(ptr++) = hgethi(stats->bytes_sent);
7450 *(ptr++) = hgetlo(stats->bytes_sent);
7451 *(ptr++) = hgethi(stats->bytes_rcvd);
7452 *(ptr++) = hgetlo(stats->bytes_rcvd);
7453 *(ptr++) = stats->queue_time_sum.sec;
7454 *(ptr++) = stats->queue_time_sum.usec;
7455 *(ptr++) = stats->queue_time_sum_sqr.sec;
7456 *(ptr++) = stats->queue_time_sum_sqr.usec;
7457 *(ptr++) = stats->queue_time_min.sec;
7458 *(ptr++) = stats->queue_time_min.usec;
7459 *(ptr++) = stats->queue_time_max.sec;
7460 *(ptr++) = stats->queue_time_max.usec;
7461 *(ptr++) = stats->execution_time_sum.sec;
7462 *(ptr++) = stats->execution_time_sum.usec;
7463 *(ptr++) = stats->execution_time_sum_sqr.sec;
7464 *(ptr++) = stats->execution_time_sum_sqr.usec;
7465 *(ptr++) = stats->execution_time_min.sec;
7466 *(ptr++) = stats->execution_time_min.usec;
7467 *(ptr++) = stats->execution_time_max.sec;
7468 *(ptr++) = stats->execution_time_max.usec;
7474 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
7479 * IN callerVersion - the rpc stat version of the caller
7481 * OUT myVersion - the rpc stat version of this function
7483 * OUT clock_sec - local time seconds
7485 * OUT clock_usec - local time microseconds
7487 * OUT allocSize - the number of bytes allocated to contain stats
7489 * OUT statCount - the number stats retrieved from this process.
7491 * OUT stats - the actual stats retrieved from this process.
7495 * Returns void. If successful, stats will != NULL.
7499 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7500 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7501 size_t * allocSize, afs_uint32 * statCount,
7502 afs_uint32 ** stats)
7512 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7515 * Check to see if stats are enabled
7518 MUTEX_ENTER(&rx_rpc_stats);
7519 if (!rxi_monitor_processStats) {
7520 MUTEX_EXIT(&rx_rpc_stats);
7524 clock_GetTime(&now);
7525 *clock_sec = now.sec;
7526 *clock_usec = now.usec;
7529 * Allocate the space based upon the caller version
7531 * If the client is at an older version than we are,
7532 * we return the statistic data in the older data format, but
7533 * we still return our version number so the client knows we
7534 * are maintaining more data than it can retrieve.
7537 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7538 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
7539 *statCount = rxi_rpc_process_stat_cnt;
7542 * This can't happen yet, but in the future version changes
7543 * can be handled by adding additional code here
7547 if (space > (size_t) 0) {
7549 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7552 rx_interface_stat_p rpc_stat, nrpc_stat;
7556 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7558 * Copy the data based upon the caller version
7560 rx_MarshallProcessRPCStats(callerVersion,
7561 rpc_stat->stats[0].func_total,
7562 rpc_stat->stats, &ptr);
7568 MUTEX_EXIT(&rx_rpc_stats);
7573 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
7577 * IN callerVersion - the rpc stat version of the caller
7579 * OUT myVersion - the rpc stat version of this function
7581 * OUT clock_sec - local time seconds
7583 * OUT clock_usec - local time microseconds
7585 * OUT allocSize - the number of bytes allocated to contain stats
7587 * OUT statCount - the number of stats retrieved from the individual
7590 * OUT stats - the actual stats retrieved from the individual peer structures.
7594 * Returns void. If successful, stats will != NULL.
7598 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
7599 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
7600 size_t * allocSize, afs_uint32 * statCount,
7601 afs_uint32 ** stats)
7611 *myVersion = RX_STATS_RETRIEVAL_VERSION;
7614 * Check to see if stats are enabled
7617 MUTEX_ENTER(&rx_rpc_stats);
7618 if (!rxi_monitor_peerStats) {
7619 MUTEX_EXIT(&rx_rpc_stats);
7623 clock_GetTime(&now);
7624 *clock_sec = now.sec;
7625 *clock_usec = now.usec;
7628 * Allocate the space based upon the caller version
7630 * If the client is at an older version than we are,
7631 * we return the statistic data in the older data format, but
7632 * we still return our version number so the client knows we
7633 * are maintaining more data than it can retrieve.
7636 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
7637 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
7638 *statCount = rxi_rpc_peer_stat_cnt;
7641 * This can't happen yet, but in the future version changes
7642 * can be handled by adding additional code here
7646 if (space > (size_t) 0) {
7648 ptr = *stats = (afs_uint32 *) rxi_Alloc(space);
7651 rx_interface_stat_p rpc_stat, nrpc_stat;
7655 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7657 * We have to fix the offset of rpc_stat since we are
7658 * keeping this structure on two rx_queues. The rx_queue
7659 * package assumes that the rx_queue member is the first
7660 * member of the structure. That is, rx_queue assumes that
7661 * any one item is only on one queue at a time. We are
7662 * breaking that assumption and so we have to do a little
7663 * math to fix our pointers.
7666 fix_offset = (char *)rpc_stat;
7667 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
7668 rpc_stat = (rx_interface_stat_p) fix_offset;
7671 * Copy the data based upon the caller version
7673 rx_MarshallProcessRPCStats(callerVersion,
7674 rpc_stat->stats[0].func_total,
7675 rpc_stat->stats, &ptr);
7681 MUTEX_EXIT(&rx_rpc_stats);
7686 * rx_FreeRPCStats - free memory allocated by
7687 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
7691 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
7692 * rx_RetrievePeerRPCStats
7694 * IN allocSize - the number of bytes in stats.
7702 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
7704 rxi_Free(stats, allocSize);
7708 * rx_queryProcessRPCStats - see if process rpc stat collection is
7709 * currently enabled.
7715 * Returns 0 if stats are not enabled != 0 otherwise
7719 rx_queryProcessRPCStats(void)
7722 MUTEX_ENTER(&rx_rpc_stats);
7723 rc = rxi_monitor_processStats;
7724 MUTEX_EXIT(&rx_rpc_stats);
7729 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
7735 * Returns 0 if stats are not enabled != 0 otherwise
7739 rx_queryPeerRPCStats(void)
7742 MUTEX_ENTER(&rx_rpc_stats);
7743 rc = rxi_monitor_peerStats;
7744 MUTEX_EXIT(&rx_rpc_stats);
7749 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
7759 rx_enableProcessRPCStats(void)
7761 MUTEX_ENTER(&rx_rpc_stats);
7762 rx_enable_stats = 1;
7763 rxi_monitor_processStats = 1;
7764 MUTEX_EXIT(&rx_rpc_stats);
7768 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
7778 rx_enablePeerRPCStats(void)
7780 MUTEX_ENTER(&rx_rpc_stats);
7781 rx_enable_stats = 1;
7782 rxi_monitor_peerStats = 1;
7783 MUTEX_EXIT(&rx_rpc_stats);
7787 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
7797 rx_disableProcessRPCStats(void)
7799 rx_interface_stat_p rpc_stat, nrpc_stat;
7802 MUTEX_ENTER(&rx_rpc_stats);
7805 * Turn off process statistics and if peer stats is also off, turn
7809 rxi_monitor_processStats = 0;
7810 if (rxi_monitor_peerStats == 0) {
7811 rx_enable_stats = 0;
7814 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7815 unsigned int num_funcs = 0;
7818 queue_Remove(rpc_stat);
7819 num_funcs = rpc_stat->stats[0].func_total;
7821 sizeof(rx_interface_stat_t) +
7822 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
7824 rxi_Free(rpc_stat, space);
7825 rxi_rpc_process_stat_cnt -= num_funcs;
7827 MUTEX_EXIT(&rx_rpc_stats);
7831 * rx_disablePeerRPCStats - stop rpc stat collection for peers
7841 rx_disablePeerRPCStats(void)
7843 struct rx_peer **peer_ptr, **peer_end;
7846 MUTEX_ENTER(&rx_rpc_stats);
7849 * Turn off peer statistics and if process stats is also off, turn
7853 rxi_monitor_peerStats = 0;
7854 if (rxi_monitor_processStats == 0) {
7855 rx_enable_stats = 0;
7858 MUTEX_ENTER(&rx_peerHashTable_lock);
7859 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7860 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7862 struct rx_peer *peer, *next, *prev;
7863 for (prev = peer = *peer_ptr; peer; peer = next) {
7865 code = MUTEX_TRYENTER(&peer->peer_lock);
7867 rx_interface_stat_p rpc_stat, nrpc_stat;
7870 (&peer->rpcStats, rpc_stat, nrpc_stat,
7871 rx_interface_stat)) {
7872 unsigned int num_funcs = 0;
7875 queue_Remove(&rpc_stat->queue_header);
7876 queue_Remove(&rpc_stat->all_peers);
7877 num_funcs = rpc_stat->stats[0].func_total;
7879 sizeof(rx_interface_stat_t) +
7880 rpc_stat->stats[0].func_total *
7881 sizeof(rx_function_entry_v1_t);
7883 rxi_Free(rpc_stat, space);
7884 rxi_rpc_peer_stat_cnt -= num_funcs;
7886 MUTEX_EXIT(&peer->peer_lock);
7887 if (prev == *peer_ptr) {
7897 MUTEX_EXIT(&rx_peerHashTable_lock);
7898 MUTEX_EXIT(&rx_rpc_stats);
7902 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
7907 * IN clearFlag - flag indicating which stats to clear
7915 rx_clearProcessRPCStats(afs_uint32 clearFlag)
7917 rx_interface_stat_p rpc_stat, nrpc_stat;
7919 MUTEX_ENTER(&rx_rpc_stats);
7921 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7922 unsigned int num_funcs = 0, i;
7923 num_funcs = rpc_stat->stats[0].func_total;
7924 for (i = 0; i < num_funcs; i++) {
7925 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
7926 hzero(rpc_stat->stats[i].invocations);
7928 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
7929 hzero(rpc_stat->stats[i].bytes_sent);
7931 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
7932 hzero(rpc_stat->stats[i].bytes_rcvd);
7934 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
7935 rpc_stat->stats[i].queue_time_sum.sec = 0;
7936 rpc_stat->stats[i].queue_time_sum.usec = 0;
7938 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
7939 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
7940 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
7942 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
7943 rpc_stat->stats[i].queue_time_min.sec = 9999999;
7944 rpc_stat->stats[i].queue_time_min.usec = 9999999;
7946 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
7947 rpc_stat->stats[i].queue_time_max.sec = 0;
7948 rpc_stat->stats[i].queue_time_max.usec = 0;
7950 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
7951 rpc_stat->stats[i].execution_time_sum.sec = 0;
7952 rpc_stat->stats[i].execution_time_sum.usec = 0;
7954 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
7955 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
7956 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
7958 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
7959 rpc_stat->stats[i].execution_time_min.sec = 9999999;
7960 rpc_stat->stats[i].execution_time_min.usec = 9999999;
7962 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
7963 rpc_stat->stats[i].execution_time_max.sec = 0;
7964 rpc_stat->stats[i].execution_time_max.usec = 0;
7969 MUTEX_EXIT(&rx_rpc_stats);
7973 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
7978 * IN clearFlag - flag indicating which stats to clear
7986 rx_clearPeerRPCStats(afs_uint32 clearFlag)
7988 rx_interface_stat_p rpc_stat, nrpc_stat;
7990 MUTEX_ENTER(&rx_rpc_stats);
7992 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
7993 unsigned int num_funcs = 0, i;
7996 * We have to fix the offset of rpc_stat since we are
7997 * keeping this structure on two rx_queues. The rx_queue
7998 * package assumes that the rx_queue member is the first
7999 * member of the structure. That is, rx_queue assumes that
8000 * any one item is only on one queue at a time. We are
8001 * breaking that assumption and so we have to do a little
8002 * math to fix our pointers.
8005 fix_offset = (char *)rpc_stat;
8006 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8007 rpc_stat = (rx_interface_stat_p) fix_offset;
8009 num_funcs = rpc_stat->stats[0].func_total;
8010 for (i = 0; i < num_funcs; i++) {
8011 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8012 hzero(rpc_stat->stats[i].invocations);
8014 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8015 hzero(rpc_stat->stats[i].bytes_sent);
8017 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8018 hzero(rpc_stat->stats[i].bytes_rcvd);
8020 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8021 rpc_stat->stats[i].queue_time_sum.sec = 0;
8022 rpc_stat->stats[i].queue_time_sum.usec = 0;
8024 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8025 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8026 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8028 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8029 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8030 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8032 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8033 rpc_stat->stats[i].queue_time_max.sec = 0;
8034 rpc_stat->stats[i].queue_time_max.usec = 0;
8036 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8037 rpc_stat->stats[i].execution_time_sum.sec = 0;
8038 rpc_stat->stats[i].execution_time_sum.usec = 0;
8040 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8041 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8042 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8044 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8045 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8046 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8048 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8049 rpc_stat->stats[i].execution_time_max.sec = 0;
8050 rpc_stat->stats[i].execution_time_max.usec = 0;
8055 MUTEX_EXIT(&rx_rpc_stats);
8059 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8060 * is authorized to enable/disable/clear RX statistics.
8062 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8065 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8067 rxi_rxstat_userok = proc;
8071 rx_RxStatUserOk(struct rx_call *call)
8073 if (!rxi_rxstat_userok)
8075 return rxi_rxstat_userok(call);
8080 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8081 * function in the MSVC runtime DLL (msvcrt.dll).
8083 * Note: the system serializes calls to this function.
8086 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8087 DWORD reason, /* reason function is being called */
8088 LPVOID reserved) /* reserved for future use */
8091 case DLL_PROCESS_ATTACH:
8092 /* library is being attached to a process */
8096 case DLL_PROCESS_DETACH:
8105 int rx_DumpCalls(FILE *outputFile, char *cookie)
8107 #ifdef RXDEBUG_PACKET
8109 #ifdef KDUMP_RX_LOCK
8110 struct rx_call_rx_lock *c;
8116 sprintf(output, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8117 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8119 for (c = rx_allCallsp; c; c = c->allNextp) {
8120 u_short rqc, tqc, iovqc;
8121 struct rx_packet *p, *np;
8123 MUTEX_ENTER(&c->lock);
8124 queue_Count(&c->rq, p, np, rx_packet, rqc);
8125 queue_Count(&c->tq, p, np, rx_packet, tqc);
8126 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
8128 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, "
8129 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
8130 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
8131 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
8132 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
8133 #ifdef RX_ENABLE_LOCKS
8136 #ifdef RX_REFCOUNT_CHECK
8137 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
8138 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
8141 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,
8142 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
8143 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
8144 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
8145 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
8146 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
8147 #ifdef RX_ENABLE_LOCKS
8148 , (afs_uint32)c->refCount
8150 #ifdef RX_REFCOUNT_CHECK
8151 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
8154 MUTEX_EXIT(&c->lock);
8156 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8158 sprintf(output, "%s - End dumping all Rx Calls\r\n", cookie);
8159 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8160 #endif /* RXDEBUG_PACKET */
8163 #endif /* AFS_NT40_ENV */