2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
14 #include "afs/param.h"
16 #include <afs/param.h>
21 #include "afs/sysincludes.h"
22 #include "afsincludes.h"
28 #include <net/net_globals.h>
29 #endif /* AFS_OSF_ENV */
30 #ifdef AFS_LINUX20_ENV
33 #include "netinet/in.h"
35 #include "inet/common.h"
37 #include "inet/ip_ire.h"
39 #include "afs/afs_args.h"
40 #include "afs/afs_osi.h"
41 #ifdef RX_KERNEL_TRACE
42 #include "rx_kcommon.h"
44 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
48 #undef RXDEBUG /* turn off debugging */
50 #if defined(AFS_SGI_ENV)
51 #include "sys/debug.h"
59 #endif /* AFS_OSF_ENV */
61 #include "afs/sysincludes.h"
62 #include "afsincludes.h"
65 #include "rx_kmutex.h"
66 #include "rx_kernel.h"
70 #include "rx_globals.h"
72 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
73 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
74 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
76 extern afs_int32 afs_termState;
78 #include "sys/lockl.h"
79 #include "sys/lock_def.h"
80 #endif /* AFS_AIX41_ENV */
81 # include "afs/rxgen_consts.h"
83 # include <sys/types.h>
93 # include <afs/afsutil.h>
94 # include <WINNT\afsreg.h>
96 # include <sys/socket.h>
97 # include <sys/file.h>
99 # include <sys/stat.h>
100 # include <netinet/in.h>
101 # include <sys/time.h>
104 # include "rx_user.h"
105 # include "rx_clock.h"
106 # include "rx_queue.h"
107 # include "rx_globals.h"
108 # include "rx_trace.h"
109 # include <afs/rxgen_consts.h>
113 #ifdef AFS_PTHREAD_ENV
115 int (*registerProgram) (pid_t, char *) = 0;
116 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
119 int (*registerProgram) (PROCESS, char *) = 0;
120 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
124 /* Local static routines */
125 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
126 #ifdef RX_ENABLE_LOCKS
127 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
130 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
132 afs_int32 rxi_start_aborted; /* rxi_start awoke after rxi_Send in error. */
133 afs_int32 rxi_start_in_error;
135 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
138 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
139 * currently allocated within rx. This number is used to allocate the
140 * memory required to return the statistics when queried.
141 * Protected by the rx_rpc_stats mutex.
144 static unsigned int rxi_rpc_peer_stat_cnt;
147 * rxi_rpc_process_stat_cnt counts the total number of local process stat
148 * structures currently allocated within rx. The number is used to allocate
149 * the memory required to return the statistics when queried.
150 * Protected by the rx_rpc_stats mutex.
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 afs_kmutex_t rx_stats_mutex;
168 extern afs_kmutex_t rx_waiting_mutex;
169 extern afs_kmutex_t rx_quota_mutex;
170 extern afs_kmutex_t rx_pthread_mutex;
171 extern afs_kmutex_t rx_packets_mutex;
172 extern afs_kmutex_t des_init_mutex;
173 extern afs_kmutex_t des_random_mutex;
174 extern afs_kmutex_t rx_clock_mutex;
175 extern afs_kmutex_t rxi_connCacheMutex;
176 extern afs_kmutex_t rx_event_mutex;
177 extern afs_kmutex_t osi_malloc_mutex;
178 extern afs_kmutex_t event_handler_mutex;
179 extern afs_kmutex_t listener_mutex;
180 extern afs_kmutex_t rx_if_init_mutex;
181 extern afs_kmutex_t rx_if_mutex;
182 extern afs_kmutex_t rxkad_client_uid_mutex;
183 extern afs_kmutex_t rxkad_random_mutex;
185 extern afs_kcondvar_t rx_event_handler_cond;
186 extern afs_kcondvar_t rx_listener_cond;
188 static afs_kmutex_t epoch_mutex;
189 static afs_kmutex_t rx_init_mutex;
190 static afs_kmutex_t rx_debug_mutex;
191 static afs_kmutex_t rx_rpc_stats;
194 rxi_InitPthread(void)
196 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_waiting_mutex, "waiting", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
217 assert(pthread_cond_init
218 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
219 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
221 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
222 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
224 rxkad_global_stats_init();
226 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
228 #ifdef RX_ENABLE_LOCKS
231 #endif /* RX_LOCKS_DB */
232 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
233 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
235 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
237 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
239 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
241 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
242 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
243 #endif /* RX_ENABLE_LOCKS */
246 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
247 #define INIT_PTHREAD_LOCKS \
248 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
250 * The rx_stats_mutex mutex protects the following global variables:
251 * rxi_lowConnRefCount
252 * rxi_lowPeerRefCount
261 * The rx_quota_mutex mutex protects the following global variables:
269 * The rx_freePktQ_lock protects the following global variables:
274 * The rx_packets_mutex mutex protects the following global variables:
282 * The rx_pthread_mutex mutex protects the following global variables:
286 #define INIT_PTHREAD_LOCKS
290 /* Variables for handling the minProcs implementation. availProcs gives the
291 * number of threads available in the pool at this moment (not counting dudes
292 * executing right now). totalMin gives the total number of procs required
293 * for handling all minProcs requests. minDeficit is a dynamic variable
294 * tracking the # of procs required to satisfy all of the remaining minProcs
296 * For fine grain locking to work, the quota check and the reservation of
297 * a server thread has to come while rxi_availProcs and rxi_minDeficit
298 * are locked. To this end, the code has been modified under #ifdef
299 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
300 * same time. A new function, ReturnToServerPool() returns the allocation.
302 * A call can be on several queue's (but only one at a time). When
303 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
304 * that no one else is touching the queue. To this end, we store the address
305 * of the queue lock in the call structure (under the call lock) when we
306 * put the call on a queue, and we clear the call_queue_lock when the
307 * call is removed from a queue (once the call lock has been obtained).
308 * This allows rxi_ResetCall to safely synchronize with others wishing
309 * to manipulate the queue.
312 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
313 static afs_kmutex_t rx_rpc_stats;
314 void rxi_StartUnlocked(struct rxevent *event, void *call,
315 void *arg1, int istack);
318 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
319 ** pretty good that the next packet coming in is from the same connection
320 ** as the last packet, since we're send multiple packets in a transmit window.
322 struct rx_connection *rxLastConn = 0;
324 #ifdef RX_ENABLE_LOCKS
325 /* The locking hierarchy for rx fine grain locking is composed of these
328 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
329 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
330 * call->lock - locks call data fields.
331 * These are independent of each other:
332 * rx_freeCallQueue_lock
337 * serverQueueEntry->lock
338 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
340 * peer->lock - locks peer data fields.
341 * conn_data_lock - that more than one thread is not updating a conn data
342 * field at the same time.
350 * Do we need a lock to protect the peer field in the conn structure?
351 * conn->peer was previously a constant for all intents and so has no
352 * lock protecting this field. The multihomed client delta introduced
353 * a RX code change : change the peer field in the connection structure
354 * to that remote interface from which the last packet for this
355 * connection was sent out. This may become an issue if further changes
358 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
359 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
361 /* rxdb_fileID is used to identify the lock location, along with line#. */
362 static int rxdb_fileID = RXDB_FILE_RX;
363 #endif /* RX_LOCKS_DB */
364 #else /* RX_ENABLE_LOCKS */
365 #define SET_CALL_QUEUE_LOCK(C, L)
366 #define CLEAR_CALL_QUEUE_LOCK(C)
367 #endif /* RX_ENABLE_LOCKS */
368 struct rx_serverQueueEntry *rx_waitForPacket = 0;
369 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
371 /* ------------Exported Interfaces------------- */
373 /* This function allows rxkad to set the epoch to a suitably random number
374 * which rx_NewConnection will use in the future. The principle purpose is to
375 * get rxnull connections to use the same epoch as the rxkad connections do, at
376 * least once the first rxkad connection is established. This is important now
377 * that the host/port addresses aren't used in FindConnection: the uniqueness
378 * of epoch/cid matters and the start time won't do. */
380 #ifdef AFS_PTHREAD_ENV
382 * This mutex protects the following global variables:
386 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
387 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
391 #endif /* AFS_PTHREAD_ENV */
394 rx_SetEpoch(afs_uint32 epoch)
401 /* Initialize rx. A port number may be mentioned, in which case this
402 * becomes the default port number for any service installed later.
403 * If 0 is provided for the port number, a random port will be chosen
404 * by the kernel. Whether this will ever overlap anything in
405 * /etc/services is anybody's guess... Returns 0 on success, -1 on
410 int rxinit_status = 1;
411 #ifdef AFS_PTHREAD_ENV
413 * This mutex protects the following global variables:
417 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
418 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
421 #define UNLOCK_RX_INIT
425 rx_InitHost(u_int host, u_int port)
432 char *htable, *ptable;
439 if (rxinit_status == 0) {
440 tmp_status = rxinit_status;
442 return tmp_status; /* Already started; return previous error code. */
448 if (afs_winsockInit() < 0)
454 * Initialize anything necessary to provide a non-premptive threading
457 rxi_InitializeThreadSupport();
460 /* Allocate and initialize a socket for client and perhaps server
463 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
464 if (rx_socket == OSI_NULLSOCKET) {
468 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
471 #endif /* RX_LOCKS_DB */
472 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_waiting_mutex, "rx_waiting_mutex", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
477 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
478 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
479 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
480 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
482 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
484 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
486 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
488 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
489 #if defined(AFS_HPUX110_ENV)
491 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
492 #endif /* AFS_HPUX110_ENV */
493 #endif /* RX_ENABLE_LOCKS && KERNEL */
496 rx_connDeadTime = 12;
497 rx_tranquil = 0; /* reset flag */
498 memset(&rx_stats, 0, sizeof(struct rx_statistics));
500 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
501 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
502 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
503 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
504 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
505 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
507 /* Malloc up a bunch of packets & buffers */
509 queue_Init(&rx_freePacketQueue);
510 rxi_NeedMorePackets = FALSE;
511 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
513 /* enforce a minimum number of allocated packets */
514 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
515 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
517 /* allocate the initial free packet pool */
518 #ifdef RX_ENABLE_TSFPQ
519 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
520 #else /* RX_ENABLE_TSFPQ */
521 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
522 #endif /* RX_ENABLE_TSFPQ */
529 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
530 tv.tv_sec = clock_now.sec;
531 tv.tv_usec = clock_now.usec;
532 srand((unsigned int)tv.tv_usec);
539 #if defined(KERNEL) && !defined(UKERNEL)
540 /* Really, this should never happen in a real kernel */
543 struct sockaddr_in addr;
545 int addrlen = sizeof(addr);
547 socklen_t addrlen = sizeof(addr);
549 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
553 rx_port = addr.sin_port;
556 rx_stats.minRtt.sec = 9999999;
558 rx_SetEpoch(tv.tv_sec | 0x80000000);
560 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
561 * will provide a randomer value. */
563 MUTEX_ENTER(&rx_quota_mutex);
564 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
565 MUTEX_EXIT(&rx_quota_mutex);
566 /* *Slightly* random start time for the cid. This is just to help
567 * out with the hashing function at the peer */
568 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
569 rx_connHashTable = (struct rx_connection **)htable;
570 rx_peerHashTable = (struct rx_peer **)ptable;
572 rx_lastAckDelay.sec = 0;
573 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
574 rx_hardAckDelay.sec = 0;
575 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
576 rx_softAckDelay.sec = 0;
577 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
579 rxevent_Init(20, rxi_ReScheduleEvents);
581 /* Initialize various global queues */
582 queue_Init(&rx_idleServerQueue);
583 queue_Init(&rx_incomingCallQueue);
584 queue_Init(&rx_freeCallQueue);
586 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
587 /* Initialize our list of usable IP addresses. */
591 /* Start listener process (exact function is dependent on the
592 * implementation environment--kernel or user space) */
596 tmp_status = rxinit_status = 0;
604 return rx_InitHost(htonl(INADDR_ANY), port);
607 /* called with unincremented nRequestsRunning to see if it is OK to start
608 * a new thread in this service. Could be "no" for two reasons: over the
609 * max quota, or would prevent others from reaching their min quota.
611 #ifdef RX_ENABLE_LOCKS
612 /* This verion of QuotaOK reserves quota if it's ok while the
613 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
616 QuotaOK(struct rx_service *aservice)
618 /* check if over max quota */
619 if (aservice->nRequestsRunning >= aservice->maxProcs) {
623 /* under min quota, we're OK */
624 /* otherwise, can use only if there are enough to allow everyone
625 * to go to their min quota after this guy starts.
628 MUTEX_ENTER(&rx_quota_mutex);
629 if ((aservice->nRequestsRunning < aservice->minProcs)
630 || (rxi_availProcs > rxi_minDeficit)) {
631 aservice->nRequestsRunning++;
632 /* just started call in minProcs pool, need fewer to maintain
634 if (aservice->nRequestsRunning <= aservice->minProcs)
637 MUTEX_EXIT(&rx_quota_mutex);
640 MUTEX_EXIT(&rx_quota_mutex);
646 ReturnToServerPool(struct rx_service *aservice)
648 aservice->nRequestsRunning--;
649 MUTEX_ENTER(&rx_quota_mutex);
650 if (aservice->nRequestsRunning < aservice->minProcs)
653 MUTEX_EXIT(&rx_quota_mutex);
656 #else /* RX_ENABLE_LOCKS */
658 QuotaOK(struct rx_service *aservice)
661 /* under min quota, we're OK */
662 if (aservice->nRequestsRunning < aservice->minProcs)
665 /* check if over max quota */
666 if (aservice->nRequestsRunning >= aservice->maxProcs)
669 /* otherwise, can use only if there are enough to allow everyone
670 * to go to their min quota after this guy starts.
672 MUTEX_ENTER(&rx_quota_mutex);
673 if (rxi_availProcs > rxi_minDeficit)
675 MUTEX_EXIT(&rx_quota_mutex);
678 #endif /* RX_ENABLE_LOCKS */
681 /* Called by rx_StartServer to start up lwp's to service calls.
682 NExistingProcs gives the number of procs already existing, and which
683 therefore needn't be created. */
685 rxi_StartServerProcs(int nExistingProcs)
687 struct rx_service *service;
692 /* For each service, reserve N processes, where N is the "minimum"
693 * number of processes that MUST be able to execute a request in parallel,
694 * at any time, for that process. Also compute the maximum difference
695 * between any service's maximum number of processes that can run
696 * (i.e. the maximum number that ever will be run, and a guarantee
697 * that this number will run if other services aren't running), and its
698 * minimum number. The result is the extra number of processes that
699 * we need in order to provide the latter guarantee */
700 for (i = 0; i < RX_MAX_SERVICES; i++) {
702 service = rx_services[i];
703 if (service == (struct rx_service *)0)
705 nProcs += service->minProcs;
706 diff = service->maxProcs - service->minProcs;
710 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
711 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
712 for (i = 0; i < nProcs; i++) {
713 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
719 /* This routine is only required on Windows */
721 rx_StartClientThread(void)
723 #ifdef AFS_PTHREAD_ENV
725 pid = pthread_self();
726 #endif /* AFS_PTHREAD_ENV */
728 #endif /* AFS_NT40_ENV */
730 /* This routine must be called if any services are exported. If the
731 * donateMe flag is set, the calling process is donated to the server
734 rx_StartServer(int donateMe)
736 struct rx_service *service;
742 /* Start server processes, if necessary (exact function is dependent
743 * on the implementation environment--kernel or user space). DonateMe
744 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
745 * case, one less new proc will be created rx_StartServerProcs.
747 rxi_StartServerProcs(donateMe);
749 /* count up the # of threads in minProcs, and add set the min deficit to
750 * be that value, too.
752 for (i = 0; i < RX_MAX_SERVICES; i++) {
753 service = rx_services[i];
754 if (service == (struct rx_service *)0)
756 MUTEX_ENTER(&rx_quota_mutex);
757 rxi_totalMin += service->minProcs;
758 /* below works even if a thread is running, since minDeficit would
759 * still have been decremented and later re-incremented.
761 rxi_minDeficit += service->minProcs;
762 MUTEX_EXIT(&rx_quota_mutex);
765 /* Turn on reaping of idle server connections */
766 rxi_ReapConnections(NULL, NULL, NULL);
775 #ifdef AFS_PTHREAD_ENV
777 pid = afs_pointer_to_int(pthread_self());
778 #else /* AFS_PTHREAD_ENV */
780 LWP_CurrentProcess(&pid);
781 #endif /* AFS_PTHREAD_ENV */
783 sprintf(name, "srv_%d", ++nProcs);
785 (*registerProgram) (pid, name);
787 #endif /* AFS_NT40_ENV */
788 rx_ServerProc(NULL); /* Never returns */
790 #ifdef RX_ENABLE_TSFPQ
791 /* no use leaving packets around in this thread's local queue if
792 * it isn't getting donated to the server thread pool.
794 rxi_FlushLocalPacketsTSFPQ();
795 #endif /* RX_ENABLE_TSFPQ */
799 /* Create a new client connection to the specified service, using the
800 * specified security object to implement the security model for this
802 struct rx_connection *
803 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
804 struct rx_securityClass *securityObject,
805 int serviceSecurityIndex)
809 struct rx_connection *conn;
814 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
815 "serviceSecurityIndex %d)\n",
816 ntohl(shost), ntohs(sport), sservice, securityObject,
817 serviceSecurityIndex));
819 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
820 * the case of kmem_alloc? */
821 conn = rxi_AllocConnection();
822 #ifdef RX_ENABLE_LOCKS
823 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
824 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
825 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
828 MUTEX_ENTER(&rx_connHashTable_lock);
829 cid = (rx_nextCid += RX_MAXCALLS);
830 conn->type = RX_CLIENT_CONNECTION;
832 conn->epoch = rx_epoch;
833 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
834 conn->serviceId = sservice;
835 conn->securityObject = securityObject;
836 conn->securityData = (void *) 0;
837 conn->securityIndex = serviceSecurityIndex;
838 rx_SetConnDeadTime(conn, rx_connDeadTime);
839 rx_SetConnSecondsUntilNatPing(conn, 0);
840 conn->ackRate = RX_FAST_ACK_RATE;
842 conn->specific = NULL;
843 conn->challengeEvent = NULL;
844 conn->delayedAbortEvent = NULL;
845 conn->abortCount = 0;
847 for (i = 0; i < RX_MAXCALLS; i++) {
848 conn->twind[i] = rx_initSendWindow;
849 conn->rwind[i] = rx_initReceiveWindow;
852 RXS_NewConnection(securityObject, conn);
854 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
856 conn->refCount++; /* no lock required since only this thread knows... */
857 conn->next = rx_connHashTable[hashindex];
858 rx_connHashTable[hashindex] = conn;
860 rx_MutexIncrement(rx_stats.nClientConns, rx_stats_mutex);
861 MUTEX_EXIT(&rx_connHashTable_lock);
867 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
869 /* The idea is to set the dead time to a value that allows several
870 * keepalives to be dropped without timing out the connection. */
871 conn->secondsUntilDead = MAX(seconds, 6);
872 conn->secondsUntilPing = conn->secondsUntilDead / 6;
875 int rxi_lowPeerRefCount = 0;
876 int rxi_lowConnRefCount = 0;
879 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
880 * NOTE: must not be called with rx_connHashTable_lock held.
883 rxi_CleanupConnection(struct rx_connection *conn)
885 /* Notify the service exporter, if requested, that this connection
886 * is being destroyed */
887 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
888 (*conn->service->destroyConnProc) (conn);
890 /* Notify the security module that this connection is being destroyed */
891 RXS_DestroyConnection(conn->securityObject, conn);
893 /* If this is the last connection using the rx_peer struct, set its
894 * idle time to now. rxi_ReapConnections will reap it if it's still
895 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
897 MUTEX_ENTER(&rx_peerHashTable_lock);
898 if (conn->peer->refCount < 2) {
899 conn->peer->idleWhen = clock_Sec();
900 if (conn->peer->refCount < 1) {
901 conn->peer->refCount = 1;
902 if (rx_stats_active) {
903 MUTEX_ENTER(&rx_stats_mutex);
904 rxi_lowPeerRefCount++;
905 MUTEX_EXIT(&rx_stats_mutex);
909 conn->peer->refCount--;
910 MUTEX_EXIT(&rx_peerHashTable_lock);
914 if (conn->type == RX_SERVER_CONNECTION)
915 rx_MutexDecrement(rx_stats.nServerConns, rx_stats_mutex);
917 rx_MutexDecrement(rx_stats.nClientConns, rx_stats_mutex);
920 if (conn->specific) {
922 for (i = 0; i < conn->nSpecific; i++) {
923 if (conn->specific[i] && rxi_keyCreate_destructor[i])
924 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
925 conn->specific[i] = NULL;
927 free(conn->specific);
929 conn->specific = NULL;
933 MUTEX_DESTROY(&conn->conn_call_lock);
934 MUTEX_DESTROY(&conn->conn_data_lock);
935 CV_DESTROY(&conn->conn_call_cv);
937 rxi_FreeConnection(conn);
940 /* Destroy the specified connection */
942 rxi_DestroyConnection(struct rx_connection *conn)
944 MUTEX_ENTER(&rx_connHashTable_lock);
945 rxi_DestroyConnectionNoLock(conn);
946 /* conn should be at the head of the cleanup list */
947 if (conn == rx_connCleanup_list) {
948 rx_connCleanup_list = rx_connCleanup_list->next;
949 MUTEX_EXIT(&rx_connHashTable_lock);
950 rxi_CleanupConnection(conn);
952 #ifdef RX_ENABLE_LOCKS
954 MUTEX_EXIT(&rx_connHashTable_lock);
956 #endif /* RX_ENABLE_LOCKS */
960 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
962 struct rx_connection **conn_ptr;
964 struct rx_packet *packet;
971 MUTEX_ENTER(&conn->conn_data_lock);
972 if (conn->refCount > 0)
975 if (rx_stats_active) {
976 MUTEX_ENTER(&rx_stats_mutex);
977 rxi_lowConnRefCount++;
978 MUTEX_EXIT(&rx_stats_mutex);
982 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
983 /* Busy; wait till the last guy before proceeding */
984 MUTEX_EXIT(&conn->conn_data_lock);
989 /* If the client previously called rx_NewCall, but it is still
990 * waiting, treat this as a running call, and wait to destroy the
991 * connection later when the call completes. */
992 if ((conn->type == RX_CLIENT_CONNECTION)
993 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
994 conn->flags |= RX_CONN_DESTROY_ME;
995 MUTEX_EXIT(&conn->conn_data_lock);
999 MUTEX_EXIT(&conn->conn_data_lock);
1001 /* Check for extant references to this connection */
1002 for (i = 0; i < RX_MAXCALLS; i++) {
1003 struct rx_call *call = conn->call[i];
1006 if (conn->type == RX_CLIENT_CONNECTION) {
1007 MUTEX_ENTER(&call->lock);
1008 if (call->delayedAckEvent) {
1009 /* Push the final acknowledgment out now--there
1010 * won't be a subsequent call to acknowledge the
1011 * last reply packets */
1012 rxevent_Cancel(call->delayedAckEvent, call,
1013 RX_CALL_REFCOUNT_DELAY);
1014 if (call->state == RX_STATE_PRECALL
1015 || call->state == RX_STATE_ACTIVE) {
1016 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1018 rxi_AckAll(NULL, call, 0);
1021 MUTEX_EXIT(&call->lock);
1025 #ifdef RX_ENABLE_LOCKS
1027 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1028 MUTEX_EXIT(&conn->conn_data_lock);
1030 /* Someone is accessing a packet right now. */
1034 #endif /* RX_ENABLE_LOCKS */
1037 /* Don't destroy the connection if there are any call
1038 * structures still in use */
1039 MUTEX_ENTER(&conn->conn_data_lock);
1040 conn->flags |= RX_CONN_DESTROY_ME;
1041 MUTEX_EXIT(&conn->conn_data_lock);
1046 if (conn->natKeepAliveEvent) {
1047 rxi_NatKeepAliveOff(conn);
1050 if (conn->delayedAbortEvent) {
1051 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1052 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1054 MUTEX_ENTER(&conn->conn_data_lock);
1055 rxi_SendConnectionAbort(conn, packet, 0, 1);
1056 MUTEX_EXIT(&conn->conn_data_lock);
1057 rxi_FreePacket(packet);
1061 /* Remove from connection hash table before proceeding */
1063 &rx_connHashTable[CONN_HASH
1064 (peer->host, peer->port, conn->cid, conn->epoch,
1066 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1067 if (*conn_ptr == conn) {
1068 *conn_ptr = conn->next;
1072 /* if the conn that we are destroying was the last connection, then we
1073 * clear rxLastConn as well */
1074 if (rxLastConn == conn)
1077 /* Make sure the connection is completely reset before deleting it. */
1078 /* get rid of pending events that could zap us later */
1079 if (conn->challengeEvent)
1080 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1081 if (conn->checkReachEvent)
1082 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1083 if (conn->natKeepAliveEvent)
1084 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1086 /* Add the connection to the list of destroyed connections that
1087 * need to be cleaned up. This is necessary to avoid deadlocks
1088 * in the routines we call to inform others that this connection is
1089 * being destroyed. */
1090 conn->next = rx_connCleanup_list;
1091 rx_connCleanup_list = conn;
1094 /* Externally available version */
1096 rx_DestroyConnection(struct rx_connection *conn)
1101 rxi_DestroyConnection(conn);
1106 rx_GetConnection(struct rx_connection *conn)
1111 MUTEX_ENTER(&conn->conn_data_lock);
1113 MUTEX_EXIT(&conn->conn_data_lock);
1117 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1118 /* Wait for the transmit queue to no longer be busy.
1119 * requires the call->lock to be held */
1120 static void rxi_WaitforTQBusy(struct rx_call *call) {
1121 while (call->flags & RX_CALL_TQ_BUSY) {
1122 call->flags |= RX_CALL_TQ_WAIT;
1124 #ifdef RX_ENABLE_LOCKS
1125 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1126 CV_WAIT(&call->cv_tq, &call->lock);
1127 #else /* RX_ENABLE_LOCKS */
1128 osi_rxSleep(&call->tq);
1129 #endif /* RX_ENABLE_LOCKS */
1131 if (call->tqWaiters == 0) {
1132 call->flags &= ~RX_CALL_TQ_WAIT;
1138 /* Start a new rx remote procedure call, on the specified connection.
1139 * If wait is set to 1, wait for a free call channel; otherwise return
1140 * 0. Maxtime gives the maximum number of seconds this call may take,
1141 * after rx_NewCall returns. After this time interval, a call to any
1142 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1143 * For fine grain locking, we hold the conn_call_lock in order to
1144 * to ensure that we don't get signalle after we found a call in an active
1145 * state and before we go to sleep.
1148 rx_NewCall(struct rx_connection *conn)
1151 struct rx_call *call;
1152 struct clock queueTime;
1156 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1159 clock_GetTime(&queueTime);
1161 * Check if there are others waiting for a new call.
1162 * If so, let them go first to avoid starving them.
1163 * This is a fairly simple scheme, and might not be
1164 * a complete solution for large numbers of waiters.
1166 * makeCallWaiters keeps track of the number of
1167 * threads waiting to make calls and the
1168 * RX_CONN_MAKECALL_WAITING flag bit is used to
1169 * indicate that there are indeed calls waiting.
1170 * The flag is set when the waiter is incremented.
1171 * It is only cleared when makeCallWaiters is 0.
1172 * This prevents us from accidently destroying the
1173 * connection while it is potentially about to be used.
1175 MUTEX_ENTER(&conn->conn_call_lock);
1176 MUTEX_ENTER(&conn->conn_data_lock);
1177 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1178 conn->flags |= RX_CONN_MAKECALL_WAITING;
1179 conn->makeCallWaiters++;
1180 MUTEX_EXIT(&conn->conn_data_lock);
1182 #ifdef RX_ENABLE_LOCKS
1183 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1187 MUTEX_ENTER(&conn->conn_data_lock);
1188 conn->makeCallWaiters--;
1189 if (conn->makeCallWaiters == 0)
1190 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1193 /* We are now the active thread in rx_NewCall */
1194 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1195 MUTEX_EXIT(&conn->conn_data_lock);
1200 for (i = 0; i < RX_MAXCALLS; i++) {
1201 call = conn->call[i];
1203 if (call->state == RX_STATE_DALLY) {
1204 MUTEX_ENTER(&call->lock);
1205 if (call->state == RX_STATE_DALLY) {
1207 * We are setting the state to RX_STATE_RESET to
1208 * ensure that no one else will attempt to use this
1209 * call once we drop the conn->conn_call_lock and
1210 * call->lock. We must drop the conn->conn_call_lock
1211 * before calling rxi_ResetCall because the process
1212 * of clearing the transmit queue can block for an
1213 * extended period of time. If we block while holding
1214 * the conn->conn_call_lock, then all rx_EndCall
1215 * processing will block as well. This has a detrimental
1216 * effect on overall system performance.
1218 call->state = RX_STATE_RESET;
1219 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1220 MUTEX_EXIT(&conn->conn_call_lock);
1221 rxi_ResetCall(call, 0);
1222 (*call->callNumber)++;
1223 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1227 * If we failed to be able to safely obtain the
1228 * conn->conn_call_lock we will have to drop the
1229 * call->lock to avoid a deadlock. When the call->lock
1230 * is released the state of the call can change. If it
1231 * is no longer RX_STATE_RESET then some other thread is
1234 MUTEX_EXIT(&call->lock);
1235 MUTEX_ENTER(&conn->conn_call_lock);
1236 MUTEX_ENTER(&call->lock);
1238 if (call->state == RX_STATE_RESET)
1242 * If we get here it means that after dropping
1243 * the conn->conn_call_lock and call->lock that
1244 * the call is no longer ours. If we can't find
1245 * a free call in the remaining slots we should
1246 * not go immediately to RX_CONN_MAKECALL_WAITING
1247 * because by dropping the conn->conn_call_lock
1248 * we have given up synchronization with rx_EndCall.
1249 * Instead, cycle through one more time to see if
1250 * we can find a call that can call our own.
1252 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1255 MUTEX_EXIT(&call->lock);
1258 /* rxi_NewCall returns with mutex locked */
1259 call = rxi_NewCall(conn, i);
1260 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1264 if (i < RX_MAXCALLS) {
1270 MUTEX_ENTER(&conn->conn_data_lock);
1271 conn->flags |= RX_CONN_MAKECALL_WAITING;
1272 conn->makeCallWaiters++;
1273 MUTEX_EXIT(&conn->conn_data_lock);
1275 #ifdef RX_ENABLE_LOCKS
1276 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1280 MUTEX_ENTER(&conn->conn_data_lock);
1281 conn->makeCallWaiters--;
1282 if (conn->makeCallWaiters == 0)
1283 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1284 MUTEX_EXIT(&conn->conn_data_lock);
1286 /* Client is initially in send mode */
1287 call->state = RX_STATE_ACTIVE;
1288 call->error = conn->error;
1290 call->mode = RX_MODE_ERROR;
1292 call->mode = RX_MODE_SENDING;
1294 /* remember start time for call in case we have hard dead time limit */
1295 call->queueTime = queueTime;
1296 clock_GetTime(&call->startTime);
1297 hzero(call->bytesSent);
1298 hzero(call->bytesRcvd);
1300 /* Turn on busy protocol. */
1301 rxi_KeepAliveOn(call);
1303 /* Attempt MTU discovery */
1304 rxi_GrowMTUOn(call);
1307 * We are no longer the active thread in rx_NewCall
1309 MUTEX_ENTER(&conn->conn_data_lock);
1310 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1311 MUTEX_EXIT(&conn->conn_data_lock);
1314 * Wake up anyone else who might be giving us a chance to
1315 * run (see code above that avoids resource starvation).
1317 #ifdef RX_ENABLE_LOCKS
1318 CV_BROADCAST(&conn->conn_call_cv);
1322 MUTEX_EXIT(&conn->conn_call_lock);
1324 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1325 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1326 osi_Panic("rx_NewCall call about to be used without an empty tq");
1328 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1330 MUTEX_EXIT(&call->lock);
1333 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1338 rxi_HasActiveCalls(struct rx_connection *aconn)
1341 struct rx_call *tcall;
1345 for (i = 0; i < RX_MAXCALLS; i++) {
1346 if ((tcall = aconn->call[i])) {
1347 if ((tcall->state == RX_STATE_ACTIVE)
1348 || (tcall->state == RX_STATE_PRECALL)) {
1359 rxi_GetCallNumberVector(struct rx_connection *aconn,
1360 afs_int32 * aint32s)
1363 struct rx_call *tcall;
1367 for (i = 0; i < RX_MAXCALLS; i++) {
1368 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1369 aint32s[i] = aconn->callNumber[i] + 1;
1371 aint32s[i] = aconn->callNumber[i];
1378 rxi_SetCallNumberVector(struct rx_connection *aconn,
1379 afs_int32 * aint32s)
1382 struct rx_call *tcall;
1386 for (i = 0; i < RX_MAXCALLS; i++) {
1387 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1388 aconn->callNumber[i] = aint32s[i] - 1;
1390 aconn->callNumber[i] = aint32s[i];
1396 /* Advertise a new service. A service is named locally by a UDP port
1397 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1400 char *serviceName; Name for identification purposes (e.g. the
1401 service name might be used for probing for
1404 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1405 char *serviceName, struct rx_securityClass **securityObjects,
1406 int nSecurityObjects,
1407 afs_int32(*serviceProc) (struct rx_call * acall))
1409 osi_socket socket = OSI_NULLSOCKET;
1410 struct rx_service *tservice;
1416 if (serviceId == 0) {
1418 "rx_NewService: service id for service %s is not non-zero.\n",
1425 "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",
1433 tservice = rxi_AllocService();
1436 #ifdef RX_ENABLE_LOCKS
1437 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1440 for (i = 0; i < RX_MAX_SERVICES; i++) {
1441 struct rx_service *service = rx_services[i];
1443 if (port == service->servicePort && host == service->serviceHost) {
1444 if (service->serviceId == serviceId) {
1445 /* The identical service has already been
1446 * installed; if the caller was intending to
1447 * change the security classes used by this
1448 * service, he/she loses. */
1450 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1451 serviceName, serviceId, service->serviceName);
1453 rxi_FreeService(tservice);
1456 /* Different service, same port: re-use the socket
1457 * which is bound to the same port */
1458 socket = service->socket;
1461 if (socket == OSI_NULLSOCKET) {
1462 /* If we don't already have a socket (from another
1463 * service on same port) get a new one */
1464 socket = rxi_GetHostUDPSocket(host, port);
1465 if (socket == OSI_NULLSOCKET) {
1467 rxi_FreeService(tservice);
1472 service->socket = socket;
1473 service->serviceHost = host;
1474 service->servicePort = port;
1475 service->serviceId = serviceId;
1476 service->serviceName = serviceName;
1477 service->nSecurityObjects = nSecurityObjects;
1478 service->securityObjects = securityObjects;
1479 service->minProcs = 0;
1480 service->maxProcs = 1;
1481 service->idleDeadTime = 60;
1482 service->idleDeadErr = 0;
1483 service->connDeadTime = rx_connDeadTime;
1484 service->executeRequestProc = serviceProc;
1485 service->checkReach = 0;
1486 service->nSpecific = 0;
1487 service->specific = NULL;
1488 rx_services[i] = service; /* not visible until now */
1494 rxi_FreeService(tservice);
1495 (osi_Msg "rx_NewService: cannot support > %d services\n",
1500 /* Set configuration options for all of a service's security objects */
1503 rx_SetSecurityConfiguration(struct rx_service *service,
1504 rx_securityConfigVariables type,
1508 for (i = 0; i<service->nSecurityObjects; i++) {
1509 if (service->securityObjects[i]) {
1510 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1518 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1519 struct rx_securityClass **securityObjects, int nSecurityObjects,
1520 afs_int32(*serviceProc) (struct rx_call * acall))
1522 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1525 /* Generic request processing loop. This routine should be called
1526 * by the implementation dependent rx_ServerProc. If socketp is
1527 * non-null, it will be set to the file descriptor that this thread
1528 * is now listening on. If socketp is null, this routine will never
1531 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1533 struct rx_call *call;
1535 struct rx_service *tservice = NULL;
1542 call = rx_GetCall(threadID, tservice, socketp);
1543 if (socketp && *socketp != OSI_NULLSOCKET) {
1544 /* We are now a listener thread */
1549 /* if server is restarting( typically smooth shutdown) then do not
1550 * allow any new calls.
1553 if (rx_tranquil && (call != NULL)) {
1557 MUTEX_ENTER(&call->lock);
1559 rxi_CallError(call, RX_RESTARTING);
1560 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1562 MUTEX_EXIT(&call->lock);
1566 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1567 #ifdef RX_ENABLE_LOCKS
1569 #endif /* RX_ENABLE_LOCKS */
1570 afs_termState = AFSOP_STOP_AFS;
1571 afs_osi_Wakeup(&afs_termState);
1572 #ifdef RX_ENABLE_LOCKS
1574 #endif /* RX_ENABLE_LOCKS */
1579 tservice = call->conn->service;
1581 if (tservice->beforeProc)
1582 (*tservice->beforeProc) (call);
1584 code = tservice->executeRequestProc(call);
1586 if (tservice->afterProc)
1587 (*tservice->afterProc) (call, code);
1589 rx_EndCall(call, code);
1590 if (rx_stats_active) {
1591 MUTEX_ENTER(&rx_stats_mutex);
1593 MUTEX_EXIT(&rx_stats_mutex);
1600 rx_WakeupServerProcs(void)
1602 struct rx_serverQueueEntry *np, *tqp;
1606 MUTEX_ENTER(&rx_serverPool_lock);
1608 #ifdef RX_ENABLE_LOCKS
1609 if (rx_waitForPacket)
1610 CV_BROADCAST(&rx_waitForPacket->cv);
1611 #else /* RX_ENABLE_LOCKS */
1612 if (rx_waitForPacket)
1613 osi_rxWakeup(rx_waitForPacket);
1614 #endif /* RX_ENABLE_LOCKS */
1615 MUTEX_ENTER(&freeSQEList_lock);
1616 for (np = rx_FreeSQEList; np; np = tqp) {
1617 tqp = *(struct rx_serverQueueEntry **)np;
1618 #ifdef RX_ENABLE_LOCKS
1619 CV_BROADCAST(&np->cv);
1620 #else /* RX_ENABLE_LOCKS */
1622 #endif /* RX_ENABLE_LOCKS */
1624 MUTEX_EXIT(&freeSQEList_lock);
1625 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1626 #ifdef RX_ENABLE_LOCKS
1627 CV_BROADCAST(&np->cv);
1628 #else /* RX_ENABLE_LOCKS */
1630 #endif /* RX_ENABLE_LOCKS */
1632 MUTEX_EXIT(&rx_serverPool_lock);
1637 * One thing that seems to happen is that all the server threads get
1638 * tied up on some empty or slow call, and then a whole bunch of calls
1639 * arrive at once, using up the packet pool, so now there are more
1640 * empty calls. The most critical resources here are server threads
1641 * and the free packet pool. The "doreclaim" code seems to help in
1642 * general. I think that eventually we arrive in this state: there
1643 * are lots of pending calls which do have all their packets present,
1644 * so they won't be reclaimed, are multi-packet calls, so they won't
1645 * be scheduled until later, and thus are tying up most of the free
1646 * packet pool for a very long time.
1648 * 1. schedule multi-packet calls if all the packets are present.
1649 * Probably CPU-bound operation, useful to return packets to pool.
1650 * Do what if there is a full window, but the last packet isn't here?
1651 * 3. preserve one thread which *only* runs "best" calls, otherwise
1652 * it sleeps and waits for that type of call.
1653 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1654 * the current dataquota business is badly broken. The quota isn't adjusted
1655 * to reflect how many packets are presently queued for a running call.
1656 * So, when we schedule a queued call with a full window of packets queued
1657 * up for it, that *should* free up a window full of packets for other 2d-class
1658 * calls to be able to use from the packet pool. But it doesn't.
1660 * NB. Most of the time, this code doesn't run -- since idle server threads
1661 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1662 * as a new call arrives.
1664 /* Sleep until a call arrives. Returns a pointer to the call, ready
1665 * for an rx_Read. */
1666 #ifdef RX_ENABLE_LOCKS
1668 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1670 struct rx_serverQueueEntry *sq;
1671 struct rx_call *call = (struct rx_call *)0;
1672 struct rx_service *service = NULL;
1675 MUTEX_ENTER(&freeSQEList_lock);
1677 if ((sq = rx_FreeSQEList)) {
1678 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1679 MUTEX_EXIT(&freeSQEList_lock);
1680 } else { /* otherwise allocate a new one and return that */
1681 MUTEX_EXIT(&freeSQEList_lock);
1682 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1683 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1684 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1687 MUTEX_ENTER(&rx_serverPool_lock);
1688 if (cur_service != NULL) {
1689 ReturnToServerPool(cur_service);
1692 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1693 struct rx_call *tcall, *ncall, *choice2 = NULL;
1695 /* Scan for eligible incoming calls. A call is not eligible
1696 * if the maximum number of calls for its service type are
1697 * already executing */
1698 /* One thread will process calls FCFS (to prevent starvation),
1699 * while the other threads may run ahead looking for calls which
1700 * have all their input data available immediately. This helps
1701 * keep threads from blocking, waiting for data from the client. */
1702 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1703 service = tcall->conn->service;
1704 if (!QuotaOK(service)) {
1707 MUTEX_ENTER(&rx_pthread_mutex);
1708 if (tno == rxi_fcfs_thread_num
1709 || !tcall->queue_item_header.next) {
1710 MUTEX_EXIT(&rx_pthread_mutex);
1711 /* If we're the fcfs thread , then we'll just use
1712 * this call. If we haven't been able to find an optimal
1713 * choice, and we're at the end of the list, then use a
1714 * 2d choice if one has been identified. Otherwise... */
1715 call = (choice2 ? choice2 : tcall);
1716 service = call->conn->service;
1718 MUTEX_EXIT(&rx_pthread_mutex);
1719 if (!queue_IsEmpty(&tcall->rq)) {
1720 struct rx_packet *rp;
1721 rp = queue_First(&tcall->rq, rx_packet);
1722 if (rp->header.seq == 1) {
1724 || (rp->header.flags & RX_LAST_PACKET)) {
1726 } else if (rxi_2dchoice && !choice2
1727 && !(tcall->flags & RX_CALL_CLEARED)
1728 && (tcall->rprev > rxi_HardAckRate)) {
1738 ReturnToServerPool(service);
1745 MUTEX_EXIT(&rx_serverPool_lock);
1746 MUTEX_ENTER(&call->lock);
1748 if (call->flags & RX_CALL_WAIT_PROC) {
1749 call->flags &= ~RX_CALL_WAIT_PROC;
1750 MUTEX_ENTER(&rx_waiting_mutex);
1752 MUTEX_EXIT(&rx_waiting_mutex);
1755 if (call->state != RX_STATE_PRECALL || call->error) {
1756 MUTEX_EXIT(&call->lock);
1757 MUTEX_ENTER(&rx_serverPool_lock);
1758 ReturnToServerPool(service);
1763 if (queue_IsEmpty(&call->rq)
1764 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1765 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1767 CLEAR_CALL_QUEUE_LOCK(call);
1770 /* If there are no eligible incoming calls, add this process
1771 * to the idle server queue, to wait for one */
1775 *socketp = OSI_NULLSOCKET;
1777 sq->socketp = socketp;
1778 queue_Append(&rx_idleServerQueue, sq);
1779 #ifndef AFS_AIX41_ENV
1780 rx_waitForPacket = sq;
1782 rx_waitingForPacket = sq;
1783 #endif /* AFS_AIX41_ENV */
1785 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1787 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1788 MUTEX_EXIT(&rx_serverPool_lock);
1789 return (struct rx_call *)0;
1792 } while (!(call = sq->newcall)
1793 && !(socketp && *socketp != OSI_NULLSOCKET));
1794 MUTEX_EXIT(&rx_serverPool_lock);
1796 MUTEX_ENTER(&call->lock);
1802 MUTEX_ENTER(&freeSQEList_lock);
1803 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1804 rx_FreeSQEList = sq;
1805 MUTEX_EXIT(&freeSQEList_lock);
1808 clock_GetTime(&call->startTime);
1809 call->state = RX_STATE_ACTIVE;
1810 call->mode = RX_MODE_RECEIVING;
1811 #ifdef RX_KERNEL_TRACE
1812 if (ICL_SETACTIVE(afs_iclSetp)) {
1813 int glockOwner = ISAFS_GLOCK();
1816 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1817 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1824 rxi_calltrace(RX_CALL_START, call);
1825 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1826 call->conn->service->servicePort, call->conn->service->serviceId,
1829 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1830 MUTEX_EXIT(&call->lock);
1832 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1837 #else /* RX_ENABLE_LOCKS */
1839 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1841 struct rx_serverQueueEntry *sq;
1842 struct rx_call *call = (struct rx_call *)0, *choice2;
1843 struct rx_service *service = NULL;
1847 MUTEX_ENTER(&freeSQEList_lock);
1849 if ((sq = rx_FreeSQEList)) {
1850 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1851 MUTEX_EXIT(&freeSQEList_lock);
1852 } else { /* otherwise allocate a new one and return that */
1853 MUTEX_EXIT(&freeSQEList_lock);
1854 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1855 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1856 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1858 MUTEX_ENTER(&sq->lock);
1860 if (cur_service != NULL) {
1861 cur_service->nRequestsRunning--;
1862 MUTEX_ENTER(&rx_quota_mutex);
1863 if (cur_service->nRequestsRunning < cur_service->minProcs)
1866 MUTEX_EXIT(&rx_quota_mutex);
1868 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1869 struct rx_call *tcall, *ncall;
1870 /* Scan for eligible incoming calls. A call is not eligible
1871 * if the maximum number of calls for its service type are
1872 * already executing */
1873 /* One thread will process calls FCFS (to prevent starvation),
1874 * while the other threads may run ahead looking for calls which
1875 * have all their input data available immediately. This helps
1876 * keep threads from blocking, waiting for data from the client. */
1877 choice2 = (struct rx_call *)0;
1878 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1879 service = tcall->conn->service;
1880 if (QuotaOK(service)) {
1881 MUTEX_ENTER(&rx_pthread_mutex);
1882 if (tno == rxi_fcfs_thread_num
1883 || !tcall->queue_item_header.next) {
1884 MUTEX_EXIT(&rx_pthread_mutex);
1885 /* If we're the fcfs thread, then we'll just use
1886 * this call. If we haven't been able to find an optimal
1887 * choice, and we're at the end of the list, then use a
1888 * 2d choice if one has been identified. Otherwise... */
1889 call = (choice2 ? choice2 : tcall);
1890 service = call->conn->service;
1892 MUTEX_EXIT(&rx_pthread_mutex);
1893 if (!queue_IsEmpty(&tcall->rq)) {
1894 struct rx_packet *rp;
1895 rp = queue_First(&tcall->rq, rx_packet);
1896 if (rp->header.seq == 1
1898 || (rp->header.flags & RX_LAST_PACKET))) {
1900 } else if (rxi_2dchoice && !choice2
1901 && !(tcall->flags & RX_CALL_CLEARED)
1902 && (tcall->rprev > rxi_HardAckRate)) {
1916 /* we can't schedule a call if there's no data!!! */
1917 /* send an ack if there's no data, if we're missing the
1918 * first packet, or we're missing something between first
1919 * and last -- there's a "hole" in the incoming data. */
1920 if (queue_IsEmpty(&call->rq)
1921 || queue_First(&call->rq, rx_packet)->header.seq != 1
1922 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1923 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1925 call->flags &= (~RX_CALL_WAIT_PROC);
1926 service->nRequestsRunning++;
1927 /* just started call in minProcs pool, need fewer to maintain
1929 MUTEX_ENTER(&rx_quota_mutex);
1930 if (service->nRequestsRunning <= service->minProcs)
1933 MUTEX_EXIT(&rx_quota_mutex);
1935 /* MUTEX_EXIT(&call->lock); */
1937 /* If there are no eligible incoming calls, add this process
1938 * to the idle server queue, to wait for one */
1941 *socketp = OSI_NULLSOCKET;
1943 sq->socketp = socketp;
1944 queue_Append(&rx_idleServerQueue, sq);
1948 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1950 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1951 return (struct rx_call *)0;
1954 } while (!(call = sq->newcall)
1955 && !(socketp && *socketp != OSI_NULLSOCKET));
1957 MUTEX_EXIT(&sq->lock);
1959 MUTEX_ENTER(&freeSQEList_lock);
1960 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1961 rx_FreeSQEList = sq;
1962 MUTEX_EXIT(&freeSQEList_lock);
1965 clock_GetTime(&call->startTime);
1966 call->state = RX_STATE_ACTIVE;
1967 call->mode = RX_MODE_RECEIVING;
1968 #ifdef RX_KERNEL_TRACE
1969 if (ICL_SETACTIVE(afs_iclSetp)) {
1970 int glockOwner = ISAFS_GLOCK();
1973 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1974 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1981 rxi_calltrace(RX_CALL_START, call);
1982 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
1983 call->conn->service->servicePort, call->conn->service->serviceId,
1986 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1993 #endif /* RX_ENABLE_LOCKS */
1997 /* Establish a procedure to be called when a packet arrives for a
1998 * call. This routine will be called at most once after each call,
1999 * and will also be called if there is an error condition on the or
2000 * the call is complete. Used by multi rx to build a selection
2001 * function which determines which of several calls is likely to be a
2002 * good one to read from.
2003 * NOTE: the way this is currently implemented it is probably only a
2004 * good idea to (1) use it immediately after a newcall (clients only)
2005 * and (2) only use it once. Other uses currently void your warranty
2008 rx_SetArrivalProc(struct rx_call *call,
2009 void (*proc) (struct rx_call * call,
2012 void * handle, int arg)
2014 call->arrivalProc = proc;
2015 call->arrivalProcHandle = handle;
2016 call->arrivalProcArg = arg;
2019 /* Call is finished (possibly prematurely). Return rc to the peer, if
2020 * appropriate, and return the final error code from the conversation
2024 rx_EndCall(struct rx_call *call, afs_int32 rc)
2026 struct rx_connection *conn = call->conn;
2030 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2031 call, rc, call->error, call->abortCode));
2034 MUTEX_ENTER(&call->lock);
2036 if (rc == 0 && call->error == 0) {
2037 call->abortCode = 0;
2038 call->abortCount = 0;
2041 call->arrivalProc = (void (*)())0;
2042 if (rc && call->error == 0) {
2043 rxi_CallError(call, rc);
2044 /* Send an abort message to the peer if this error code has
2045 * only just been set. If it was set previously, assume the
2046 * peer has already been sent the error code or will request it
2048 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2050 if (conn->type == RX_SERVER_CONNECTION) {
2051 /* Make sure reply or at least dummy reply is sent */
2052 if (call->mode == RX_MODE_RECEIVING) {
2053 rxi_WriteProc(call, 0, 0);
2055 if (call->mode == RX_MODE_SENDING) {
2056 rxi_FlushWrite(call);
2058 rxi_calltrace(RX_CALL_END, call);
2059 /* Call goes to hold state until reply packets are acknowledged */
2060 if (call->tfirst + call->nSoftAcked < call->tnext) {
2061 call->state = RX_STATE_HOLD;
2063 call->state = RX_STATE_DALLY;
2064 rxi_ClearTransmitQueue(call, 0);
2065 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2066 rxevent_Cancel(call->keepAliveEvent, call,
2067 RX_CALL_REFCOUNT_ALIVE);
2069 } else { /* Client connection */
2071 /* Make sure server receives input packets, in the case where
2072 * no reply arguments are expected */
2073 if ((call->mode == RX_MODE_SENDING)
2074 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2075 (void)rxi_ReadProc(call, &dummy, 1);
2078 /* If we had an outstanding delayed ack, be nice to the server
2079 * and force-send it now.
2081 if (call->delayedAckEvent) {
2082 rxevent_Cancel(call->delayedAckEvent, call,
2083 RX_CALL_REFCOUNT_DELAY);
2084 call->delayedAckEvent = NULL;
2085 rxi_SendDelayedAck(NULL, call, NULL);
2088 /* We need to release the call lock since it's lower than the
2089 * conn_call_lock and we don't want to hold the conn_call_lock
2090 * over the rx_ReadProc call. The conn_call_lock needs to be held
2091 * here for the case where rx_NewCall is perusing the calls on
2092 * the connection structure. We don't want to signal until
2093 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2094 * have checked this call, found it active and by the time it
2095 * goes to sleep, will have missed the signal.
2097 MUTEX_EXIT(&call->lock);
2098 MUTEX_ENTER(&conn->conn_call_lock);
2099 MUTEX_ENTER(&call->lock);
2100 MUTEX_ENTER(&conn->conn_data_lock);
2101 conn->flags |= RX_CONN_BUSY;
2102 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2103 MUTEX_EXIT(&conn->conn_data_lock);
2104 #ifdef RX_ENABLE_LOCKS
2105 CV_BROADCAST(&conn->conn_call_cv);
2110 #ifdef RX_ENABLE_LOCKS
2112 MUTEX_EXIT(&conn->conn_data_lock);
2114 #endif /* RX_ENABLE_LOCKS */
2115 call->state = RX_STATE_DALLY;
2117 error = call->error;
2119 /* currentPacket, nLeft, and NFree must be zeroed here, because
2120 * ResetCall cannot: ResetCall may be called at splnet(), in the
2121 * kernel version, and may interrupt the macros rx_Read or
2122 * rx_Write, which run at normal priority for efficiency. */
2123 if (call->currentPacket) {
2124 #ifdef RX_TRACK_PACKETS
2125 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2127 rxi_FreePacket(call->currentPacket);
2128 call->currentPacket = (struct rx_packet *)0;
2131 call->nLeft = call->nFree = call->curlen = 0;
2133 /* Free any packets from the last call to ReadvProc/WritevProc */
2134 #ifdef RXDEBUG_PACKET
2136 #endif /* RXDEBUG_PACKET */
2137 rxi_FreePackets(0, &call->iovq);
2139 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2140 MUTEX_EXIT(&call->lock);
2141 if (conn->type == RX_CLIENT_CONNECTION) {
2142 MUTEX_ENTER(&conn->conn_data_lock);
2143 conn->flags &= ~RX_CONN_BUSY;
2144 MUTEX_EXIT(&conn->conn_data_lock);
2145 MUTEX_EXIT(&conn->conn_call_lock);
2149 * Map errors to the local host's errno.h format.
2151 error = ntoh_syserr_conv(error);
2155 #if !defined(KERNEL)
2157 /* Call this routine when shutting down a server or client (especially
2158 * clients). This will allow Rx to gracefully garbage collect server
2159 * connections, and reduce the number of retries that a server might
2160 * make to a dead client.
2161 * This is not quite right, since some calls may still be ongoing and
2162 * we can't lock them to destroy them. */
2166 struct rx_connection **conn_ptr, **conn_end;
2170 if (rxinit_status == 1) {
2172 return; /* Already shutdown. */
2174 rxi_DeleteCachedConnections();
2175 if (rx_connHashTable) {
2176 MUTEX_ENTER(&rx_connHashTable_lock);
2177 for (conn_ptr = &rx_connHashTable[0], conn_end =
2178 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2180 struct rx_connection *conn, *next;
2181 for (conn = *conn_ptr; conn; conn = next) {
2183 if (conn->type == RX_CLIENT_CONNECTION) {
2184 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2186 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2187 #ifdef RX_ENABLE_LOCKS
2188 rxi_DestroyConnectionNoLock(conn);
2189 #else /* RX_ENABLE_LOCKS */
2190 rxi_DestroyConnection(conn);
2191 #endif /* RX_ENABLE_LOCKS */
2195 #ifdef RX_ENABLE_LOCKS
2196 while (rx_connCleanup_list) {
2197 struct rx_connection *conn;
2198 conn = rx_connCleanup_list;
2199 rx_connCleanup_list = rx_connCleanup_list->next;
2200 MUTEX_EXIT(&rx_connHashTable_lock);
2201 rxi_CleanupConnection(conn);
2202 MUTEX_ENTER(&rx_connHashTable_lock);
2204 MUTEX_EXIT(&rx_connHashTable_lock);
2205 #endif /* RX_ENABLE_LOCKS */
2210 afs_winsockCleanup();
2218 /* if we wakeup packet waiter too often, can get in loop with two
2219 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2221 rxi_PacketsUnWait(void)
2223 if (!rx_waitingForPackets) {
2227 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2228 return; /* still over quota */
2231 rx_waitingForPackets = 0;
2232 #ifdef RX_ENABLE_LOCKS
2233 CV_BROADCAST(&rx_waitingForPackets_cv);
2235 osi_rxWakeup(&rx_waitingForPackets);
2241 /* ------------------Internal interfaces------------------------- */
2243 /* Return this process's service structure for the
2244 * specified socket and service */
2246 rxi_FindService(osi_socket socket, u_short serviceId)
2248 struct rx_service **sp;
2249 for (sp = &rx_services[0]; *sp; sp++) {
2250 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2256 #ifdef RXDEBUG_PACKET
2257 #ifdef KDUMP_RX_LOCK
2258 static struct rx_call_rx_lock *rx_allCallsp = 0;
2260 static struct rx_call *rx_allCallsp = 0;
2262 #endif /* RXDEBUG_PACKET */
2264 /* Allocate a call structure, for the indicated channel of the
2265 * supplied connection. The mode and state of the call must be set by
2266 * the caller. Returns the call with mutex locked. */
2268 rxi_NewCall(struct rx_connection *conn, int channel)
2270 struct rx_call *call;
2271 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2272 struct rx_call *cp; /* Call pointer temp */
2273 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2274 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2276 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2278 /* Grab an existing call structure, or allocate a new one.
2279 * Existing call structures are assumed to have been left reset by
2281 MUTEX_ENTER(&rx_freeCallQueue_lock);
2283 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2285 * EXCEPT that the TQ might not yet be cleared out.
2286 * Skip over those with in-use TQs.
2289 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2290 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2296 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2297 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2298 call = queue_First(&rx_freeCallQueue, rx_call);
2299 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2301 if (rx_stats_active)
2302 rx_MutexDecrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2303 MUTEX_EXIT(&rx_freeCallQueue_lock);
2304 MUTEX_ENTER(&call->lock);
2305 CLEAR_CALL_QUEUE_LOCK(call);
2306 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2307 /* Now, if TQ wasn't cleared earlier, do it now. */
2308 rxi_WaitforTQBusy(call);
2309 if (call->flags & RX_CALL_TQ_CLEARME) {
2310 rxi_ClearTransmitQueue(call, 1);
2311 /*queue_Init(&call->tq);*/
2313 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2314 /* Bind the call to its connection structure */
2316 rxi_ResetCall(call, 1);
2319 call = rxi_Alloc(sizeof(struct rx_call));
2320 #ifdef RXDEBUG_PACKET
2321 call->allNextp = rx_allCallsp;
2322 rx_allCallsp = call;
2324 #endif /* RXDEBUG_PACKET */
2325 rx_MutexIncrement(rx_stats.nCallStructs, rx_stats_mutex);
2327 MUTEX_EXIT(&rx_freeCallQueue_lock);
2328 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2329 MUTEX_ENTER(&call->lock);
2330 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2331 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2332 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2334 /* Initialize once-only items */
2335 queue_Init(&call->tq);
2336 queue_Init(&call->rq);
2337 queue_Init(&call->iovq);
2338 #ifdef RXDEBUG_PACKET
2339 call->rqc = call->tqc = call->iovqc = 0;
2340 #endif /* RXDEBUG_PACKET */
2341 /* Bind the call to its connection structure (prereq for reset) */
2343 rxi_ResetCall(call, 1);
2345 call->channel = channel;
2346 call->callNumber = &conn->callNumber[channel];
2347 call->rwind = conn->rwind[channel];
2348 call->twind = conn->twind[channel];
2349 /* Note that the next expected call number is retained (in
2350 * conn->callNumber[i]), even if we reallocate the call structure
2352 conn->call[channel] = call;
2353 /* if the channel's never been used (== 0), we should start at 1, otherwise
2354 * the call number is valid from the last time this channel was used */
2355 if (*call->callNumber == 0)
2356 *call->callNumber = 1;
2361 /* A call has been inactive long enough that so we can throw away
2362 * state, including the call structure, which is placed on the call
2364 * Call is locked upon entry.
2365 * haveCTLock set if called from rxi_ReapConnections
2367 #ifdef RX_ENABLE_LOCKS
2369 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2370 #else /* RX_ENABLE_LOCKS */
2372 rxi_FreeCall(struct rx_call *call)
2373 #endif /* RX_ENABLE_LOCKS */
2375 int channel = call->channel;
2376 struct rx_connection *conn = call->conn;
2379 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2380 (*call->callNumber)++;
2381 rxi_ResetCall(call, 0);
2382 call->conn->call[channel] = (struct rx_call *)0;
2384 MUTEX_ENTER(&rx_freeCallQueue_lock);
2385 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2386 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2387 /* A call may be free even though its transmit queue is still in use.
2388 * Since we search the call list from head to tail, put busy calls at
2389 * the head of the list, and idle calls at the tail.
2391 if (call->flags & RX_CALL_TQ_BUSY)
2392 queue_Prepend(&rx_freeCallQueue, call);
2394 queue_Append(&rx_freeCallQueue, call);
2395 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2396 queue_Append(&rx_freeCallQueue, call);
2397 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2398 if (rx_stats_active)
2399 rx_MutexIncrement(rx_stats.nFreeCallStructs, rx_stats_mutex);
2400 MUTEX_EXIT(&rx_freeCallQueue_lock);
2402 /* Destroy the connection if it was previously slated for
2403 * destruction, i.e. the Rx client code previously called
2404 * rx_DestroyConnection (client connections), or
2405 * rxi_ReapConnections called the same routine (server
2406 * connections). Only do this, however, if there are no
2407 * outstanding calls. Note that for fine grain locking, there appears
2408 * to be a deadlock in that rxi_FreeCall has a call locked and
2409 * DestroyConnectionNoLock locks each call in the conn. But note a
2410 * few lines up where we have removed this call from the conn.
2411 * If someone else destroys a connection, they either have no
2412 * call lock held or are going through this section of code.
2414 MUTEX_ENTER(&conn->conn_data_lock);
2415 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2417 MUTEX_EXIT(&conn->conn_data_lock);
2418 #ifdef RX_ENABLE_LOCKS
2420 rxi_DestroyConnectionNoLock(conn);
2422 rxi_DestroyConnection(conn);
2423 #else /* RX_ENABLE_LOCKS */
2424 rxi_DestroyConnection(conn);
2425 #endif /* RX_ENABLE_LOCKS */
2427 MUTEX_EXIT(&conn->conn_data_lock);
2431 afs_int32 rxi_Alloccnt = 0, rxi_Allocsize = 0;
2433 rxi_Alloc(size_t size)
2437 if (rx_stats_active)
2438 rx_MutexAdd1Increment2(rxi_Allocsize, (afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2441 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2442 afs_osi_Alloc_NoSleep(size);
2447 osi_Panic("rxi_Alloc error");
2453 rxi_Free(void *addr, size_t size)
2455 if (rx_stats_active)
2456 rx_MutexAdd1Decrement2(rxi_Allocsize, -(afs_int32)size, rxi_Alloccnt, rx_stats_mutex);
2457 osi_Free(addr, size);
2461 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2463 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2464 struct rx_peer *next = NULL;
2468 MUTEX_ENTER(&rx_peerHashTable_lock);
2470 peer_ptr = &rx_peerHashTable[0];
2471 peer_end = &rx_peerHashTable[rx_hashTableSize];
2474 for ( ; peer_ptr < peer_end; peer_ptr++) {
2477 for ( ; peer; peer = next) {
2479 if (host == peer->host)
2484 hashIndex = PEER_HASH(host, port);
2485 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2486 if ((peer->host == host) && (peer->port == port))
2491 MUTEX_ENTER(&rx_peerHashTable_lock);
2496 MUTEX_EXIT(&rx_peerHashTable_lock);
2498 MUTEX_ENTER(&peer->peer_lock);
2499 /* We don't handle dropping below min, so don't */
2500 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2501 peer->ifMTU=MIN(mtu, peer->ifMTU);
2502 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2503 /* if we tweaked this down, need to tune our peer MTU too */
2504 peer->MTU = MIN(peer->MTU, peer->natMTU);
2505 /* if we discovered a sub-1500 mtu, degrade */
2506 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2507 peer->maxDgramPackets = 1;
2508 /* We no longer have valid peer packet information */
2509 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2510 peer->maxPacketSize = 0;
2511 MUTEX_EXIT(&peer->peer_lock);
2513 MUTEX_ENTER(&rx_peerHashTable_lock);
2515 if (host && !port) {
2517 /* pick up where we left off */
2521 MUTEX_EXIT(&rx_peerHashTable_lock);
2524 /* Find the peer process represented by the supplied (host,port)
2525 * combination. If there is no appropriate active peer structure, a
2526 * new one will be allocated and initialized
2527 * The origPeer, if set, is a pointer to a peer structure on which the
2528 * refcount will be be decremented. This is used to replace the peer
2529 * structure hanging off a connection structure */
2531 rxi_FindPeer(afs_uint32 host, u_short port,
2532 struct rx_peer *origPeer, int create)
2536 hashIndex = PEER_HASH(host, port);
2537 MUTEX_ENTER(&rx_peerHashTable_lock);
2538 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2539 if ((pp->host == host) && (pp->port == port))
2544 pp = rxi_AllocPeer(); /* This bzero's *pp */
2545 pp->host = host; /* set here or in InitPeerParams is zero */
2547 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2548 queue_Init(&pp->congestionQueue);
2549 queue_Init(&pp->rpcStats);
2550 pp->next = rx_peerHashTable[hashIndex];
2551 rx_peerHashTable[hashIndex] = pp;
2552 rxi_InitPeerParams(pp);
2553 if (rx_stats_active)
2554 rx_MutexIncrement(rx_stats.nPeerStructs, rx_stats_mutex);
2561 origPeer->refCount--;
2562 MUTEX_EXIT(&rx_peerHashTable_lock);
2567 /* Find the connection at (host, port) started at epoch, and with the
2568 * given connection id. Creates the server connection if necessary.
2569 * The type specifies whether a client connection or a server
2570 * connection is desired. In both cases, (host, port) specify the
2571 * peer's (host, pair) pair. Client connections are not made
2572 * automatically by this routine. The parameter socket gives the
2573 * socket descriptor on which the packet was received. This is used,
2574 * in the case of server connections, to check that *new* connections
2575 * come via a valid (port, serviceId). Finally, the securityIndex
2576 * parameter must match the existing index for the connection. If a
2577 * server connection is created, it will be created using the supplied
2578 * index, if the index is valid for this service */
2579 struct rx_connection *
2580 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2581 u_short port, u_short serviceId, afs_uint32 cid,
2582 afs_uint32 epoch, int type, u_int securityIndex)
2584 int hashindex, flag, i;
2585 struct rx_connection *conn;
2586 hashindex = CONN_HASH(host, port, cid, epoch, type);
2587 MUTEX_ENTER(&rx_connHashTable_lock);
2588 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2589 rx_connHashTable[hashindex],
2592 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2593 && (epoch == conn->epoch)) {
2594 struct rx_peer *pp = conn->peer;
2595 if (securityIndex != conn->securityIndex) {
2596 /* this isn't supposed to happen, but someone could forge a packet
2597 * like this, and there seems to be some CM bug that makes this
2598 * happen from time to time -- in which case, the fileserver
2600 MUTEX_EXIT(&rx_connHashTable_lock);
2601 return (struct rx_connection *)0;
2603 if (pp->host == host && pp->port == port)
2605 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2607 /* So what happens when it's a callback connection? */
2608 if ( /*type == RX_CLIENT_CONNECTION && */
2609 (conn->epoch & 0x80000000))
2613 /* the connection rxLastConn that was used the last time is not the
2614 ** one we are looking for now. Hence, start searching in the hash */
2616 conn = rx_connHashTable[hashindex];
2621 struct rx_service *service;
2622 if (type == RX_CLIENT_CONNECTION) {
2623 MUTEX_EXIT(&rx_connHashTable_lock);
2624 return (struct rx_connection *)0;
2626 service = rxi_FindService(socket, serviceId);
2627 if (!service || (securityIndex >= service->nSecurityObjects)
2628 || (service->securityObjects[securityIndex] == 0)) {
2629 MUTEX_EXIT(&rx_connHashTable_lock);
2630 return (struct rx_connection *)0;
2632 conn = rxi_AllocConnection(); /* This bzero's the connection */
2633 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2634 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2635 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2636 conn->next = rx_connHashTable[hashindex];
2637 rx_connHashTable[hashindex] = conn;
2638 conn->peer = rxi_FindPeer(host, port, 0, 1);
2639 conn->type = RX_SERVER_CONNECTION;
2640 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2641 conn->epoch = epoch;
2642 conn->cid = cid & RX_CIDMASK;
2643 /* conn->serial = conn->lastSerial = 0; */
2644 /* conn->timeout = 0; */
2645 conn->ackRate = RX_FAST_ACK_RATE;
2646 conn->service = service;
2647 conn->serviceId = serviceId;
2648 conn->securityIndex = securityIndex;
2649 conn->securityObject = service->securityObjects[securityIndex];
2650 conn->nSpecific = 0;
2651 conn->specific = NULL;
2652 rx_SetConnDeadTime(conn, service->connDeadTime);
2653 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2654 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2655 for (i = 0; i < RX_MAXCALLS; i++) {
2656 conn->twind[i] = rx_initSendWindow;
2657 conn->rwind[i] = rx_initReceiveWindow;
2659 /* Notify security object of the new connection */
2660 RXS_NewConnection(conn->securityObject, conn);
2661 /* XXXX Connection timeout? */
2662 if (service->newConnProc)
2663 (*service->newConnProc) (conn);
2664 if (rx_stats_active)
2665 rx_MutexIncrement(rx_stats.nServerConns, rx_stats_mutex);
2668 MUTEX_ENTER(&conn->conn_data_lock);
2670 MUTEX_EXIT(&conn->conn_data_lock);
2672 rxLastConn = conn; /* store this connection as the last conn used */
2673 MUTEX_EXIT(&rx_connHashTable_lock);
2677 /* There are two packet tracing routines available for testing and monitoring
2678 * Rx. One is called just after every packet is received and the other is
2679 * called just before every packet is sent. Received packets, have had their
2680 * headers decoded, and packets to be sent have not yet had their headers
2681 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2682 * containing the network address. Both can be modified. The return value, if
2683 * non-zero, indicates that the packet should be dropped. */
2685 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2686 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2688 /* A packet has been received off the interface. Np is the packet, socket is
2689 * the socket number it was received from (useful in determining which service
2690 * this packet corresponds to), and (host, port) reflect the host,port of the
2691 * sender. This call returns the packet to the caller if it is finished with
2692 * it, rather than de-allocating it, just as a small performance hack */
2695 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2696 afs_uint32 host, u_short port, int *tnop,
2697 struct rx_call **newcallp)
2699 struct rx_call *call;
2700 struct rx_connection *conn;
2702 afs_uint32 currentCallNumber;
2708 struct rx_packet *tnp;
2711 /* We don't print out the packet until now because (1) the time may not be
2712 * accurate enough until now in the lwp implementation (rx_Listener only gets
2713 * the time after the packet is read) and (2) from a protocol point of view,
2714 * this is the first time the packet has been seen */
2715 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2716 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2717 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2718 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2719 np->header.epoch, np->header.cid, np->header.callNumber,
2720 np->header.seq, np->header.flags, np));
2723 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2724 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2727 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2728 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2731 /* If an input tracer function is defined, call it with the packet and
2732 * network address. Note this function may modify its arguments. */
2733 if (rx_justReceived) {
2734 struct sockaddr_in addr;
2736 addr.sin_family = AF_INET;
2737 addr.sin_port = port;
2738 addr.sin_addr.s_addr = host;
2739 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2740 addr.sin_len = sizeof(addr);
2741 #endif /* AFS_OSF_ENV */
2742 drop = (*rx_justReceived) (np, &addr);
2743 /* drop packet if return value is non-zero */
2746 port = addr.sin_port; /* in case fcn changed addr */
2747 host = addr.sin_addr.s_addr;
2751 /* If packet was not sent by the client, then *we* must be the client */
2752 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2753 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2755 /* Find the connection (or fabricate one, if we're the server & if
2756 * necessary) associated with this packet */
2758 rxi_FindConnection(socket, host, port, np->header.serviceId,
2759 np->header.cid, np->header.epoch, type,
2760 np->header.securityIndex);
2763 /* If no connection found or fabricated, just ignore the packet.
2764 * (An argument could be made for sending an abort packet for
2769 MUTEX_ENTER(&conn->conn_data_lock);
2770 if (conn->maxSerial < np->header.serial)
2771 conn->maxSerial = np->header.serial;
2772 MUTEX_EXIT(&conn->conn_data_lock);
2774 /* If the connection is in an error state, send an abort packet and ignore
2775 * the incoming packet */
2777 /* Don't respond to an abort packet--we don't want loops! */
2778 MUTEX_ENTER(&conn->conn_data_lock);
2779 if (np->header.type != RX_PACKET_TYPE_ABORT)
2780 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2782 MUTEX_EXIT(&conn->conn_data_lock);
2786 /* Check for connection-only requests (i.e. not call specific). */
2787 if (np->header.callNumber == 0) {
2788 switch (np->header.type) {
2789 case RX_PACKET_TYPE_ABORT: {
2790 /* What if the supplied error is zero? */
2791 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2792 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2793 rxi_ConnectionError(conn, errcode);
2794 MUTEX_ENTER(&conn->conn_data_lock);
2796 MUTEX_EXIT(&conn->conn_data_lock);
2799 case RX_PACKET_TYPE_CHALLENGE:
2800 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2801 MUTEX_ENTER(&conn->conn_data_lock);
2803 MUTEX_EXIT(&conn->conn_data_lock);
2805 case RX_PACKET_TYPE_RESPONSE:
2806 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2807 MUTEX_ENTER(&conn->conn_data_lock);
2809 MUTEX_EXIT(&conn->conn_data_lock);
2811 case RX_PACKET_TYPE_PARAMS:
2812 case RX_PACKET_TYPE_PARAMS + 1:
2813 case RX_PACKET_TYPE_PARAMS + 2:
2814 /* ignore these packet types for now */
2815 MUTEX_ENTER(&conn->conn_data_lock);
2817 MUTEX_EXIT(&conn->conn_data_lock);
2822 /* Should not reach here, unless the peer is broken: send an
2824 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2825 MUTEX_ENTER(&conn->conn_data_lock);
2826 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2828 MUTEX_EXIT(&conn->conn_data_lock);
2833 channel = np->header.cid & RX_CHANNELMASK;
2834 call = conn->call[channel];
2835 #ifdef RX_ENABLE_LOCKS
2837 MUTEX_ENTER(&call->lock);
2838 /* Test to see if call struct is still attached to conn. */
2839 if (call != conn->call[channel]) {
2841 MUTEX_EXIT(&call->lock);
2842 if (type == RX_SERVER_CONNECTION) {
2843 call = conn->call[channel];
2844 /* If we started with no call attached and there is one now,
2845 * another thread is also running this routine and has gotten
2846 * the connection channel. We should drop this packet in the tests
2847 * below. If there was a call on this connection and it's now
2848 * gone, then we'll be making a new call below.
2849 * If there was previously a call and it's now different then
2850 * the old call was freed and another thread running this routine
2851 * has created a call on this channel. One of these two threads
2852 * has a packet for the old call and the code below handles those
2856 MUTEX_ENTER(&call->lock);
2858 /* This packet can't be for this call. If the new call address is
2859 * 0 then no call is running on this channel. If there is a call
2860 * then, since this is a client connection we're getting data for
2861 * it must be for the previous call.
2863 if (rx_stats_active)
2864 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2865 MUTEX_ENTER(&conn->conn_data_lock);
2867 MUTEX_EXIT(&conn->conn_data_lock);
2872 currentCallNumber = conn->callNumber[channel];
2874 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2875 if (np->header.callNumber < currentCallNumber) {
2876 if (rx_stats_active)
2877 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
2878 #ifdef RX_ENABLE_LOCKS
2880 MUTEX_EXIT(&call->lock);
2882 MUTEX_ENTER(&conn->conn_data_lock);
2884 MUTEX_EXIT(&conn->conn_data_lock);
2888 MUTEX_ENTER(&conn->conn_call_lock);
2889 call = rxi_NewCall(conn, channel);
2890 MUTEX_EXIT(&conn->conn_call_lock);
2891 *call->callNumber = np->header.callNumber;
2893 if (np->header.callNumber == 0)
2894 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d",
2895 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2896 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2897 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2899 call->state = RX_STATE_PRECALL;
2900 clock_GetTime(&call->queueTime);
2901 hzero(call->bytesSent);
2902 hzero(call->bytesRcvd);
2904 * If the number of queued calls exceeds the overload
2905 * threshold then abort this call.
2907 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2908 struct rx_packet *tp;
2910 rxi_CallError(call, rx_BusyError);
2911 tp = rxi_SendCallAbort(call, np, 1, 0);
2912 MUTEX_EXIT(&call->lock);
2913 MUTEX_ENTER(&conn->conn_data_lock);
2915 MUTEX_EXIT(&conn->conn_data_lock);
2916 if (rx_stats_active)
2917 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2920 rxi_KeepAliveOn(call);
2921 } else if (np->header.callNumber != currentCallNumber) {
2922 /* Wait until the transmit queue is idle before deciding
2923 * whether to reset the current call. Chances are that the
2924 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2927 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2928 while ((call->state == RX_STATE_ACTIVE)
2929 && (call->flags & RX_CALL_TQ_BUSY)) {
2930 call->flags |= RX_CALL_TQ_WAIT;
2932 #ifdef RX_ENABLE_LOCKS
2933 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2934 CV_WAIT(&call->cv_tq, &call->lock);
2935 #else /* RX_ENABLE_LOCKS */
2936 osi_rxSleep(&call->tq);
2937 #endif /* RX_ENABLE_LOCKS */
2939 if (call->tqWaiters == 0)
2940 call->flags &= ~RX_CALL_TQ_WAIT;
2942 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2943 /* If the new call cannot be taken right now send a busy and set
2944 * the error condition in this call, so that it terminates as
2945 * quickly as possible */
2946 if (call->state == RX_STATE_ACTIVE) {
2947 struct rx_packet *tp;
2949 rxi_CallError(call, RX_CALL_DEAD);
2950 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2952 MUTEX_EXIT(&call->lock);
2953 MUTEX_ENTER(&conn->conn_data_lock);
2955 MUTEX_EXIT(&conn->conn_data_lock);
2958 rxi_ResetCall(call, 0);
2959 *call->callNumber = np->header.callNumber;
2961 if (np->header.callNumber == 0)
2962 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
2963 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2964 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2965 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
2967 call->state = RX_STATE_PRECALL;
2968 clock_GetTime(&call->queueTime);
2969 hzero(call->bytesSent);
2970 hzero(call->bytesRcvd);
2972 * If the number of queued calls exceeds the overload
2973 * threshold then abort this call.
2975 if ((rx_BusyThreshold > 0) && (rx_nWaiting > rx_BusyThreshold)) {
2976 struct rx_packet *tp;
2978 rxi_CallError(call, rx_BusyError);
2979 tp = rxi_SendCallAbort(call, np, 1, 0);
2980 MUTEX_EXIT(&call->lock);
2981 MUTEX_ENTER(&conn->conn_data_lock);
2983 MUTEX_EXIT(&conn->conn_data_lock);
2984 if (rx_stats_active)
2985 rx_MutexIncrement(rx_stats.nBusies, rx_stats_mutex);
2988 rxi_KeepAliveOn(call);
2990 /* Continuing call; do nothing here. */
2992 } else { /* we're the client */
2993 /* Ignore all incoming acknowledgements for calls in DALLY state */
2994 if (call && (call->state == RX_STATE_DALLY)
2995 && (np->header.type == RX_PACKET_TYPE_ACK)) {
2996 if (rx_stats_active)
2997 rx_MutexIncrement(rx_stats.ignorePacketDally, rx_stats_mutex);
2998 #ifdef RX_ENABLE_LOCKS
3000 MUTEX_EXIT(&call->lock);
3003 MUTEX_ENTER(&conn->conn_data_lock);
3005 MUTEX_EXIT(&conn->conn_data_lock);
3009 /* Ignore anything that's not relevant to the current call. If there
3010 * isn't a current call, then no packet is relevant. */
3011 if (!call || (np->header.callNumber != currentCallNumber)) {
3012 if (rx_stats_active)
3013 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
3014 #ifdef RX_ENABLE_LOCKS
3016 MUTEX_EXIT(&call->lock);
3019 MUTEX_ENTER(&conn->conn_data_lock);
3021 MUTEX_EXIT(&conn->conn_data_lock);
3024 /* If the service security object index stamped in the packet does not
3025 * match the connection's security index, ignore the packet */
3026 if (np->header.securityIndex != conn->securityIndex) {
3027 #ifdef RX_ENABLE_LOCKS
3028 MUTEX_EXIT(&call->lock);
3030 MUTEX_ENTER(&conn->conn_data_lock);
3032 MUTEX_EXIT(&conn->conn_data_lock);
3036 /* If we're receiving the response, then all transmit packets are
3037 * implicitly acknowledged. Get rid of them. */
3038 if (np->header.type == RX_PACKET_TYPE_DATA) {
3039 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3040 /* XXX Hack. Because we must release the global rx lock when
3041 * sending packets (osi_NetSend) we drop all acks while we're
3042 * traversing the tq in rxi_Start sending packets out because
3043 * packets may move to the freePacketQueue as result of being here!
3044 * So we drop these packets until we're safely out of the
3045 * traversing. Really ugly!
3046 * For fine grain RX locking, we set the acked field in the
3047 * packets and let rxi_Start remove them from the transmit queue.
3049 if (call->flags & RX_CALL_TQ_BUSY) {
3050 #ifdef RX_ENABLE_LOCKS
3051 rxi_SetAcksInTransmitQueue(call);
3054 return np; /* xmitting; drop packet */
3057 rxi_ClearTransmitQueue(call, 0);
3059 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3060 rxi_ClearTransmitQueue(call, 0);
3061 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3063 if (np->header.type == RX_PACKET_TYPE_ACK) {
3064 /* now check to see if this is an ack packet acknowledging that the
3065 * server actually *lost* some hard-acked data. If this happens we
3066 * ignore this packet, as it may indicate that the server restarted in
3067 * the middle of a call. It is also possible that this is an old ack
3068 * packet. We don't abort the connection in this case, because this
3069 * *might* just be an old ack packet. The right way to detect a server
3070 * restart in the midst of a call is to notice that the server epoch
3072 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3073 * XXX unacknowledged. I think that this is off-by-one, but
3074 * XXX I don't dare change it just yet, since it will
3075 * XXX interact badly with the server-restart detection
3076 * XXX code in receiveackpacket. */
3077 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3078 if (rx_stats_active)
3079 rx_MutexIncrement(rx_stats.spuriousPacketsRead, rx_stats_mutex);
3080 MUTEX_EXIT(&call->lock);
3081 MUTEX_ENTER(&conn->conn_data_lock);
3083 MUTEX_EXIT(&conn->conn_data_lock);
3087 } /* else not a data packet */
3090 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3091 /* Set remote user defined status from packet */
3092 call->remoteStatus = np->header.userStatus;
3094 /* Note the gap between the expected next packet and the actual
3095 * packet that arrived, when the new packet has a smaller serial number
3096 * than expected. Rioses frequently reorder packets all by themselves,
3097 * so this will be quite important with very large window sizes.
3098 * Skew is checked against 0 here to avoid any dependence on the type of
3099 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3101 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3102 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3103 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3105 MUTEX_ENTER(&conn->conn_data_lock);
3106 skew = conn->lastSerial - np->header.serial;
3107 conn->lastSerial = np->header.serial;
3108 MUTEX_EXIT(&conn->conn_data_lock);
3110 struct rx_peer *peer;
3112 if (skew > peer->inPacketSkew) {
3113 dpf(("*** In skew changed from %d to %d\n",
3114 peer->inPacketSkew, skew));
3115 peer->inPacketSkew = skew;
3119 /* Now do packet type-specific processing */
3120 switch (np->header.type) {
3121 case RX_PACKET_TYPE_DATA:
3122 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3125 case RX_PACKET_TYPE_ACK:
3126 /* Respond immediately to ack packets requesting acknowledgement
3128 if (np->header.flags & RX_REQUEST_ACK) {
3130 (void)rxi_SendCallAbort(call, 0, 1, 0);
3132 (void)rxi_SendAck(call, 0, np->header.serial,
3133 RX_ACK_PING_RESPONSE, 1);
3135 np = rxi_ReceiveAckPacket(call, np, 1);
3137 case RX_PACKET_TYPE_ABORT: {
3138 /* An abort packet: reset the call, passing the error up to the user. */
3139 /* What if error is zero? */
3140 /* What if the error is -1? the application will treat it as a timeout. */
3141 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3142 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3143 rxi_CallError(call, errdata);
3144 MUTEX_EXIT(&call->lock);
3145 MUTEX_ENTER(&conn->conn_data_lock);
3147 MUTEX_EXIT(&conn->conn_data_lock);
3148 return np; /* xmitting; drop packet */
3150 case RX_PACKET_TYPE_BUSY:
3153 case RX_PACKET_TYPE_ACKALL:
3154 /* All packets acknowledged, so we can drop all packets previously
3155 * readied for sending */
3156 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3157 /* XXX Hack. We because we can't release the global rx lock when
3158 * sending packets (osi_NetSend) we drop all ack pkts while we're
3159 * traversing the tq in rxi_Start sending packets out because
3160 * packets may move to the freePacketQueue as result of being
3161 * here! So we drop these packets until we're safely out of the
3162 * traversing. Really ugly!
3163 * For fine grain RX locking, we set the acked field in the packets
3164 * and let rxi_Start remove the packets from the transmit queue.
3166 if (call->flags & RX_CALL_TQ_BUSY) {
3167 #ifdef RX_ENABLE_LOCKS
3168 rxi_SetAcksInTransmitQueue(call);
3170 #else /* RX_ENABLE_LOCKS */
3171 MUTEX_EXIT(&call->lock);
3172 MUTEX_ENTER(&conn->conn_data_lock);
3174 MUTEX_EXIT(&conn->conn_data_lock);
3175 return np; /* xmitting; drop packet */
3176 #endif /* RX_ENABLE_LOCKS */
3178 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3179 rxi_ClearTransmitQueue(call, 0);
3180 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3183 /* Should not reach here, unless the peer is broken: send an abort
3185 rxi_CallError(call, RX_PROTOCOL_ERROR);
3186 np = rxi_SendCallAbort(call, np, 1, 0);
3189 /* Note when this last legitimate packet was received, for keep-alive
3190 * processing. Note, we delay getting the time until now in the hope that
3191 * the packet will be delivered to the user before any get time is required
3192 * (if not, then the time won't actually be re-evaluated here). */
3193 call->lastReceiveTime = clock_Sec();
3194 MUTEX_EXIT(&call->lock);
3195 MUTEX_ENTER(&conn->conn_data_lock);
3197 MUTEX_EXIT(&conn->conn_data_lock);
3201 /* return true if this is an "interesting" connection from the point of view
3202 of someone trying to debug the system */
3204 rxi_IsConnInteresting(struct rx_connection *aconn)
3207 struct rx_call *tcall;
3209 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3212 for (i = 0; i < RX_MAXCALLS; i++) {
3213 tcall = aconn->call[i];
3215 if ((tcall->state == RX_STATE_PRECALL)
3216 || (tcall->state == RX_STATE_ACTIVE))
3218 if ((tcall->mode == RX_MODE_SENDING)
3219 || (tcall->mode == RX_MODE_RECEIVING))
3227 /* if this is one of the last few packets AND it wouldn't be used by the
3228 receiving call to immediately satisfy a read request, then drop it on
3229 the floor, since accepting it might prevent a lock-holding thread from
3230 making progress in its reading. If a call has been cleared while in
3231 the precall state then ignore all subsequent packets until the call
3232 is assigned to a thread. */
3235 TooLow(struct rx_packet *ap, struct rx_call *acall)
3239 MUTEX_ENTER(&rx_quota_mutex);
3240 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3241 && (acall->state == RX_STATE_PRECALL))
3242 || ((rx_nFreePackets < rxi_dataQuota + 2)
3243 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3244 && (acall->flags & RX_CALL_READER_WAIT)))) {
3247 MUTEX_EXIT(&rx_quota_mutex);
3253 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3255 struct rx_connection *conn = arg1;
3256 struct rx_call *acall = arg2;
3257 struct rx_call *call = acall;
3258 struct clock when, now;
3261 MUTEX_ENTER(&conn->conn_data_lock);
3262 conn->checkReachEvent = NULL;
3263 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3266 MUTEX_EXIT(&conn->conn_data_lock);
3270 MUTEX_ENTER(&conn->conn_call_lock);
3271 MUTEX_ENTER(&conn->conn_data_lock);
3272 for (i = 0; i < RX_MAXCALLS; i++) {
3273 struct rx_call *tc = conn->call[i];
3274 if (tc && tc->state == RX_STATE_PRECALL) {
3280 /* Indicate that rxi_CheckReachEvent is no longer running by
3281 * clearing the flag. Must be atomic under conn_data_lock to
3282 * avoid a new call slipping by: rxi_CheckConnReach holds
3283 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3285 conn->flags &= ~RX_CONN_ATTACHWAIT;
3286 MUTEX_EXIT(&conn->conn_data_lock);
3287 MUTEX_EXIT(&conn->conn_call_lock);
3292 MUTEX_ENTER(&call->lock);
3293 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3295 MUTEX_EXIT(&call->lock);
3297 clock_GetTime(&now);
3299 when.sec += RX_CHECKREACH_TIMEOUT;
3300 MUTEX_ENTER(&conn->conn_data_lock);
3301 if (!conn->checkReachEvent) {
3303 conn->checkReachEvent =
3304 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3307 MUTEX_EXIT(&conn->conn_data_lock);
3313 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3315 struct rx_service *service = conn->service;
3316 struct rx_peer *peer = conn->peer;
3317 afs_uint32 now, lastReach;
3319 if (service->checkReach == 0)
3323 MUTEX_ENTER(&peer->peer_lock);
3324 lastReach = peer->lastReachTime;
3325 MUTEX_EXIT(&peer->peer_lock);
3326 if (now - lastReach < RX_CHECKREACH_TTL)
3329 MUTEX_ENTER(&conn->conn_data_lock);
3330 if (conn->flags & RX_CONN_ATTACHWAIT) {
3331 MUTEX_EXIT(&conn->conn_data_lock);
3334 conn->flags |= RX_CONN_ATTACHWAIT;
3335 MUTEX_EXIT(&conn->conn_data_lock);
3336 if (!conn->checkReachEvent)
3337 rxi_CheckReachEvent(NULL, conn, call);
3342 /* try to attach call, if authentication is complete */
3344 TryAttach(struct rx_call *acall, osi_socket socket,
3345 int *tnop, struct rx_call **newcallp,
3348 struct rx_connection *conn = acall->conn;
3350 if (conn->type == RX_SERVER_CONNECTION
3351 && acall->state == RX_STATE_PRECALL) {
3352 /* Don't attach until we have any req'd. authentication. */
3353 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3354 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3355 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3356 /* Note: this does not necessarily succeed; there
3357 * may not any proc available
3360 rxi_ChallengeOn(acall->conn);
3365 /* A data packet has been received off the interface. This packet is
3366 * appropriate to the call (the call is in the right state, etc.). This
3367 * routine can return a packet to the caller, for re-use */
3370 rxi_ReceiveDataPacket(struct rx_call *call,
3371 struct rx_packet *np, int istack,
3372 osi_socket socket, afs_uint32 host, u_short port,
3373 int *tnop, struct rx_call **newcallp)
3375 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3380 afs_uint32 serial=0, flags=0;
3382 struct rx_packet *tnp;
3383 struct clock when, now;
3384 if (rx_stats_active)
3385 rx_MutexIncrement(rx_stats.dataPacketsRead, rx_stats_mutex);
3388 /* If there are no packet buffers, drop this new packet, unless we can find
3389 * packet buffers from inactive calls */
3391 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3392 MUTEX_ENTER(&rx_freePktQ_lock);
3393 rxi_NeedMorePackets = TRUE;
3394 MUTEX_EXIT(&rx_freePktQ_lock);
3395 if (rx_stats_active)
3396 rx_MutexIncrement(rx_stats.noPacketBuffersOnRead, rx_stats_mutex);
3397 call->rprev = np->header.serial;
3398 rxi_calltrace(RX_TRACE_DROP, call);
3399 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3401 rxi_ClearReceiveQueue(call);
3402 clock_GetTime(&now);
3404 clock_Add(&when, &rx_softAckDelay);
3405 if (!call->delayedAckEvent
3406 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3407 rxevent_Cancel(call->delayedAckEvent, call,
3408 RX_CALL_REFCOUNT_DELAY);
3409 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3410 call->delayedAckEvent =
3411 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3413 /* we've damaged this call already, might as well do it in. */
3419 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3420 * packet is one of several packets transmitted as a single
3421 * datagram. Do not send any soft or hard acks until all packets
3422 * in a jumbogram have been processed. Send negative acks right away.
3424 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3425 /* tnp is non-null when there are more packets in the
3426 * current jumbo gram */
3433 seq = np->header.seq;
3434 serial = np->header.serial;
3435 flags = np->header.flags;
3437 /* If the call is in an error state, send an abort message */
3439 return rxi_SendCallAbort(call, np, istack, 0);
3441 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3442 * AFS 3.5 jumbogram. */
3443 if (flags & RX_JUMBO_PACKET) {
3444 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3449 if (np->header.spare != 0) {
3450 MUTEX_ENTER(&call->conn->conn_data_lock);
3451 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3452 MUTEX_EXIT(&call->conn->conn_data_lock);
3455 /* The usual case is that this is the expected next packet */
3456 if (seq == call->rnext) {
3458 /* Check to make sure it is not a duplicate of one already queued */
3459 if (queue_IsNotEmpty(&call->rq)
3460 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3461 if (rx_stats_active)
3462 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3463 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3464 rxevent_Cancel(call->delayedAckEvent, call,
3465 RX_CALL_REFCOUNT_DELAY);
3466 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3472 /* It's the next packet. Stick it on the receive queue
3473 * for this call. Set newPackets to make sure we wake
3474 * the reader once all packets have been processed */
3475 #ifdef RX_TRACK_PACKETS
3476 np->flags |= RX_PKTFLAG_RQ;
3478 queue_Prepend(&call->rq, np);
3479 #ifdef RXDEBUG_PACKET
3481 #endif /* RXDEBUG_PACKET */
3483 np = NULL; /* We can't use this anymore */
3486 /* If an ack is requested then set a flag to make sure we
3487 * send an acknowledgement for this packet */
3488 if (flags & RX_REQUEST_ACK) {
3489 ackNeeded = RX_ACK_REQUESTED;
3492 /* Keep track of whether we have received the last packet */
3493 if (flags & RX_LAST_PACKET) {
3494 call->flags |= RX_CALL_HAVE_LAST;
3498 /* Check whether we have all of the packets for this call */
3499 if (call->flags & RX_CALL_HAVE_LAST) {
3500 afs_uint32 tseq; /* temporary sequence number */
3501 struct rx_packet *tp; /* Temporary packet pointer */
3502 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3504 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3505 if (tseq != tp->header.seq)
3507 if (tp->header.flags & RX_LAST_PACKET) {
3508 call->flags |= RX_CALL_RECEIVE_DONE;
3515 /* Provide asynchronous notification for those who want it
3516 * (e.g. multi rx) */
3517 if (call->arrivalProc) {
3518 (*call->arrivalProc) (call, call->arrivalProcHandle,
3519 call->arrivalProcArg);
3520 call->arrivalProc = (void (*)())0;
3523 /* Update last packet received */
3526 /* If there is no server process serving this call, grab
3527 * one, if available. We only need to do this once. If a
3528 * server thread is available, this thread becomes a server
3529 * thread and the server thread becomes a listener thread. */
3531 TryAttach(call, socket, tnop, newcallp, 0);
3534 /* This is not the expected next packet. */
3536 /* Determine whether this is a new or old packet, and if it's
3537 * a new one, whether it fits into the current receive window.
3538 * Also figure out whether the packet was delivered in sequence.
3539 * We use the prev variable to determine whether the new packet
3540 * is the successor of its immediate predecessor in the
3541 * receive queue, and the missing flag to determine whether
3542 * any of this packets predecessors are missing. */
3544 afs_uint32 prev; /* "Previous packet" sequence number */
3545 struct rx_packet *tp; /* Temporary packet pointer */
3546 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3547 int missing; /* Are any predecessors missing? */
3549 /* If the new packet's sequence number has been sent to the
3550 * application already, then this is a duplicate */
3551 if (seq < call->rnext) {
3552 if (rx_stats_active)
3553 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3554 rxevent_Cancel(call->delayedAckEvent, call,
3555 RX_CALL_REFCOUNT_DELAY);
3556 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3562 /* If the sequence number is greater than what can be
3563 * accomodated by the current window, then send a negative
3564 * acknowledge and drop the packet */
3565 if ((call->rnext + call->rwind) <= seq) {
3566 rxevent_Cancel(call->delayedAckEvent, call,
3567 RX_CALL_REFCOUNT_DELAY);
3568 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3575 /* Look for the packet in the queue of old received packets */
3576 for (prev = call->rnext - 1, missing =
3577 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3578 /*Check for duplicate packet */
3579 if (seq == tp->header.seq) {
3580 if (rx_stats_active)
3581 rx_MutexIncrement(rx_stats.dupPacketsRead, rx_stats_mutex);
3582 rxevent_Cancel(call->delayedAckEvent, call,
3583 RX_CALL_REFCOUNT_DELAY);
3584 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3590 /* If we find a higher sequence packet, break out and
3591 * insert the new packet here. */
3592 if (seq < tp->header.seq)
3594 /* Check for missing packet */
3595 if (tp->header.seq != prev + 1) {
3599 prev = tp->header.seq;
3602 /* Keep track of whether we have received the last packet. */
3603 if (flags & RX_LAST_PACKET) {
3604 call->flags |= RX_CALL_HAVE_LAST;
3607 /* It's within the window: add it to the the receive queue.
3608 * tp is left by the previous loop either pointing at the
3609 * packet before which to insert the new packet, or at the
3610 * queue head if the queue is empty or the packet should be
3612 #ifdef RX_TRACK_PACKETS
3613 np->flags |= RX_PKTFLAG_RQ;
3615 #ifdef RXDEBUG_PACKET
3617 #endif /* RXDEBUG_PACKET */
3618 queue_InsertBefore(tp, np);
3622 /* Check whether we have all of the packets for this call */
3623 if ((call->flags & RX_CALL_HAVE_LAST)
3624 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3625 afs_uint32 tseq; /* temporary sequence number */
3628 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3629 if (tseq != tp->header.seq)
3631 if (tp->header.flags & RX_LAST_PACKET) {
3632 call->flags |= RX_CALL_RECEIVE_DONE;
3639 /* We need to send an ack of the packet is out of sequence,
3640 * or if an ack was requested by the peer. */
3641 if (seq != prev + 1 || missing) {
3642 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3643 } else if (flags & RX_REQUEST_ACK) {
3644 ackNeeded = RX_ACK_REQUESTED;
3647 /* Acknowledge the last packet for each call */
3648 if (flags & RX_LAST_PACKET) {
3659 * If the receiver is waiting for an iovec, fill the iovec
3660 * using the data from the receive queue */
3661 if (call->flags & RX_CALL_IOVEC_WAIT) {
3662 didHardAck = rxi_FillReadVec(call, serial);
3663 /* the call may have been aborted */
3672 /* Wakeup the reader if any */
3673 if ((call->flags & RX_CALL_READER_WAIT)
3674 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3675 || (call->iovNext >= call->iovMax)
3676 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3677 call->flags &= ~RX_CALL_READER_WAIT;
3678 #ifdef RX_ENABLE_LOCKS
3679 CV_BROADCAST(&call->cv_rq);
3681 osi_rxWakeup(&call->rq);
3687 * Send an ack when requested by the peer, or once every
3688 * rxi_SoftAckRate packets until the last packet has been
3689 * received. Always send a soft ack for the last packet in
3690 * the server's reply. */
3692 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3693 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3694 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3695 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3696 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3697 } else if (call->nSoftAcks) {
3698 clock_GetTime(&now);
3700 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3701 clock_Add(&when, &rx_lastAckDelay);
3703 clock_Add(&when, &rx_softAckDelay);
3705 if (!call->delayedAckEvent
3706 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3707 rxevent_Cancel(call->delayedAckEvent, call,
3708 RX_CALL_REFCOUNT_DELAY);
3709 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3710 call->delayedAckEvent =
3711 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3713 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3714 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3721 static void rxi_ComputeRate();
3725 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3727 struct rx_peer *peer = conn->peer;
3729 MUTEX_ENTER(&peer->peer_lock);
3730 peer->lastReachTime = clock_Sec();
3731 MUTEX_EXIT(&peer->peer_lock);
3733 MUTEX_ENTER(&conn->conn_data_lock);
3734 if (conn->flags & RX_CONN_ATTACHWAIT) {
3737 conn->flags &= ~RX_CONN_ATTACHWAIT;
3738 MUTEX_EXIT(&conn->conn_data_lock);
3740 for (i = 0; i < RX_MAXCALLS; i++) {
3741 struct rx_call *call = conn->call[i];
3744 MUTEX_ENTER(&call->lock);
3745 /* tnop can be null if newcallp is null */
3746 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3748 MUTEX_EXIT(&call->lock);
3752 MUTEX_EXIT(&conn->conn_data_lock);
3755 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3757 rx_ack_reason(int reason)
3760 case RX_ACK_REQUESTED:
3762 case RX_ACK_DUPLICATE:
3764 case RX_ACK_OUT_OF_SEQUENCE:
3766 case RX_ACK_EXCEEDS_WINDOW:
3768 case RX_ACK_NOSPACE:
3772 case RX_ACK_PING_RESPONSE:
3785 /* rxi_ComputePeerNetStats
3787 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3788 * estimates (like RTT and throughput) based on ack packets. Caller
3789 * must ensure that the packet in question is the right one (i.e.
3790 * serial number matches).
3793 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3794 struct rx_ackPacket *ap, struct rx_packet *np)
3796 struct rx_peer *peer = call->conn->peer;
3798 /* Use RTT if not delayed by client and
3799 * ignore packets that were retransmitted. */
3800 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3801 ap->reason != RX_ACK_DELAY &&
3802 clock_Eq(&p->timeSent, &p->firstSent))
3803 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3805 rxi_ComputeRate(peer, call, p, np, ap->reason);
3809 /* The real smarts of the whole thing. */
3811 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3814 struct rx_ackPacket *ap;
3816 struct rx_packet *tp;
3817 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3818 struct rx_connection *conn = call->conn;
3819 struct rx_peer *peer = conn->peer;
3822 /* because there are CM's that are bogus, sending weird values for this. */
3823 afs_uint32 skew = 0;
3828 int newAckCount = 0;
3829 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3830 int pktsize = 0; /* Set if we need to update the peer mtu */
3831 int conn_data_locked = 0;
3833 if (rx_stats_active)
3834 rx_MutexIncrement(rx_stats.ackPacketsRead, rx_stats_mutex);
3835 ap = (struct rx_ackPacket *)rx_DataOf(np);
3836 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3838 return np; /* truncated ack packet */
3840 /* depends on ack packet struct */
3841 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3842 first = ntohl(ap->firstPacket);
3843 serial = ntohl(ap->serial);
3844 /* temporarily disabled -- needs to degrade over time
3845 * skew = ntohs(ap->maxSkew); */
3847 /* Ignore ack packets received out of order */
3848 if (first < call->tfirst) {
3852 if (np->header.flags & RX_SLOW_START_OK) {
3853 call->flags |= RX_CALL_SLOW_START_OK;
3856 if (ap->reason == RX_ACK_PING_RESPONSE)
3857 rxi_UpdatePeerReach(conn, call);
3859 if (conn->lastPacketSizeSeq) {
3860 MUTEX_ENTER(&conn->conn_data_lock);
3861 conn_data_locked = 1;
3862 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
3863 pktsize = conn->lastPacketSize;
3864 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
3867 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
3868 if (!conn_data_locked) {
3869 MUTEX_ENTER(&conn->conn_data_lock);
3870 conn_data_locked = 1;
3872 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
3873 /* process mtu ping ack */
3874 pktsize = conn->lastPingSize;
3875 conn->lastPingSizeSer = conn->lastPingSize = 0;
3879 if (conn_data_locked) {
3880 MUTEX_EXIT(&conn->conn_data_lock);
3881 conn_data_locked = 0;
3885 if (rxdebug_active) {
3889 len = _snprintf(msg, sizeof(msg),
3890 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3891 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3892 ntohl(ap->serial), ntohl(ap->previousPacket),
3893 (unsigned int)np->header.seq, (unsigned int)skew,
3894 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3898 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3899 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3903 OutputDebugString(msg);
3905 #else /* AFS_NT40_ENV */
3908 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3909 ap->reason, ntohl(ap->previousPacket),
3910 (unsigned int)np->header.seq, (unsigned int)serial,
3911 (unsigned int)skew, ntohl(ap->firstPacket));
3914 for (offset = 0; offset < nAcks; offset++)
3915 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3920 #endif /* AFS_NT40_ENV */
3923 MUTEX_ENTER(&peer->peer_lock);
3926 * Start somewhere. Can't assume we can send what we can receive,
3927 * but we are clearly receiving.
3929 if (!peer->maxPacketSize)
3930 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
3932 if (pktsize > peer->maxPacketSize) {
3933 peer->maxPacketSize = pktsize;
3934 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
3935 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
3936 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
3937 rxi_ScheduleGrowMTUEvent(call, 1);
3942 /* Update the outgoing packet skew value to the latest value of
3943 * the peer's incoming packet skew value. The ack packet, of
3944 * course, could arrive out of order, but that won't affect things
3946 peer->outPacketSkew = skew;
3948 /* Check for packets that no longer need to be transmitted, and
3949 * discard them. This only applies to packets positively
3950 * acknowledged as having been sent to the peer's upper level.
3951 * All other packets must be retained. So only packets with
3952 * sequence numbers < ap->firstPacket are candidates. */
3953 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3954 if (tp->header.seq >= first)
3956 call->tfirst = tp->header.seq + 1;
3957 rxi_ComputePeerNetStats(call, tp, ap, np);
3958 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3961 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3962 /* XXX Hack. Because we have to release the global rx lock when sending
3963 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3964 * in rxi_Start sending packets out because packets may move to the
3965 * freePacketQueue as result of being here! So we drop these packets until
3966 * we're safely out of the traversing. Really ugly!
3967 * To make it even uglier, if we're using fine grain locking, we can
3968 * set the ack bits in the packets and have rxi_Start remove the packets
3969 * when it's done transmitting.
3971 if (call->flags & RX_CALL_TQ_BUSY) {
3972 #ifdef RX_ENABLE_LOCKS
3973 tp->flags |= RX_PKTFLAG_ACKED;
3974 call->flags |= RX_CALL_TQ_SOME_ACKED;
3975 #else /* RX_ENABLE_LOCKS */
3977 #endif /* RX_ENABLE_LOCKS */
3979 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3982 #ifdef RX_TRACK_PACKETS
3983 tp->flags &= ~RX_PKTFLAG_TQ;
3985 #ifdef RXDEBUG_PACKET
3987 #endif /* RXDEBUG_PACKET */
3988 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
3993 /* Give rate detector a chance to respond to ping requests */
3994 if (ap->reason == RX_ACK_PING_RESPONSE) {
3995 rxi_ComputeRate(peer, call, 0, np, ap->reason);
3999 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4001 /* Now go through explicit acks/nacks and record the results in
4002 * the waiting packets. These are packets that can't be released
4003 * yet, even with a positive acknowledge. This positive
4004 * acknowledge only means the packet has been received by the
4005 * peer, not that it will be retained long enough to be sent to
4006 * the peer's upper level. In addition, reset the transmit timers
4007 * of any missing packets (those packets that must be missing
4008 * because this packet was out of sequence) */
4010 call->nSoftAcked = 0;
4011 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4012 /* Update round trip time if the ack was stimulated on receipt
4014 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4015 #ifdef RX_ENABLE_LOCKS
4016 if (tp->header.seq >= first)
4017 #endif /* RX_ENABLE_LOCKS */
4018 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4019 rxi_ComputePeerNetStats(call, tp, ap, np);
4021 /* Set the acknowledge flag per packet based on the
4022 * information in the ack packet. An acknowlegded packet can
4023 * be downgraded when the server has discarded a packet it
4024 * soacked previously, or when an ack packet is received
4025 * out of sequence. */
4026 if (tp->header.seq < first) {
4027 /* Implicit ack information */
4028 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4031 tp->flags |= RX_PKTFLAG_ACKED;
4032 } else if (tp->header.seq < first + nAcks) {
4033 /* Explicit ack information: set it in the packet appropriately */
4034 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4035 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4037 tp->flags |= RX_PKTFLAG_ACKED;
4044 } else /* RX_ACK_TYPE_NACK */ {
4045 tp->flags &= ~RX_PKTFLAG_ACKED;
4049 tp->flags &= ~RX_PKTFLAG_ACKED;
4054 * Following the suggestion of Phil Kern, we back off the peer's
4055 * timeout value for future packets until a successful response
4056 * is received for an initial transmission.
4058 if (missing && !peer->backedOff) {
4059 struct clock c = peer->timeout;
4060 struct clock max_to = {3, 0};
4062 clock_Add(&peer->timeout, &c);
4063 if (clock_Gt(&peer->timeout, &max_to))
4064 peer->timeout = max_to;
4065 peer->backedOff = 1;
4068 /* If packet isn't yet acked, and it has been transmitted at least
4069 * once, reset retransmit time using latest timeout
4070 * ie, this should readjust the retransmit timer for all outstanding
4071 * packets... So we don't just retransmit when we should know better*/
4073 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4074 tp->retryTime = tp->timeSent;
4075 clock_Add(&tp->retryTime, &peer->timeout);
4076 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4077 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4081 /* If the window has been extended by this acknowledge packet,
4082 * then wakeup a sender waiting in alloc for window space, or try
4083 * sending packets now, if he's been sitting on packets due to
4084 * lack of window space */
4085 if (call->tnext < (call->tfirst + call->twind)) {
4086 #ifdef RX_ENABLE_LOCKS
4087 CV_SIGNAL(&call->cv_twind);
4089 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4090 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4091 osi_rxWakeup(&call->twind);
4094 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4095 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4099 /* if the ack packet has a receivelen field hanging off it,
4100 * update our state */
4101 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4104 /* If the ack packet has a "recommended" size that is less than
4105 * what I am using now, reduce my size to match */
4106 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4107 (int)sizeof(afs_int32), &tSize);
4108 tSize = (afs_uint32) ntohl(tSize);
4109 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4111 /* Get the maximum packet size to send to this peer */
4112 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4114 tSize = (afs_uint32) ntohl(tSize);
4115 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4116 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4118 /* sanity check - peer might have restarted with different params.
4119 * If peer says "send less", dammit, send less... Peer should never
4120 * be unable to accept packets of the size that prior AFS versions would
4121 * send without asking. */
4122 if (peer->maxMTU != tSize) {
4123 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4125 peer->maxMTU = tSize;
4126 peer->MTU = MIN(tSize, peer->MTU);
4127 call->MTU = MIN(call->MTU, tSize);
4130 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4133 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4134 (int)sizeof(afs_int32), &tSize);
4135 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4136 if (tSize < call->twind) { /* smaller than our send */
4137 call->twind = tSize; /* window, we must send less... */
4138 call->ssthresh = MIN(call->twind, call->ssthresh);
4139 call->conn->twind[call->channel] = call->twind;
4142 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4143 * network MTU confused with the loopback MTU. Calculate the
4144 * maximum MTU here for use in the slow start code below.
4146 /* Did peer restart with older RX version? */
4147 if (peer->maxDgramPackets > 1) {
4148 peer->maxDgramPackets = 1;
4150 } else if (np->length >=
4151 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4154 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4155 sizeof(afs_int32), &tSize);
4156 tSize = (afs_uint32) ntohl(tSize);
4158 * As of AFS 3.5 we set the send window to match the receive window.
4160 if (tSize < call->twind) {
4161 call->twind = tSize;
4162 call->conn->twind[call->channel] = call->twind;
4163 call->ssthresh = MIN(call->twind, call->ssthresh);
4164 } else if (tSize > call->twind) {
4165 call->twind = tSize;
4166 call->conn->twind[call->channel] = call->twind;
4170 * As of AFS 3.5, a jumbogram is more than one fixed size
4171 * packet transmitted in a single UDP datagram. If the remote
4172 * MTU is smaller than our local MTU then never send a datagram
4173 * larger than the natural MTU.
4176 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4177 (int)sizeof(afs_int32), &tSize);
4178 maxDgramPackets = (afs_uint32) ntohl(tSize);
4179 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4181 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4182 maxDgramPackets = MIN(maxDgramPackets, tSize);
4183 if (maxDgramPackets > 1) {
4184 peer->maxDgramPackets = maxDgramPackets;
4185 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4187 peer->maxDgramPackets = 1;
4188 call->MTU = peer->natMTU;
4190 } else if (peer->maxDgramPackets > 1) {
4191 /* Restarted with lower version of RX */
4192 peer->maxDgramPackets = 1;
4194 } else if (peer->maxDgramPackets > 1
4195 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4196 /* Restarted with lower version of RX */
4197 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4198 peer->natMTU = OLD_MAX_PACKET_SIZE;
4199 peer->MTU = OLD_MAX_PACKET_SIZE;
4200 peer->maxDgramPackets = 1;
4201 peer->nDgramPackets = 1;
4203 call->MTU = OLD_MAX_PACKET_SIZE;
4208 * Calculate how many datagrams were successfully received after
4209 * the first missing packet and adjust the negative ack counter
4214 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4215 if (call->nNacks < nNacked) {
4216 call->nNacks = nNacked;
4219 call->nAcks += newAckCount;
4223 if (call->flags & RX_CALL_FAST_RECOVER) {
4225 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4227 call->flags &= ~RX_CALL_FAST_RECOVER;
4228 call->cwind = call->nextCwind;
4229 call->nextCwind = 0;
4232 call->nCwindAcks = 0;
4233 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4234 /* Three negative acks in a row trigger congestion recovery */
4235 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4236 MUTEX_EXIT(&peer->peer_lock);
4237 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4238 /* someone else is waiting to start recovery */
4241 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4242 rxi_WaitforTQBusy(call);
4243 MUTEX_ENTER(&peer->peer_lock);
4244 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4245 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4246 call->flags |= RX_CALL_FAST_RECOVER;
4247 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4249 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4250 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4251 call->nextCwind = call->ssthresh;
4254 peer->MTU = call->MTU;
4255 peer->cwind = call->nextCwind;
4256 peer->nDgramPackets = call->nDgramPackets;
4258 call->congestSeq = peer->congestSeq;
4259 /* Reset the resend times on the packets that were nacked
4260 * so we will retransmit as soon as the window permits*/
4261 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4263 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4264 clock_Zero(&tp->retryTime);
4266 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4271 /* If cwind is smaller than ssthresh, then increase
4272 * the window one packet for each ack we receive (exponential
4274 * If cwind is greater than or equal to ssthresh then increase
4275 * the congestion window by one packet for each cwind acks we
4276 * receive (linear growth). */
4277 if (call->cwind < call->ssthresh) {
4279 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4280 call->nCwindAcks = 0;
4282 call->nCwindAcks += newAckCount;
4283 if (call->nCwindAcks >= call->cwind) {
4284 call->nCwindAcks = 0;
4285 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4289 * If we have received several acknowledgements in a row then
4290 * it is time to increase the size of our datagrams
4292 if ((int)call->nAcks > rx_nDgramThreshold) {
4293 if (peer->maxDgramPackets > 1) {
4294 if (call->nDgramPackets < peer->maxDgramPackets) {
4295 call->nDgramPackets++;
4297 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4298 } else if (call->MTU < peer->maxMTU) {
4299 /* don't upgrade if we can't handle it */
4300 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4301 call->MTU = peer->ifMTU;
4303 call->MTU += peer->natMTU;
4304 call->MTU = MIN(call->MTU, peer->maxMTU);
4311 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4313 /* Servers need to hold the call until all response packets have
4314 * been acknowledged. Soft acks are good enough since clients
4315 * are not allowed to clear their receive queues. */
4316 if (call->state == RX_STATE_HOLD
4317 && call->tfirst + call->nSoftAcked >= call->tnext) {
4318 call->state = RX_STATE_DALLY;
4319 rxi_ClearTransmitQueue(call, 0);
4320 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4321 } else if (!queue_IsEmpty(&call->tq)) {
4322 rxi_Start(0, call, 0, istack);
4327 /* Received a response to a challenge packet */
4329 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4330 struct rx_packet *np, int istack)
4334 /* Ignore the packet if we're the client */
4335 if (conn->type == RX_CLIENT_CONNECTION)