2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
14 #include "afs/param.h"
16 #include <afs/param.h>
21 #include "afs/sysincludes.h"
22 #include "afsincludes.h"
28 #include <net/net_globals.h>
29 #endif /* AFS_OSF_ENV */
30 #ifdef AFS_LINUX20_ENV
33 #include "netinet/in.h"
35 #include "inet/common.h"
37 #include "inet/ip_ire.h"
39 #include "afs/afs_args.h"
40 #include "afs/afs_osi.h"
41 #ifdef RX_KERNEL_TRACE
42 #include "rx_kcommon.h"
44 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
48 #undef RXDEBUG /* turn off debugging */
50 #if defined(AFS_SGI_ENV)
51 #include "sys/debug.h"
59 #endif /* AFS_OSF_ENV */
61 #include "afs/sysincludes.h"
62 #include "afsincludes.h"
65 #include "rx_kmutex.h"
66 #include "rx_kernel.h"
70 #include "rx_globals.h"
72 #include "rx_atomic.h"
73 #include "rx_internal.h"
75 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
76 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
77 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
79 extern afs_int32 afs_termState;
81 #include "sys/lockl.h"
82 #include "sys/lock_def.h"
83 #endif /* AFS_AIX41_ENV */
84 # include "afs/rxgen_consts.h"
86 # include <sys/types.h>
96 # include <afs/afsutil.h>
97 # include <WINNT\afsreg.h>
99 # include <sys/socket.h>
100 # include <sys/file.h>
102 # include <sys/stat.h>
103 # include <netinet/in.h>
104 # include <sys/time.h>
107 # include "rx_user.h"
108 # include "rx_clock.h"
109 # include "rx_queue.h"
110 # include "rx_atomic.h"
111 # include "rx_globals.h"
112 # include "rx_trace.h"
113 # include "rx_internal.h"
114 # include "rx_stats.h"
115 # include <afs/rxgen_consts.h>
119 #ifdef AFS_PTHREAD_ENV
121 int (*registerProgram) (pid_t, char *) = 0;
122 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
125 int (*registerProgram) (PROCESS, char *) = 0;
126 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
130 /* Local static routines */
131 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
132 #ifdef RX_ENABLE_LOCKS
133 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
136 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
138 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
139 rx_atomic_t rxi_start_in_error;
141 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
144 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
145 * currently allocated within rx. This number is used to allocate the
146 * memory required to return the statistics when queried.
147 * Protected by the rx_rpc_stats mutex.
150 static unsigned int rxi_rpc_peer_stat_cnt;
153 * rxi_rpc_process_stat_cnt counts the total number of local process stat
154 * structures currently allocated within rx. The number is used to allocate
155 * the memory required to return the statistics when queried.
156 * Protected by the rx_rpc_stats mutex.
159 static unsigned int rxi_rpc_process_stat_cnt;
161 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
162 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
164 #if !defined(offsetof)
165 #include <stddef.h> /* for definition of offsetof() */
168 #ifdef RX_ENABLE_LOCKS
169 afs_kmutex_t rx_atomic_mutex;
172 #ifdef AFS_PTHREAD_ENV
176 * Use procedural initialization of mutexes/condition variables
180 extern afs_kmutex_t rx_quota_mutex;
181 extern afs_kmutex_t rx_pthread_mutex;
182 extern afs_kmutex_t rx_packets_mutex;
183 extern afs_kmutex_t des_init_mutex;
184 extern afs_kmutex_t des_random_mutex;
185 extern afs_kmutex_t rx_clock_mutex;
186 extern afs_kmutex_t rxi_connCacheMutex;
187 extern afs_kmutex_t rx_event_mutex;
188 extern afs_kmutex_t osi_malloc_mutex;
189 extern afs_kmutex_t event_handler_mutex;
190 extern afs_kmutex_t listener_mutex;
191 extern afs_kmutex_t rx_if_init_mutex;
192 extern afs_kmutex_t rx_if_mutex;
193 extern afs_kmutex_t rxkad_client_uid_mutex;
194 extern afs_kmutex_t rxkad_random_mutex;
196 extern afs_kcondvar_t rx_event_handler_cond;
197 extern afs_kcondvar_t rx_listener_cond;
199 static afs_kmutex_t epoch_mutex;
200 static afs_kmutex_t rx_init_mutex;
201 static afs_kmutex_t rx_debug_mutex;
202 static afs_kmutex_t rx_rpc_stats;
205 rxi_InitPthread(void)
207 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
216 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
217 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
220 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
222 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
224 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
226 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
228 assert(pthread_cond_init
229 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
230 assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
232 assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
233 assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
235 rxkad_global_stats_init();
237 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
238 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
239 #ifdef RX_ENABLE_LOCKS
242 #endif /* RX_LOCKS_DB */
243 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
244 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
246 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
248 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
250 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
252 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
253 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
254 #endif /* RX_ENABLE_LOCKS */
257 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
258 #define INIT_PTHREAD_LOCKS \
259 assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
261 * The rx_stats_mutex mutex protects the following global variables:
262 * rxi_lowConnRefCount
263 * rxi_lowPeerRefCount
272 * The rx_quota_mutex mutex protects the following global variables:
280 * The rx_freePktQ_lock protects the following global variables:
285 * The rx_packets_mutex mutex protects the following global variables:
293 * The rx_pthread_mutex mutex protects the following global variables:
294 * rxi_fcfs_thread_num
297 #define INIT_PTHREAD_LOCKS
301 /* Variables for handling the minProcs implementation. availProcs gives the
302 * number of threads available in the pool at this moment (not counting dudes
303 * executing right now). totalMin gives the total number of procs required
304 * for handling all minProcs requests. minDeficit is a dynamic variable
305 * tracking the # of procs required to satisfy all of the remaining minProcs
307 * For fine grain locking to work, the quota check and the reservation of
308 * a server thread has to come while rxi_availProcs and rxi_minDeficit
309 * are locked. To this end, the code has been modified under #ifdef
310 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
311 * same time. A new function, ReturnToServerPool() returns the allocation.
313 * A call can be on several queue's (but only one at a time). When
314 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
315 * that no one else is touching the queue. To this end, we store the address
316 * of the queue lock in the call structure (under the call lock) when we
317 * put the call on a queue, and we clear the call_queue_lock when the
318 * call is removed from a queue (once the call lock has been obtained).
319 * This allows rxi_ResetCall to safely synchronize with others wishing
320 * to manipulate the queue.
323 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
324 static afs_kmutex_t rx_rpc_stats;
325 void rxi_StartUnlocked(struct rxevent *event, void *call,
326 void *arg1, int istack);
329 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
330 ** pretty good that the next packet coming in is from the same connection
331 ** as the last packet, since we're send multiple packets in a transmit window.
333 struct rx_connection *rxLastConn = 0;
335 #ifdef RX_ENABLE_LOCKS
336 /* The locking hierarchy for rx fine grain locking is composed of these
339 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
340 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
341 * call->lock - locks call data fields.
342 * These are independent of each other:
343 * rx_freeCallQueue_lock
348 * serverQueueEntry->lock
349 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
351 * peer->lock - locks peer data fields.
352 * conn_data_lock - that more than one thread is not updating a conn data
353 * field at the same time.
362 * Do we need a lock to protect the peer field in the conn structure?
363 * conn->peer was previously a constant for all intents and so has no
364 * lock protecting this field. The multihomed client delta introduced
365 * a RX code change : change the peer field in the connection structure
366 * to that remote interface from which the last packet for this
367 * connection was sent out. This may become an issue if further changes
370 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
371 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
373 /* rxdb_fileID is used to identify the lock location, along with line#. */
374 static int rxdb_fileID = RXDB_FILE_RX;
375 #endif /* RX_LOCKS_DB */
376 #else /* RX_ENABLE_LOCKS */
377 #define SET_CALL_QUEUE_LOCK(C, L)
378 #define CLEAR_CALL_QUEUE_LOCK(C)
379 #endif /* RX_ENABLE_LOCKS */
380 struct rx_serverQueueEntry *rx_waitForPacket = 0;
381 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
383 /* ------------Exported Interfaces------------- */
385 /* This function allows rxkad to set the epoch to a suitably random number
386 * which rx_NewConnection will use in the future. The principle purpose is to
387 * get rxnull connections to use the same epoch as the rxkad connections do, at
388 * least once the first rxkad connection is established. This is important now
389 * that the host/port addresses aren't used in FindConnection: the uniqueness
390 * of epoch/cid matters and the start time won't do. */
392 #ifdef AFS_PTHREAD_ENV
394 * This mutex protects the following global variables:
398 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
399 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
403 #endif /* AFS_PTHREAD_ENV */
406 rx_SetEpoch(afs_uint32 epoch)
413 /* Initialize rx. A port number may be mentioned, in which case this
414 * becomes the default port number for any service installed later.
415 * If 0 is provided for the port number, a random port will be chosen
416 * by the kernel. Whether this will ever overlap anything in
417 * /etc/services is anybody's guess... Returns 0 on success, -1 on
422 int rxinit_status = 1;
423 #ifdef AFS_PTHREAD_ENV
425 * This mutex protects the following global variables:
429 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
430 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
433 #define UNLOCK_RX_INIT
437 rx_InitHost(u_int host, u_int port)
444 char *htable, *ptable;
451 if (rxinit_status == 0) {
452 tmp_status = rxinit_status;
454 return tmp_status; /* Already started; return previous error code. */
460 if (afs_winsockInit() < 0)
466 * Initialize anything necessary to provide a non-premptive threading
469 rxi_InitializeThreadSupport();
472 /* Allocate and initialize a socket for client and perhaps server
475 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
476 if (rx_socket == OSI_NULLSOCKET) {
480 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
483 #endif /* RX_LOCKS_DB */
484 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
485 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
486 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
487 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
488 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
489 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
490 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
491 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
493 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
495 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
497 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
499 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
500 #if defined(AFS_HPUX110_ENV)
502 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
503 #endif /* AFS_HPUX110_ENV */
504 #endif /* RX_ENABLE_LOCKS && KERNEL */
507 rx_connDeadTime = 12;
508 rx_tranquil = 0; /* reset flag */
509 rxi_ResetStatistics();
511 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
512 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
513 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
514 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
515 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
516 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
518 /* Malloc up a bunch of packets & buffers */
520 queue_Init(&rx_freePacketQueue);
521 rxi_NeedMorePackets = FALSE;
522 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
524 /* enforce a minimum number of allocated packets */
525 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
526 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
528 /* allocate the initial free packet pool */
529 #ifdef RX_ENABLE_TSFPQ
530 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
531 #else /* RX_ENABLE_TSFPQ */
532 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
533 #endif /* RX_ENABLE_TSFPQ */
540 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
541 tv.tv_sec = clock_now.sec;
542 tv.tv_usec = clock_now.usec;
543 srand((unsigned int)tv.tv_usec);
550 #if defined(KERNEL) && !defined(UKERNEL)
551 /* Really, this should never happen in a real kernel */
554 struct sockaddr_in addr;
556 int addrlen = sizeof(addr);
558 socklen_t addrlen = sizeof(addr);
560 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
564 rx_port = addr.sin_port;
567 rx_stats.minRtt.sec = 9999999;
569 rx_SetEpoch(tv.tv_sec | 0x80000000);
571 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
572 * will provide a randomer value. */
574 MUTEX_ENTER(&rx_quota_mutex);
575 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
576 MUTEX_EXIT(&rx_quota_mutex);
577 /* *Slightly* random start time for the cid. This is just to help
578 * out with the hashing function at the peer */
579 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
580 rx_connHashTable = (struct rx_connection **)htable;
581 rx_peerHashTable = (struct rx_peer **)ptable;
583 rx_lastAckDelay.sec = 0;
584 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
585 rx_hardAckDelay.sec = 0;
586 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
587 rx_softAckDelay.sec = 0;
588 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
590 rxevent_Init(20, rxi_ReScheduleEvents);
592 /* Initialize various global queues */
593 queue_Init(&rx_idleServerQueue);
594 queue_Init(&rx_incomingCallQueue);
595 queue_Init(&rx_freeCallQueue);
597 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
598 /* Initialize our list of usable IP addresses. */
602 /* Start listener process (exact function is dependent on the
603 * implementation environment--kernel or user space) */
607 tmp_status = rxinit_status = 0;
615 return rx_InitHost(htonl(INADDR_ANY), port);
618 /* called with unincremented nRequestsRunning to see if it is OK to start
619 * a new thread in this service. Could be "no" for two reasons: over the
620 * max quota, or would prevent others from reaching their min quota.
622 #ifdef RX_ENABLE_LOCKS
623 /* This verion of QuotaOK reserves quota if it's ok while the
624 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
627 QuotaOK(struct rx_service *aservice)
629 /* check if over max quota */
630 if (aservice->nRequestsRunning >= aservice->maxProcs) {
634 /* under min quota, we're OK */
635 /* otherwise, can use only if there are enough to allow everyone
636 * to go to their min quota after this guy starts.
639 MUTEX_ENTER(&rx_quota_mutex);
640 if ((aservice->nRequestsRunning < aservice->minProcs)
641 || (rxi_availProcs > rxi_minDeficit)) {
642 aservice->nRequestsRunning++;
643 /* just started call in minProcs pool, need fewer to maintain
645 if (aservice->nRequestsRunning <= aservice->minProcs)
648 MUTEX_EXIT(&rx_quota_mutex);
651 MUTEX_EXIT(&rx_quota_mutex);
657 ReturnToServerPool(struct rx_service *aservice)
659 aservice->nRequestsRunning--;
660 MUTEX_ENTER(&rx_quota_mutex);
661 if (aservice->nRequestsRunning < aservice->minProcs)
664 MUTEX_EXIT(&rx_quota_mutex);
667 #else /* RX_ENABLE_LOCKS */
669 QuotaOK(struct rx_service *aservice)
672 /* under min quota, we're OK */
673 if (aservice->nRequestsRunning < aservice->minProcs)
676 /* check if over max quota */
677 if (aservice->nRequestsRunning >= aservice->maxProcs)
680 /* otherwise, can use only if there are enough to allow everyone
681 * to go to their min quota after this guy starts.
683 MUTEX_ENTER(&rx_quota_mutex);
684 if (rxi_availProcs > rxi_minDeficit)
686 MUTEX_EXIT(&rx_quota_mutex);
689 #endif /* RX_ENABLE_LOCKS */
692 /* Called by rx_StartServer to start up lwp's to service calls.
693 NExistingProcs gives the number of procs already existing, and which
694 therefore needn't be created. */
696 rxi_StartServerProcs(int nExistingProcs)
698 struct rx_service *service;
703 /* For each service, reserve N processes, where N is the "minimum"
704 * number of processes that MUST be able to execute a request in parallel,
705 * at any time, for that process. Also compute the maximum difference
706 * between any service's maximum number of processes that can run
707 * (i.e. the maximum number that ever will be run, and a guarantee
708 * that this number will run if other services aren't running), and its
709 * minimum number. The result is the extra number of processes that
710 * we need in order to provide the latter guarantee */
711 for (i = 0; i < RX_MAX_SERVICES; i++) {
713 service = rx_services[i];
714 if (service == (struct rx_service *)0)
716 nProcs += service->minProcs;
717 diff = service->maxProcs - service->minProcs;
721 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
722 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
723 for (i = 0; i < nProcs; i++) {
724 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
730 /* This routine is only required on Windows */
732 rx_StartClientThread(void)
734 #ifdef AFS_PTHREAD_ENV
736 pid = pthread_self();
737 #endif /* AFS_PTHREAD_ENV */
739 #endif /* AFS_NT40_ENV */
741 /* This routine must be called if any services are exported. If the
742 * donateMe flag is set, the calling process is donated to the server
745 rx_StartServer(int donateMe)
747 struct rx_service *service;
753 /* Start server processes, if necessary (exact function is dependent
754 * on the implementation environment--kernel or user space). DonateMe
755 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
756 * case, one less new proc will be created rx_StartServerProcs.
758 rxi_StartServerProcs(donateMe);
760 /* count up the # of threads in minProcs, and add set the min deficit to
761 * be that value, too.
763 for (i = 0; i < RX_MAX_SERVICES; i++) {
764 service = rx_services[i];
765 if (service == (struct rx_service *)0)
767 MUTEX_ENTER(&rx_quota_mutex);
768 rxi_totalMin += service->minProcs;
769 /* below works even if a thread is running, since minDeficit would
770 * still have been decremented and later re-incremented.
772 rxi_minDeficit += service->minProcs;
773 MUTEX_EXIT(&rx_quota_mutex);
776 /* Turn on reaping of idle server connections */
777 rxi_ReapConnections(NULL, NULL, NULL);
786 #ifdef AFS_PTHREAD_ENV
788 pid = afs_pointer_to_int(pthread_self());
789 #else /* AFS_PTHREAD_ENV */
791 LWP_CurrentProcess(&pid);
792 #endif /* AFS_PTHREAD_ENV */
794 sprintf(name, "srv_%d", ++nProcs);
796 (*registerProgram) (pid, name);
798 #endif /* AFS_NT40_ENV */
799 rx_ServerProc(NULL); /* Never returns */
801 #ifdef RX_ENABLE_TSFPQ
802 /* no use leaving packets around in this thread's local queue if
803 * it isn't getting donated to the server thread pool.
805 rxi_FlushLocalPacketsTSFPQ();
806 #endif /* RX_ENABLE_TSFPQ */
810 /* Create a new client connection to the specified service, using the
811 * specified security object to implement the security model for this
813 struct rx_connection *
814 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
815 struct rx_securityClass *securityObject,
816 int serviceSecurityIndex)
820 struct rx_connection *conn;
825 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
826 "serviceSecurityIndex %d)\n",
827 ntohl(shost), ntohs(sport), sservice, securityObject,
828 serviceSecurityIndex));
830 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
831 * the case of kmem_alloc? */
832 conn = rxi_AllocConnection();
833 #ifdef RX_ENABLE_LOCKS
834 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
835 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
836 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
839 MUTEX_ENTER(&rx_connHashTable_lock);
840 cid = (rx_nextCid += RX_MAXCALLS);
841 conn->type = RX_CLIENT_CONNECTION;
843 conn->epoch = rx_epoch;
844 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
845 conn->serviceId = sservice;
846 conn->securityObject = securityObject;
847 conn->securityData = (void *) 0;
848 conn->securityIndex = serviceSecurityIndex;
849 rx_SetConnDeadTime(conn, rx_connDeadTime);
850 rx_SetConnSecondsUntilNatPing(conn, 0);
851 conn->ackRate = RX_FAST_ACK_RATE;
853 conn->specific = NULL;
854 conn->challengeEvent = NULL;
855 conn->delayedAbortEvent = NULL;
856 conn->abortCount = 0;
858 for (i = 0; i < RX_MAXCALLS; i++) {
859 conn->twind[i] = rx_initSendWindow;
860 conn->rwind[i] = rx_initReceiveWindow;
863 RXS_NewConnection(securityObject, conn);
865 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
867 conn->refCount++; /* no lock required since only this thread knows... */
868 conn->next = rx_connHashTable[hashindex];
869 rx_connHashTable[hashindex] = conn;
871 rx_atomic_inc(&rx_stats.nClientConns);
872 MUTEX_EXIT(&rx_connHashTable_lock);
878 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
880 /* The idea is to set the dead time to a value that allows several
881 * keepalives to be dropped without timing out the connection. */
882 conn->secondsUntilDead = MAX(seconds, 6);
883 conn->secondsUntilPing = conn->secondsUntilDead / 6;
886 int rxi_lowPeerRefCount = 0;
887 int rxi_lowConnRefCount = 0;
890 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
891 * NOTE: must not be called with rx_connHashTable_lock held.
894 rxi_CleanupConnection(struct rx_connection *conn)
896 /* Notify the service exporter, if requested, that this connection
897 * is being destroyed */
898 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
899 (*conn->service->destroyConnProc) (conn);
901 /* Notify the security module that this connection is being destroyed */
902 RXS_DestroyConnection(conn->securityObject, conn);
904 /* If this is the last connection using the rx_peer struct, set its
905 * idle time to now. rxi_ReapConnections will reap it if it's still
906 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
908 MUTEX_ENTER(&rx_peerHashTable_lock);
909 if (conn->peer->refCount < 2) {
910 conn->peer->idleWhen = clock_Sec();
911 if (conn->peer->refCount < 1) {
912 conn->peer->refCount = 1;
913 if (rx_stats_active) {
914 MUTEX_ENTER(&rx_stats_mutex);
915 rxi_lowPeerRefCount++;
916 MUTEX_EXIT(&rx_stats_mutex);
920 conn->peer->refCount--;
921 MUTEX_EXIT(&rx_peerHashTable_lock);
925 if (conn->type == RX_SERVER_CONNECTION)
926 rx_atomic_dec(&rx_stats.nServerConns);
928 rx_atomic_dec(&rx_stats.nClientConns);
931 if (conn->specific) {
933 for (i = 0; i < conn->nSpecific; i++) {
934 if (conn->specific[i] && rxi_keyCreate_destructor[i])
935 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
936 conn->specific[i] = NULL;
938 free(conn->specific);
940 conn->specific = NULL;
944 MUTEX_DESTROY(&conn->conn_call_lock);
945 MUTEX_DESTROY(&conn->conn_data_lock);
946 CV_DESTROY(&conn->conn_call_cv);
948 rxi_FreeConnection(conn);
951 /* Destroy the specified connection */
953 rxi_DestroyConnection(struct rx_connection *conn)
955 MUTEX_ENTER(&rx_connHashTable_lock);
956 rxi_DestroyConnectionNoLock(conn);
957 /* conn should be at the head of the cleanup list */
958 if (conn == rx_connCleanup_list) {
959 rx_connCleanup_list = rx_connCleanup_list->next;
960 MUTEX_EXIT(&rx_connHashTable_lock);
961 rxi_CleanupConnection(conn);
963 #ifdef RX_ENABLE_LOCKS
965 MUTEX_EXIT(&rx_connHashTable_lock);
967 #endif /* RX_ENABLE_LOCKS */
971 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
973 struct rx_connection **conn_ptr;
975 struct rx_packet *packet;
982 MUTEX_ENTER(&conn->conn_data_lock);
983 if (conn->refCount > 0)
986 if (rx_stats_active) {
987 MUTEX_ENTER(&rx_stats_mutex);
988 rxi_lowConnRefCount++;
989 MUTEX_EXIT(&rx_stats_mutex);
993 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
994 /* Busy; wait till the last guy before proceeding */
995 MUTEX_EXIT(&conn->conn_data_lock);
1000 /* If the client previously called rx_NewCall, but it is still
1001 * waiting, treat this as a running call, and wait to destroy the
1002 * connection later when the call completes. */
1003 if ((conn->type == RX_CLIENT_CONNECTION)
1004 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1005 conn->flags |= RX_CONN_DESTROY_ME;
1006 MUTEX_EXIT(&conn->conn_data_lock);
1010 MUTEX_EXIT(&conn->conn_data_lock);
1012 /* Check for extant references to this connection */
1013 for (i = 0; i < RX_MAXCALLS; i++) {
1014 struct rx_call *call = conn->call[i];
1017 if (conn->type == RX_CLIENT_CONNECTION) {
1018 MUTEX_ENTER(&call->lock);
1019 if (call->delayedAckEvent) {
1020 /* Push the final acknowledgment out now--there
1021 * won't be a subsequent call to acknowledge the
1022 * last reply packets */
1023 rxevent_Cancel(call->delayedAckEvent, call,
1024 RX_CALL_REFCOUNT_DELAY);
1025 if (call->state == RX_STATE_PRECALL
1026 || call->state == RX_STATE_ACTIVE) {
1027 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1029 rxi_AckAll(NULL, call, 0);
1032 MUTEX_EXIT(&call->lock);
1036 #ifdef RX_ENABLE_LOCKS
1038 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1039 MUTEX_EXIT(&conn->conn_data_lock);
1041 /* Someone is accessing a packet right now. */
1045 #endif /* RX_ENABLE_LOCKS */
1048 /* Don't destroy the connection if there are any call
1049 * structures still in use */
1050 MUTEX_ENTER(&conn->conn_data_lock);
1051 conn->flags |= RX_CONN_DESTROY_ME;
1052 MUTEX_EXIT(&conn->conn_data_lock);
1057 if (conn->natKeepAliveEvent) {
1058 rxi_NatKeepAliveOff(conn);
1061 if (conn->delayedAbortEvent) {
1062 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1063 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1065 MUTEX_ENTER(&conn->conn_data_lock);
1066 rxi_SendConnectionAbort(conn, packet, 0, 1);
1067 MUTEX_EXIT(&conn->conn_data_lock);
1068 rxi_FreePacket(packet);
1072 /* Remove from connection hash table before proceeding */
1074 &rx_connHashTable[CONN_HASH
1075 (peer->host, peer->port, conn->cid, conn->epoch,
1077 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1078 if (*conn_ptr == conn) {
1079 *conn_ptr = conn->next;
1083 /* if the conn that we are destroying was the last connection, then we
1084 * clear rxLastConn as well */
1085 if (rxLastConn == conn)
1088 /* Make sure the connection is completely reset before deleting it. */
1089 /* get rid of pending events that could zap us later */
1090 if (conn->challengeEvent)
1091 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1092 if (conn->checkReachEvent)
1093 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1094 if (conn->natKeepAliveEvent)
1095 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1097 /* Add the connection to the list of destroyed connections that
1098 * need to be cleaned up. This is necessary to avoid deadlocks
1099 * in the routines we call to inform others that this connection is
1100 * being destroyed. */
1101 conn->next = rx_connCleanup_list;
1102 rx_connCleanup_list = conn;
1105 /* Externally available version */
1107 rx_DestroyConnection(struct rx_connection *conn)
1112 rxi_DestroyConnection(conn);
1117 rx_GetConnection(struct rx_connection *conn)
1122 MUTEX_ENTER(&conn->conn_data_lock);
1124 MUTEX_EXIT(&conn->conn_data_lock);
1128 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1129 /* Wait for the transmit queue to no longer be busy.
1130 * requires the call->lock to be held */
1131 static void rxi_WaitforTQBusy(struct rx_call *call) {
1132 while (call->flags & RX_CALL_TQ_BUSY) {
1133 call->flags |= RX_CALL_TQ_WAIT;
1135 #ifdef RX_ENABLE_LOCKS
1136 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1137 CV_WAIT(&call->cv_tq, &call->lock);
1138 #else /* RX_ENABLE_LOCKS */
1139 osi_rxSleep(&call->tq);
1140 #endif /* RX_ENABLE_LOCKS */
1142 if (call->tqWaiters == 0) {
1143 call->flags &= ~RX_CALL_TQ_WAIT;
1149 /* Start a new rx remote procedure call, on the specified connection.
1150 * If wait is set to 1, wait for a free call channel; otherwise return
1151 * 0. Maxtime gives the maximum number of seconds this call may take,
1152 * after rx_NewCall returns. After this time interval, a call to any
1153 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1154 * For fine grain locking, we hold the conn_call_lock in order to
1155 * to ensure that we don't get signalle after we found a call in an active
1156 * state and before we go to sleep.
1159 rx_NewCall(struct rx_connection *conn)
1162 struct rx_call *call;
1163 struct clock queueTime;
1167 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1170 clock_GetTime(&queueTime);
1172 * Check if there are others waiting for a new call.
1173 * If so, let them go first to avoid starving them.
1174 * This is a fairly simple scheme, and might not be
1175 * a complete solution for large numbers of waiters.
1177 * makeCallWaiters keeps track of the number of
1178 * threads waiting to make calls and the
1179 * RX_CONN_MAKECALL_WAITING flag bit is used to
1180 * indicate that there are indeed calls waiting.
1181 * The flag is set when the waiter is incremented.
1182 * It is only cleared when makeCallWaiters is 0.
1183 * This prevents us from accidently destroying the
1184 * connection while it is potentially about to be used.
1186 MUTEX_ENTER(&conn->conn_call_lock);
1187 MUTEX_ENTER(&conn->conn_data_lock);
1188 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1189 conn->flags |= RX_CONN_MAKECALL_WAITING;
1190 conn->makeCallWaiters++;
1191 MUTEX_EXIT(&conn->conn_data_lock);
1193 #ifdef RX_ENABLE_LOCKS
1194 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1198 MUTEX_ENTER(&conn->conn_data_lock);
1199 conn->makeCallWaiters--;
1200 if (conn->makeCallWaiters == 0)
1201 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1204 /* We are now the active thread in rx_NewCall */
1205 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1206 MUTEX_EXIT(&conn->conn_data_lock);
1211 for (i = 0; i < RX_MAXCALLS; i++) {
1212 call = conn->call[i];
1214 if (call->state == RX_STATE_DALLY) {
1215 MUTEX_ENTER(&call->lock);
1216 if (call->state == RX_STATE_DALLY) {
1218 * We are setting the state to RX_STATE_RESET to
1219 * ensure that no one else will attempt to use this
1220 * call once we drop the conn->conn_call_lock and
1221 * call->lock. We must drop the conn->conn_call_lock
1222 * before calling rxi_ResetCall because the process
1223 * of clearing the transmit queue can block for an
1224 * extended period of time. If we block while holding
1225 * the conn->conn_call_lock, then all rx_EndCall
1226 * processing will block as well. This has a detrimental
1227 * effect on overall system performance.
1229 call->state = RX_STATE_RESET;
1230 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1231 MUTEX_EXIT(&conn->conn_call_lock);
1232 rxi_ResetCall(call, 0);
1233 (*call->callNumber)++;
1234 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1238 * If we failed to be able to safely obtain the
1239 * conn->conn_call_lock we will have to drop the
1240 * call->lock to avoid a deadlock. When the call->lock
1241 * is released the state of the call can change. If it
1242 * is no longer RX_STATE_RESET then some other thread is
1245 MUTEX_EXIT(&call->lock);
1246 MUTEX_ENTER(&conn->conn_call_lock);
1247 MUTEX_ENTER(&call->lock);
1249 if (call->state == RX_STATE_RESET)
1253 * If we get here it means that after dropping
1254 * the conn->conn_call_lock and call->lock that
1255 * the call is no longer ours. If we can't find
1256 * a free call in the remaining slots we should
1257 * not go immediately to RX_CONN_MAKECALL_WAITING
1258 * because by dropping the conn->conn_call_lock
1259 * we have given up synchronization with rx_EndCall.
1260 * Instead, cycle through one more time to see if
1261 * we can find a call that can call our own.
1263 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1266 MUTEX_EXIT(&call->lock);
1269 /* rxi_NewCall returns with mutex locked */
1270 call = rxi_NewCall(conn, i);
1271 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1275 if (i < RX_MAXCALLS) {
1281 MUTEX_ENTER(&conn->conn_data_lock);
1282 conn->flags |= RX_CONN_MAKECALL_WAITING;
1283 conn->makeCallWaiters++;
1284 MUTEX_EXIT(&conn->conn_data_lock);
1286 #ifdef RX_ENABLE_LOCKS
1287 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1291 MUTEX_ENTER(&conn->conn_data_lock);
1292 conn->makeCallWaiters--;
1293 if (conn->makeCallWaiters == 0)
1294 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1295 MUTEX_EXIT(&conn->conn_data_lock);
1297 /* Client is initially in send mode */
1298 call->state = RX_STATE_ACTIVE;
1299 call->error = conn->error;
1301 call->mode = RX_MODE_ERROR;
1303 call->mode = RX_MODE_SENDING;
1305 /* remember start time for call in case we have hard dead time limit */
1306 call->queueTime = queueTime;
1307 clock_GetTime(&call->startTime);
1308 hzero(call->bytesSent);
1309 hzero(call->bytesRcvd);
1311 /* Turn on busy protocol. */
1312 rxi_KeepAliveOn(call);
1314 /* Attempt MTU discovery */
1315 rxi_GrowMTUOn(call);
1318 * We are no longer the active thread in rx_NewCall
1320 MUTEX_ENTER(&conn->conn_data_lock);
1321 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1322 MUTEX_EXIT(&conn->conn_data_lock);
1325 * Wake up anyone else who might be giving us a chance to
1326 * run (see code above that avoids resource starvation).
1328 #ifdef RX_ENABLE_LOCKS
1329 CV_BROADCAST(&conn->conn_call_cv);
1333 MUTEX_EXIT(&conn->conn_call_lock);
1335 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1336 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1337 osi_Panic("rx_NewCall call about to be used without an empty tq");
1339 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1341 MUTEX_EXIT(&call->lock);
1344 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1349 rxi_HasActiveCalls(struct rx_connection *aconn)
1352 struct rx_call *tcall;
1356 for (i = 0; i < RX_MAXCALLS; i++) {
1357 if ((tcall = aconn->call[i])) {
1358 if ((tcall->state == RX_STATE_ACTIVE)
1359 || (tcall->state == RX_STATE_PRECALL)) {
1370 rxi_GetCallNumberVector(struct rx_connection *aconn,
1371 afs_int32 * aint32s)
1374 struct rx_call *tcall;
1378 for (i = 0; i < RX_MAXCALLS; i++) {
1379 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1380 aint32s[i] = aconn->callNumber[i] + 1;
1382 aint32s[i] = aconn->callNumber[i];
1389 rxi_SetCallNumberVector(struct rx_connection *aconn,
1390 afs_int32 * aint32s)
1393 struct rx_call *tcall;
1397 for (i = 0; i < RX_MAXCALLS; i++) {
1398 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1399 aconn->callNumber[i] = aint32s[i] - 1;
1401 aconn->callNumber[i] = aint32s[i];
1407 /* Advertise a new service. A service is named locally by a UDP port
1408 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1411 char *serviceName; Name for identification purposes (e.g. the
1412 service name might be used for probing for
1415 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1416 char *serviceName, struct rx_securityClass **securityObjects,
1417 int nSecurityObjects,
1418 afs_int32(*serviceProc) (struct rx_call * acall))
1420 osi_socket socket = OSI_NULLSOCKET;
1421 struct rx_service *tservice;
1427 if (serviceId == 0) {
1429 "rx_NewService: service id for service %s is not non-zero.\n",
1436 "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",
1444 tservice = rxi_AllocService();
1447 #ifdef RX_ENABLE_LOCKS
1448 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1451 for (i = 0; i < RX_MAX_SERVICES; i++) {
1452 struct rx_service *service = rx_services[i];
1454 if (port == service->servicePort && host == service->serviceHost) {
1455 if (service->serviceId == serviceId) {
1456 /* The identical service has already been
1457 * installed; if the caller was intending to
1458 * change the security classes used by this
1459 * service, he/she loses. */
1461 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1462 serviceName, serviceId, service->serviceName);
1464 rxi_FreeService(tservice);
1467 /* Different service, same port: re-use the socket
1468 * which is bound to the same port */
1469 socket = service->socket;
1472 if (socket == OSI_NULLSOCKET) {
1473 /* If we don't already have a socket (from another
1474 * service on same port) get a new one */
1475 socket = rxi_GetHostUDPSocket(host, port);
1476 if (socket == OSI_NULLSOCKET) {
1478 rxi_FreeService(tservice);
1483 service->socket = socket;
1484 service->serviceHost = host;
1485 service->servicePort = port;
1486 service->serviceId = serviceId;
1487 service->serviceName = serviceName;
1488 service->nSecurityObjects = nSecurityObjects;
1489 service->securityObjects = securityObjects;
1490 service->minProcs = 0;
1491 service->maxProcs = 1;
1492 service->idleDeadTime = 60;
1493 service->idleDeadErr = 0;
1494 service->connDeadTime = rx_connDeadTime;
1495 service->executeRequestProc = serviceProc;
1496 service->checkReach = 0;
1497 service->nSpecific = 0;
1498 service->specific = NULL;
1499 rx_services[i] = service; /* not visible until now */
1505 rxi_FreeService(tservice);
1506 (osi_Msg "rx_NewService: cannot support > %d services\n",
1511 /* Set configuration options for all of a service's security objects */
1514 rx_SetSecurityConfiguration(struct rx_service *service,
1515 rx_securityConfigVariables type,
1519 for (i = 0; i<service->nSecurityObjects; i++) {
1520 if (service->securityObjects[i]) {
1521 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1529 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1530 struct rx_securityClass **securityObjects, int nSecurityObjects,
1531 afs_int32(*serviceProc) (struct rx_call * acall))
1533 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1536 /* Generic request processing loop. This routine should be called
1537 * by the implementation dependent rx_ServerProc. If socketp is
1538 * non-null, it will be set to the file descriptor that this thread
1539 * is now listening on. If socketp is null, this routine will never
1542 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1544 struct rx_call *call;
1546 struct rx_service *tservice = NULL;
1553 call = rx_GetCall(threadID, tservice, socketp);
1554 if (socketp && *socketp != OSI_NULLSOCKET) {
1555 /* We are now a listener thread */
1560 /* if server is restarting( typically smooth shutdown) then do not
1561 * allow any new calls.
1564 if (rx_tranquil && (call != NULL)) {
1568 MUTEX_ENTER(&call->lock);
1570 rxi_CallError(call, RX_RESTARTING);
1571 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1573 MUTEX_EXIT(&call->lock);
1577 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1578 #ifdef RX_ENABLE_LOCKS
1580 #endif /* RX_ENABLE_LOCKS */
1581 afs_termState = AFSOP_STOP_AFS;
1582 afs_osi_Wakeup(&afs_termState);
1583 #ifdef RX_ENABLE_LOCKS
1585 #endif /* RX_ENABLE_LOCKS */
1590 tservice = call->conn->service;
1592 if (tservice->beforeProc)
1593 (*tservice->beforeProc) (call);
1595 code = tservice->executeRequestProc(call);
1597 if (tservice->afterProc)
1598 (*tservice->afterProc) (call, code);
1600 rx_EndCall(call, code);
1601 if (rx_stats_active) {
1602 MUTEX_ENTER(&rx_stats_mutex);
1604 MUTEX_EXIT(&rx_stats_mutex);
1611 rx_WakeupServerProcs(void)
1613 struct rx_serverQueueEntry *np, *tqp;
1617 MUTEX_ENTER(&rx_serverPool_lock);
1619 #ifdef RX_ENABLE_LOCKS
1620 if (rx_waitForPacket)
1621 CV_BROADCAST(&rx_waitForPacket->cv);
1622 #else /* RX_ENABLE_LOCKS */
1623 if (rx_waitForPacket)
1624 osi_rxWakeup(rx_waitForPacket);
1625 #endif /* RX_ENABLE_LOCKS */
1626 MUTEX_ENTER(&freeSQEList_lock);
1627 for (np = rx_FreeSQEList; np; np = tqp) {
1628 tqp = *(struct rx_serverQueueEntry **)np;
1629 #ifdef RX_ENABLE_LOCKS
1630 CV_BROADCAST(&np->cv);
1631 #else /* RX_ENABLE_LOCKS */
1633 #endif /* RX_ENABLE_LOCKS */
1635 MUTEX_EXIT(&freeSQEList_lock);
1636 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1637 #ifdef RX_ENABLE_LOCKS
1638 CV_BROADCAST(&np->cv);
1639 #else /* RX_ENABLE_LOCKS */
1641 #endif /* RX_ENABLE_LOCKS */
1643 MUTEX_EXIT(&rx_serverPool_lock);
1648 * One thing that seems to happen is that all the server threads get
1649 * tied up on some empty or slow call, and then a whole bunch of calls
1650 * arrive at once, using up the packet pool, so now there are more
1651 * empty calls. The most critical resources here are server threads
1652 * and the free packet pool. The "doreclaim" code seems to help in
1653 * general. I think that eventually we arrive in this state: there
1654 * are lots of pending calls which do have all their packets present,
1655 * so they won't be reclaimed, are multi-packet calls, so they won't
1656 * be scheduled until later, and thus are tying up most of the free
1657 * packet pool for a very long time.
1659 * 1. schedule multi-packet calls if all the packets are present.
1660 * Probably CPU-bound operation, useful to return packets to pool.
1661 * Do what if there is a full window, but the last packet isn't here?
1662 * 3. preserve one thread which *only* runs "best" calls, otherwise
1663 * it sleeps and waits for that type of call.
1664 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1665 * the current dataquota business is badly broken. The quota isn't adjusted
1666 * to reflect how many packets are presently queued for a running call.
1667 * So, when we schedule a queued call with a full window of packets queued
1668 * up for it, that *should* free up a window full of packets for other 2d-class
1669 * calls to be able to use from the packet pool. But it doesn't.
1671 * NB. Most of the time, this code doesn't run -- since idle server threads
1672 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1673 * as a new call arrives.
1675 /* Sleep until a call arrives. Returns a pointer to the call, ready
1676 * for an rx_Read. */
1677 #ifdef RX_ENABLE_LOCKS
1679 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1681 struct rx_serverQueueEntry *sq;
1682 struct rx_call *call = (struct rx_call *)0;
1683 struct rx_service *service = NULL;
1686 MUTEX_ENTER(&freeSQEList_lock);
1688 if ((sq = rx_FreeSQEList)) {
1689 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1690 MUTEX_EXIT(&freeSQEList_lock);
1691 } else { /* otherwise allocate a new one and return that */
1692 MUTEX_EXIT(&freeSQEList_lock);
1693 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1694 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1695 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1698 MUTEX_ENTER(&rx_serverPool_lock);
1699 if (cur_service != NULL) {
1700 ReturnToServerPool(cur_service);
1703 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1704 struct rx_call *tcall, *ncall, *choice2 = NULL;
1706 /* Scan for eligible incoming calls. A call is not eligible
1707 * if the maximum number of calls for its service type are
1708 * already executing */
1709 /* One thread will process calls FCFS (to prevent starvation),
1710 * while the other threads may run ahead looking for calls which
1711 * have all their input data available immediately. This helps
1712 * keep threads from blocking, waiting for data from the client. */
1713 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1714 service = tcall->conn->service;
1715 if (!QuotaOK(service)) {
1718 MUTEX_ENTER(&rx_pthread_mutex);
1719 if (tno == rxi_fcfs_thread_num
1720 || !tcall->queue_item_header.next) {
1721 MUTEX_EXIT(&rx_pthread_mutex);
1722 /* If we're the fcfs thread , then we'll just use
1723 * this call. If we haven't been able to find an optimal
1724 * choice, and we're at the end of the list, then use a
1725 * 2d choice if one has been identified. Otherwise... */
1726 call = (choice2 ? choice2 : tcall);
1727 service = call->conn->service;
1729 MUTEX_EXIT(&rx_pthread_mutex);
1730 if (!queue_IsEmpty(&tcall->rq)) {
1731 struct rx_packet *rp;
1732 rp = queue_First(&tcall->rq, rx_packet);
1733 if (rp->header.seq == 1) {
1735 || (rp->header.flags & RX_LAST_PACKET)) {
1737 } else if (rxi_2dchoice && !choice2
1738 && !(tcall->flags & RX_CALL_CLEARED)
1739 && (tcall->rprev > rxi_HardAckRate)) {
1749 ReturnToServerPool(service);
1756 MUTEX_EXIT(&rx_serverPool_lock);
1757 MUTEX_ENTER(&call->lock);
1759 if (call->flags & RX_CALL_WAIT_PROC) {
1760 call->flags &= ~RX_CALL_WAIT_PROC;
1761 rx_atomic_dec(&rx_nWaiting);
1764 if (call->state != RX_STATE_PRECALL || call->error) {
1765 MUTEX_EXIT(&call->lock);
1766 MUTEX_ENTER(&rx_serverPool_lock);
1767 ReturnToServerPool(service);
1772 if (queue_IsEmpty(&call->rq)
1773 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1774 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1776 CLEAR_CALL_QUEUE_LOCK(call);
1779 /* If there are no eligible incoming calls, add this process
1780 * to the idle server queue, to wait for one */
1784 *socketp = OSI_NULLSOCKET;
1786 sq->socketp = socketp;
1787 queue_Append(&rx_idleServerQueue, sq);
1788 #ifndef AFS_AIX41_ENV
1789 rx_waitForPacket = sq;
1791 rx_waitingForPacket = sq;
1792 #endif /* AFS_AIX41_ENV */
1794 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1796 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1797 MUTEX_EXIT(&rx_serverPool_lock);
1798 return (struct rx_call *)0;
1801 } while (!(call = sq->newcall)
1802 && !(socketp && *socketp != OSI_NULLSOCKET));
1803 MUTEX_EXIT(&rx_serverPool_lock);
1805 MUTEX_ENTER(&call->lock);
1811 MUTEX_ENTER(&freeSQEList_lock);
1812 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1813 rx_FreeSQEList = sq;
1814 MUTEX_EXIT(&freeSQEList_lock);
1817 clock_GetTime(&call->startTime);
1818 call->state = RX_STATE_ACTIVE;
1819 call->mode = RX_MODE_RECEIVING;
1820 #ifdef RX_KERNEL_TRACE
1821 if (ICL_SETACTIVE(afs_iclSetp)) {
1822 int glockOwner = ISAFS_GLOCK();
1825 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1826 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1833 rxi_calltrace(RX_CALL_START, call);
1834 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1835 call->conn->service->servicePort, call->conn->service->serviceId,
1838 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1839 MUTEX_EXIT(&call->lock);
1841 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1846 #else /* RX_ENABLE_LOCKS */
1848 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1850 struct rx_serverQueueEntry *sq;
1851 struct rx_call *call = (struct rx_call *)0, *choice2;
1852 struct rx_service *service = NULL;
1856 MUTEX_ENTER(&freeSQEList_lock);
1858 if ((sq = rx_FreeSQEList)) {
1859 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1860 MUTEX_EXIT(&freeSQEList_lock);
1861 } else { /* otherwise allocate a new one and return that */
1862 MUTEX_EXIT(&freeSQEList_lock);
1863 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1864 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1865 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1867 MUTEX_ENTER(&sq->lock);
1869 if (cur_service != NULL) {
1870 cur_service->nRequestsRunning--;
1871 MUTEX_ENTER(&rx_quota_mutex);
1872 if (cur_service->nRequestsRunning < cur_service->minProcs)
1875 MUTEX_EXIT(&rx_quota_mutex);
1877 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1878 struct rx_call *tcall, *ncall;
1879 /* Scan for eligible incoming calls. A call is not eligible
1880 * if the maximum number of calls for its service type are
1881 * already executing */
1882 /* One thread will process calls FCFS (to prevent starvation),
1883 * while the other threads may run ahead looking for calls which
1884 * have all their input data available immediately. This helps
1885 * keep threads from blocking, waiting for data from the client. */
1886 choice2 = (struct rx_call *)0;
1887 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1888 service = tcall->conn->service;
1889 if (QuotaOK(service)) {
1890 MUTEX_ENTER(&rx_pthread_mutex);
1891 if (tno == rxi_fcfs_thread_num
1892 || !tcall->queue_item_header.next) {
1893 MUTEX_EXIT(&rx_pthread_mutex);
1894 /* If we're the fcfs thread, then we'll just use
1895 * this call. If we haven't been able to find an optimal
1896 * choice, and we're at the end of the list, then use a
1897 * 2d choice if one has been identified. Otherwise... */
1898 call = (choice2 ? choice2 : tcall);
1899 service = call->conn->service;
1901 MUTEX_EXIT(&rx_pthread_mutex);
1902 if (!queue_IsEmpty(&tcall->rq)) {
1903 struct rx_packet *rp;
1904 rp = queue_First(&tcall->rq, rx_packet);
1905 if (rp->header.seq == 1
1907 || (rp->header.flags & RX_LAST_PACKET))) {
1909 } else if (rxi_2dchoice && !choice2
1910 && !(tcall->flags & RX_CALL_CLEARED)
1911 && (tcall->rprev > rxi_HardAckRate)) {
1925 /* we can't schedule a call if there's no data!!! */
1926 /* send an ack if there's no data, if we're missing the
1927 * first packet, or we're missing something between first
1928 * and last -- there's a "hole" in the incoming data. */
1929 if (queue_IsEmpty(&call->rq)
1930 || queue_First(&call->rq, rx_packet)->header.seq != 1
1931 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1932 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1934 call->flags &= (~RX_CALL_WAIT_PROC);
1935 service->nRequestsRunning++;
1936 /* just started call in minProcs pool, need fewer to maintain
1938 MUTEX_ENTER(&rx_quota_mutex);
1939 if (service->nRequestsRunning <= service->minProcs)
1942 MUTEX_EXIT(&rx_quota_mutex);
1943 rx_atomic_dec(&rx_nWaiting);
1944 /* MUTEX_EXIT(&call->lock); */
1946 /* If there are no eligible incoming calls, add this process
1947 * to the idle server queue, to wait for one */
1950 *socketp = OSI_NULLSOCKET;
1952 sq->socketp = socketp;
1953 queue_Append(&rx_idleServerQueue, sq);
1957 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1959 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
1960 return (struct rx_call *)0;
1963 } while (!(call = sq->newcall)
1964 && !(socketp && *socketp != OSI_NULLSOCKET));
1966 MUTEX_EXIT(&sq->lock);
1968 MUTEX_ENTER(&freeSQEList_lock);
1969 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1970 rx_FreeSQEList = sq;
1971 MUTEX_EXIT(&freeSQEList_lock);
1974 clock_GetTime(&call->startTime);
1975 call->state = RX_STATE_ACTIVE;
1976 call->mode = RX_MODE_RECEIVING;
1977 #ifdef RX_KERNEL_TRACE
1978 if (ICL_SETACTIVE(afs_iclSetp)) {
1979 int glockOwner = ISAFS_GLOCK();
1982 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1983 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1990 rxi_calltrace(RX_CALL_START, call);
1991 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
1992 call->conn->service->servicePort, call->conn->service->serviceId,
1995 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2002 #endif /* RX_ENABLE_LOCKS */
2006 /* Establish a procedure to be called when a packet arrives for a
2007 * call. This routine will be called at most once after each call,
2008 * and will also be called if there is an error condition on the or
2009 * the call is complete. Used by multi rx to build a selection
2010 * function which determines which of several calls is likely to be a
2011 * good one to read from.
2012 * NOTE: the way this is currently implemented it is probably only a
2013 * good idea to (1) use it immediately after a newcall (clients only)
2014 * and (2) only use it once. Other uses currently void your warranty
2017 rx_SetArrivalProc(struct rx_call *call,
2018 void (*proc) (struct rx_call * call,
2021 void * handle, int arg)
2023 call->arrivalProc = proc;
2024 call->arrivalProcHandle = handle;
2025 call->arrivalProcArg = arg;
2028 /* Call is finished (possibly prematurely). Return rc to the peer, if
2029 * appropriate, and return the final error code from the conversation
2033 rx_EndCall(struct rx_call *call, afs_int32 rc)
2035 struct rx_connection *conn = call->conn;
2039 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2040 call, rc, call->error, call->abortCode));
2043 MUTEX_ENTER(&call->lock);
2045 if (rc == 0 && call->error == 0) {
2046 call->abortCode = 0;
2047 call->abortCount = 0;
2050 call->arrivalProc = (void (*)())0;
2051 if (rc && call->error == 0) {
2052 rxi_CallError(call, rc);
2053 /* Send an abort message to the peer if this error code has
2054 * only just been set. If it was set previously, assume the
2055 * peer has already been sent the error code or will request it
2057 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2059 if (conn->type == RX_SERVER_CONNECTION) {
2060 /* Make sure reply or at least dummy reply is sent */
2061 if (call->mode == RX_MODE_RECEIVING) {
2062 rxi_WriteProc(call, 0, 0);
2064 if (call->mode == RX_MODE_SENDING) {
2065 rxi_FlushWrite(call);
2067 rxi_calltrace(RX_CALL_END, call);
2068 /* Call goes to hold state until reply packets are acknowledged */
2069 if (call->tfirst + call->nSoftAcked < call->tnext) {
2070 call->state = RX_STATE_HOLD;
2072 call->state = RX_STATE_DALLY;
2073 rxi_ClearTransmitQueue(call, 0);
2074 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2075 rxevent_Cancel(call->keepAliveEvent, call,
2076 RX_CALL_REFCOUNT_ALIVE);
2078 } else { /* Client connection */
2080 /* Make sure server receives input packets, in the case where
2081 * no reply arguments are expected */
2082 if ((call->mode == RX_MODE_SENDING)
2083 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2084 (void)rxi_ReadProc(call, &dummy, 1);
2087 /* If we had an outstanding delayed ack, be nice to the server
2088 * and force-send it now.
2090 if (call->delayedAckEvent) {
2091 rxevent_Cancel(call->delayedAckEvent, call,
2092 RX_CALL_REFCOUNT_DELAY);
2093 call->delayedAckEvent = NULL;
2094 rxi_SendDelayedAck(NULL, call, NULL);
2097 /* We need to release the call lock since it's lower than the
2098 * conn_call_lock and we don't want to hold the conn_call_lock
2099 * over the rx_ReadProc call. The conn_call_lock needs to be held
2100 * here for the case where rx_NewCall is perusing the calls on
2101 * the connection structure. We don't want to signal until
2102 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2103 * have checked this call, found it active and by the time it
2104 * goes to sleep, will have missed the signal.
2106 MUTEX_EXIT(&call->lock);
2107 MUTEX_ENTER(&conn->conn_call_lock);
2108 MUTEX_ENTER(&call->lock);
2109 MUTEX_ENTER(&conn->conn_data_lock);
2110 conn->flags |= RX_CONN_BUSY;
2111 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2112 MUTEX_EXIT(&conn->conn_data_lock);
2113 #ifdef RX_ENABLE_LOCKS
2114 CV_BROADCAST(&conn->conn_call_cv);
2119 #ifdef RX_ENABLE_LOCKS
2121 MUTEX_EXIT(&conn->conn_data_lock);
2123 #endif /* RX_ENABLE_LOCKS */
2124 call->state = RX_STATE_DALLY;
2126 error = call->error;
2128 /* currentPacket, nLeft, and NFree must be zeroed here, because
2129 * ResetCall cannot: ResetCall may be called at splnet(), in the
2130 * kernel version, and may interrupt the macros rx_Read or
2131 * rx_Write, which run at normal priority for efficiency. */
2132 if (call->currentPacket) {
2133 #ifdef RX_TRACK_PACKETS
2134 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2136 rxi_FreePacket(call->currentPacket);
2137 call->currentPacket = (struct rx_packet *)0;
2140 call->nLeft = call->nFree = call->curlen = 0;
2142 /* Free any packets from the last call to ReadvProc/WritevProc */
2143 #ifdef RXDEBUG_PACKET
2145 #endif /* RXDEBUG_PACKET */
2146 rxi_FreePackets(0, &call->iovq);
2148 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2149 MUTEX_EXIT(&call->lock);
2150 if (conn->type == RX_CLIENT_CONNECTION) {
2151 MUTEX_ENTER(&conn->conn_data_lock);
2152 conn->flags &= ~RX_CONN_BUSY;
2153 MUTEX_EXIT(&conn->conn_data_lock);
2154 MUTEX_EXIT(&conn->conn_call_lock);
2158 * Map errors to the local host's errno.h format.
2160 error = ntoh_syserr_conv(error);
2164 #if !defined(KERNEL)
2166 /* Call this routine when shutting down a server or client (especially
2167 * clients). This will allow Rx to gracefully garbage collect server
2168 * connections, and reduce the number of retries that a server might
2169 * make to a dead client.
2170 * This is not quite right, since some calls may still be ongoing and
2171 * we can't lock them to destroy them. */
2175 struct rx_connection **conn_ptr, **conn_end;
2179 if (rxinit_status == 1) {
2181 return; /* Already shutdown. */
2183 rxi_DeleteCachedConnections();
2184 if (rx_connHashTable) {
2185 MUTEX_ENTER(&rx_connHashTable_lock);
2186 for (conn_ptr = &rx_connHashTable[0], conn_end =
2187 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2189 struct rx_connection *conn, *next;
2190 for (conn = *conn_ptr; conn; conn = next) {
2192 if (conn->type == RX_CLIENT_CONNECTION) {
2193 /* MUTEX_ENTER(&conn->conn_data_lock); when used in kernel */
2195 /* MUTEX_EXIT(&conn->conn_data_lock); when used in kernel */
2196 #ifdef RX_ENABLE_LOCKS
2197 rxi_DestroyConnectionNoLock(conn);
2198 #else /* RX_ENABLE_LOCKS */
2199 rxi_DestroyConnection(conn);
2200 #endif /* RX_ENABLE_LOCKS */
2204 #ifdef RX_ENABLE_LOCKS
2205 while (rx_connCleanup_list) {
2206 struct rx_connection *conn;
2207 conn = rx_connCleanup_list;
2208 rx_connCleanup_list = rx_connCleanup_list->next;
2209 MUTEX_EXIT(&rx_connHashTable_lock);
2210 rxi_CleanupConnection(conn);
2211 MUTEX_ENTER(&rx_connHashTable_lock);
2213 MUTEX_EXIT(&rx_connHashTable_lock);
2214 #endif /* RX_ENABLE_LOCKS */
2219 afs_winsockCleanup();
2227 /* if we wakeup packet waiter too often, can get in loop with two
2228 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2230 rxi_PacketsUnWait(void)
2232 if (!rx_waitingForPackets) {
2236 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2237 return; /* still over quota */
2240 rx_waitingForPackets = 0;
2241 #ifdef RX_ENABLE_LOCKS
2242 CV_BROADCAST(&rx_waitingForPackets_cv);
2244 osi_rxWakeup(&rx_waitingForPackets);
2250 /* ------------------Internal interfaces------------------------- */
2252 /* Return this process's service structure for the
2253 * specified socket and service */
2255 rxi_FindService(osi_socket socket, u_short serviceId)
2257 struct rx_service **sp;
2258 for (sp = &rx_services[0]; *sp; sp++) {
2259 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2265 #ifdef RXDEBUG_PACKET
2266 #ifdef KDUMP_RX_LOCK
2267 static struct rx_call_rx_lock *rx_allCallsp = 0;
2269 static struct rx_call *rx_allCallsp = 0;
2271 #endif /* RXDEBUG_PACKET */
2273 /* Allocate a call structure, for the indicated channel of the
2274 * supplied connection. The mode and state of the call must be set by
2275 * the caller. Returns the call with mutex locked. */
2277 rxi_NewCall(struct rx_connection *conn, int channel)
2279 struct rx_call *call;
2280 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2281 struct rx_call *cp; /* Call pointer temp */
2282 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2283 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2285 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2287 /* Grab an existing call structure, or allocate a new one.
2288 * Existing call structures are assumed to have been left reset by
2290 MUTEX_ENTER(&rx_freeCallQueue_lock);
2292 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2294 * EXCEPT that the TQ might not yet be cleared out.
2295 * Skip over those with in-use TQs.
2298 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2299 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2305 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2306 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2307 call = queue_First(&rx_freeCallQueue, rx_call);
2308 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2310 if (rx_stats_active)
2311 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2312 MUTEX_EXIT(&rx_freeCallQueue_lock);
2313 MUTEX_ENTER(&call->lock);
2314 CLEAR_CALL_QUEUE_LOCK(call);
2315 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2316 /* Now, if TQ wasn't cleared earlier, do it now. */
2317 rxi_WaitforTQBusy(call);
2318 if (call->flags & RX_CALL_TQ_CLEARME) {
2319 rxi_ClearTransmitQueue(call, 1);
2320 /*queue_Init(&call->tq);*/
2322 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2323 /* Bind the call to its connection structure */
2325 rxi_ResetCall(call, 1);
2328 call = rxi_Alloc(sizeof(struct rx_call));
2329 #ifdef RXDEBUG_PACKET
2330 call->allNextp = rx_allCallsp;
2331 rx_allCallsp = call;
2333 #endif /* RXDEBUG_PACKET */
2334 if (rx_stats_active)
2335 rx_atomic_inc(&rx_stats.nCallStructs);
2337 MUTEX_EXIT(&rx_freeCallQueue_lock);
2338 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2339 MUTEX_ENTER(&call->lock);
2340 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2341 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2342 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2344 /* Initialize once-only items */
2345 queue_Init(&call->tq);
2346 queue_Init(&call->rq);
2347 queue_Init(&call->iovq);
2348 #ifdef RXDEBUG_PACKET
2349 call->rqc = call->tqc = call->iovqc = 0;
2350 #endif /* RXDEBUG_PACKET */
2351 /* Bind the call to its connection structure (prereq for reset) */
2353 rxi_ResetCall(call, 1);
2355 call->channel = channel;
2356 call->callNumber = &conn->callNumber[channel];
2357 call->rwind = conn->rwind[channel];
2358 call->twind = conn->twind[channel];
2359 /* Note that the next expected call number is retained (in
2360 * conn->callNumber[i]), even if we reallocate the call structure
2362 conn->call[channel] = call;
2363 /* if the channel's never been used (== 0), we should start at 1, otherwise
2364 * the call number is valid from the last time this channel was used */
2365 if (*call->callNumber == 0)
2366 *call->callNumber = 1;
2371 /* A call has been inactive long enough that so we can throw away
2372 * state, including the call structure, which is placed on the call
2374 * Call is locked upon entry.
2375 * haveCTLock set if called from rxi_ReapConnections
2378 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2380 int channel = call->channel;
2381 struct rx_connection *conn = call->conn;
2384 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2385 (*call->callNumber)++;
2386 rxi_ResetCall(call, 0);
2387 call->conn->call[channel] = (struct rx_call *)0;
2389 MUTEX_ENTER(&rx_freeCallQueue_lock);
2390 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2391 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2392 /* A call may be free even though its transmit queue is still in use.
2393 * Since we search the call list from head to tail, put busy calls at
2394 * the head of the list, and idle calls at the tail.
2396 if (call->flags & RX_CALL_TQ_BUSY)
2397 queue_Prepend(&rx_freeCallQueue, call);
2399 queue_Append(&rx_freeCallQueue, call);
2400 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2401 queue_Append(&rx_freeCallQueue, call);
2402 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2403 if (rx_stats_active)
2404 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2405 MUTEX_EXIT(&rx_freeCallQueue_lock);
2407 /* Destroy the connection if it was previously slated for
2408 * destruction, i.e. the Rx client code previously called
2409 * rx_DestroyConnection (client connections), or
2410 * rxi_ReapConnections called the same routine (server
2411 * connections). Only do this, however, if there are no
2412 * outstanding calls. Note that for fine grain locking, there appears
2413 * to be a deadlock in that rxi_FreeCall has a call locked and
2414 * DestroyConnectionNoLock locks each call in the conn. But note a
2415 * few lines up where we have removed this call from the conn.
2416 * If someone else destroys a connection, they either have no
2417 * call lock held or are going through this section of code.
2419 MUTEX_ENTER(&conn->conn_data_lock);
2420 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2422 MUTEX_EXIT(&conn->conn_data_lock);
2423 #ifdef RX_ENABLE_LOCKS
2425 rxi_DestroyConnectionNoLock(conn);
2427 rxi_DestroyConnection(conn);
2428 #else /* RX_ENABLE_LOCKS */
2429 rxi_DestroyConnection(conn);
2430 #endif /* RX_ENABLE_LOCKS */
2432 MUTEX_EXIT(&conn->conn_data_lock);
2436 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2437 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2440 rxi_Alloc(size_t size)
2444 if (rx_stats_active) {
2445 rx_atomic_add(&rxi_Allocsize, (int) size);
2446 rx_atomic_inc(&rxi_Alloccnt);
2450 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2451 afs_osi_Alloc_NoSleep(size);
2456 osi_Panic("rxi_Alloc error");
2462 rxi_Free(void *addr, size_t size)
2464 if (rx_stats_active) {
2465 rx_atomic_sub(&rxi_Allocsize, (int) size);
2466 rx_atomic_dec(&rxi_Alloccnt);
2468 osi_Free(addr, size);
2472 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2474 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2475 struct rx_peer *next = NULL;
2479 MUTEX_ENTER(&rx_peerHashTable_lock);
2481 peer_ptr = &rx_peerHashTable[0];
2482 peer_end = &rx_peerHashTable[rx_hashTableSize];
2485 for ( ; peer_ptr < peer_end; peer_ptr++) {
2488 for ( ; peer; peer = next) {
2490 if (host == peer->host)
2495 hashIndex = PEER_HASH(host, port);
2496 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2497 if ((peer->host == host) && (peer->port == port))
2502 MUTEX_ENTER(&rx_peerHashTable_lock);
2507 MUTEX_EXIT(&rx_peerHashTable_lock);
2509 MUTEX_ENTER(&peer->peer_lock);
2510 /* We don't handle dropping below min, so don't */
2511 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2512 peer->ifMTU=MIN(mtu, peer->ifMTU);
2513 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2514 /* if we tweaked this down, need to tune our peer MTU too */
2515 peer->MTU = MIN(peer->MTU, peer->natMTU);
2516 /* if we discovered a sub-1500 mtu, degrade */
2517 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2518 peer->maxDgramPackets = 1;
2519 /* We no longer have valid peer packet information */
2520 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2521 peer->maxPacketSize = 0;
2522 MUTEX_EXIT(&peer->peer_lock);
2524 MUTEX_ENTER(&rx_peerHashTable_lock);
2526 if (host && !port) {
2528 /* pick up where we left off */
2532 MUTEX_EXIT(&rx_peerHashTable_lock);
2535 /* Find the peer process represented by the supplied (host,port)
2536 * combination. If there is no appropriate active peer structure, a
2537 * new one will be allocated and initialized
2538 * The origPeer, if set, is a pointer to a peer structure on which the
2539 * refcount will be be decremented. This is used to replace the peer
2540 * structure hanging off a connection structure */
2542 rxi_FindPeer(afs_uint32 host, u_short port,
2543 struct rx_peer *origPeer, int create)
2547 hashIndex = PEER_HASH(host, port);
2548 MUTEX_ENTER(&rx_peerHashTable_lock);
2549 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2550 if ((pp->host == host) && (pp->port == port))
2555 pp = rxi_AllocPeer(); /* This bzero's *pp */
2556 pp->host = host; /* set here or in InitPeerParams is zero */
2558 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2559 queue_Init(&pp->congestionQueue);
2560 queue_Init(&pp->rpcStats);
2561 pp->next = rx_peerHashTable[hashIndex];
2562 rx_peerHashTable[hashIndex] = pp;
2563 rxi_InitPeerParams(pp);
2564 if (rx_stats_active)
2565 rx_atomic_inc(&rx_stats.nPeerStructs);
2572 origPeer->refCount--;
2573 MUTEX_EXIT(&rx_peerHashTable_lock);
2578 /* Find the connection at (host, port) started at epoch, and with the
2579 * given connection id. Creates the server connection if necessary.
2580 * The type specifies whether a client connection or a server
2581 * connection is desired. In both cases, (host, port) specify the
2582 * peer's (host, pair) pair. Client connections are not made
2583 * automatically by this routine. The parameter socket gives the
2584 * socket descriptor on which the packet was received. This is used,
2585 * in the case of server connections, to check that *new* connections
2586 * come via a valid (port, serviceId). Finally, the securityIndex
2587 * parameter must match the existing index for the connection. If a
2588 * server connection is created, it will be created using the supplied
2589 * index, if the index is valid for this service */
2590 struct rx_connection *
2591 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2592 u_short port, u_short serviceId, afs_uint32 cid,
2593 afs_uint32 epoch, int type, u_int securityIndex)
2595 int hashindex, flag, i;
2596 struct rx_connection *conn;
2597 hashindex = CONN_HASH(host, port, cid, epoch, type);
2598 MUTEX_ENTER(&rx_connHashTable_lock);
2599 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2600 rx_connHashTable[hashindex],
2603 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2604 && (epoch == conn->epoch)) {
2605 struct rx_peer *pp = conn->peer;
2606 if (securityIndex != conn->securityIndex) {
2607 /* this isn't supposed to happen, but someone could forge a packet
2608 * like this, and there seems to be some CM bug that makes this
2609 * happen from time to time -- in which case, the fileserver
2611 MUTEX_EXIT(&rx_connHashTable_lock);
2612 return (struct rx_connection *)0;
2614 if (pp->host == host && pp->port == port)
2616 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2618 /* So what happens when it's a callback connection? */
2619 if ( /*type == RX_CLIENT_CONNECTION && */
2620 (conn->epoch & 0x80000000))
2624 /* the connection rxLastConn that was used the last time is not the
2625 ** one we are looking for now. Hence, start searching in the hash */
2627 conn = rx_connHashTable[hashindex];
2632 struct rx_service *service;
2633 if (type == RX_CLIENT_CONNECTION) {
2634 MUTEX_EXIT(&rx_connHashTable_lock);
2635 return (struct rx_connection *)0;
2637 service = rxi_FindService(socket, serviceId);
2638 if (!service || (securityIndex >= service->nSecurityObjects)
2639 || (service->securityObjects[securityIndex] == 0)) {
2640 MUTEX_EXIT(&rx_connHashTable_lock);
2641 return (struct rx_connection *)0;
2643 conn = rxi_AllocConnection(); /* This bzero's the connection */
2644 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2645 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2646 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2647 conn->next = rx_connHashTable[hashindex];
2648 rx_connHashTable[hashindex] = conn;
2649 conn->peer = rxi_FindPeer(host, port, 0, 1);
2650 conn->type = RX_SERVER_CONNECTION;
2651 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2652 conn->epoch = epoch;
2653 conn->cid = cid & RX_CIDMASK;
2654 /* conn->serial = conn->lastSerial = 0; */
2655 /* conn->timeout = 0; */
2656 conn->ackRate = RX_FAST_ACK_RATE;
2657 conn->service = service;
2658 conn->serviceId = serviceId;
2659 conn->securityIndex = securityIndex;
2660 conn->securityObject = service->securityObjects[securityIndex];
2661 conn->nSpecific = 0;
2662 conn->specific = NULL;
2663 rx_SetConnDeadTime(conn, service->connDeadTime);
2664 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2665 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2666 for (i = 0; i < RX_MAXCALLS; i++) {
2667 conn->twind[i] = rx_initSendWindow;
2668 conn->rwind[i] = rx_initReceiveWindow;
2670 /* Notify security object of the new connection */
2671 RXS_NewConnection(conn->securityObject, conn);
2672 /* XXXX Connection timeout? */
2673 if (service->newConnProc)
2674 (*service->newConnProc) (conn);
2675 if (rx_stats_active)
2676 rx_atomic_inc(&rx_stats.nServerConns);
2679 MUTEX_ENTER(&conn->conn_data_lock);
2681 MUTEX_EXIT(&conn->conn_data_lock);
2683 rxLastConn = conn; /* store this connection as the last conn used */
2684 MUTEX_EXIT(&rx_connHashTable_lock);
2688 /* There are two packet tracing routines available for testing and monitoring
2689 * Rx. One is called just after every packet is received and the other is
2690 * called just before every packet is sent. Received packets, have had their
2691 * headers decoded, and packets to be sent have not yet had their headers
2692 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2693 * containing the network address. Both can be modified. The return value, if
2694 * non-zero, indicates that the packet should be dropped. */
2696 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2697 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2699 /* A packet has been received off the interface. Np is the packet, socket is
2700 * the socket number it was received from (useful in determining which service
2701 * this packet corresponds to), and (host, port) reflect the host,port of the
2702 * sender. This call returns the packet to the caller if it is finished with
2703 * it, rather than de-allocating it, just as a small performance hack */
2706 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2707 afs_uint32 host, u_short port, int *tnop,
2708 struct rx_call **newcallp)
2710 struct rx_call *call;
2711 struct rx_connection *conn;
2713 afs_uint32 currentCallNumber;
2719 struct rx_packet *tnp;
2722 /* We don't print out the packet until now because (1) the time may not be
2723 * accurate enough until now in the lwp implementation (rx_Listener only gets
2724 * the time after the packet is read) and (2) from a protocol point of view,
2725 * this is the first time the packet has been seen */
2726 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2727 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2728 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT,
2729 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2730 np->header.epoch, np->header.cid, np->header.callNumber,
2731 np->header.seq, np->header.flags, np));
2734 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2735 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2738 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2739 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2742 /* If an input tracer function is defined, call it with the packet and
2743 * network address. Note this function may modify its arguments. */
2744 if (rx_justReceived) {
2745 struct sockaddr_in addr;
2747 addr.sin_family = AF_INET;
2748 addr.sin_port = port;
2749 addr.sin_addr.s_addr = host;
2750 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2751 addr.sin_len = sizeof(addr);
2752 #endif /* AFS_OSF_ENV */
2753 drop = (*rx_justReceived) (np, &addr);
2754 /* drop packet if return value is non-zero */
2757 port = addr.sin_port; /* in case fcn changed addr */
2758 host = addr.sin_addr.s_addr;
2762 /* If packet was not sent by the client, then *we* must be the client */
2763 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2764 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2766 /* Find the connection (or fabricate one, if we're the server & if
2767 * necessary) associated with this packet */
2769 rxi_FindConnection(socket, host, port, np->header.serviceId,
2770 np->header.cid, np->header.epoch, type,
2771 np->header.securityIndex);
2774 /* If no connection found or fabricated, just ignore the packet.
2775 * (An argument could be made for sending an abort packet for
2780 MUTEX_ENTER(&conn->conn_data_lock);
2781 if (conn->maxSerial < np->header.serial)
2782 conn->maxSerial = np->header.serial;
2783 MUTEX_EXIT(&conn->conn_data_lock);
2785 /* If the connection is in an error state, send an abort packet and ignore
2786 * the incoming packet */
2788 /* Don't respond to an abort packet--we don't want loops! */
2789 MUTEX_ENTER(&conn->conn_data_lock);
2790 if (np->header.type != RX_PACKET_TYPE_ABORT)
2791 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2793 MUTEX_EXIT(&conn->conn_data_lock);
2797 /* Check for connection-only requests (i.e. not call specific). */
2798 if (np->header.callNumber == 0) {
2799 switch (np->header.type) {
2800 case RX_PACKET_TYPE_ABORT: {
2801 /* What if the supplied error is zero? */
2802 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2803 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d", errcode));
2804 rxi_ConnectionError(conn, errcode);
2805 MUTEX_ENTER(&conn->conn_data_lock);
2807 MUTEX_EXIT(&conn->conn_data_lock);
2810 case RX_PACKET_TYPE_CHALLENGE:
2811 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2812 MUTEX_ENTER(&conn->conn_data_lock);
2814 MUTEX_EXIT(&conn->conn_data_lock);
2816 case RX_PACKET_TYPE_RESPONSE:
2817 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2818 MUTEX_ENTER(&conn->conn_data_lock);
2820 MUTEX_EXIT(&conn->conn_data_lock);
2822 case RX_PACKET_TYPE_PARAMS:
2823 case RX_PACKET_TYPE_PARAMS + 1:
2824 case RX_PACKET_TYPE_PARAMS + 2:
2825 /* ignore these packet types for now */
2826 MUTEX_ENTER(&conn->conn_data_lock);
2828 MUTEX_EXIT(&conn->conn_data_lock);
2833 /* Should not reach here, unless the peer is broken: send an
2835 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2836 MUTEX_ENTER(&conn->conn_data_lock);
2837 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2839 MUTEX_EXIT(&conn->conn_data_lock);
2844 channel = np->header.cid & RX_CHANNELMASK;
2845 call = conn->call[channel];
2846 #ifdef RX_ENABLE_LOCKS
2848 MUTEX_ENTER(&call->lock);
2849 /* Test to see if call struct is still attached to conn. */
2850 if (call != conn->call[channel]) {
2852 MUTEX_EXIT(&call->lock);
2853 if (type == RX_SERVER_CONNECTION) {
2854 call = conn->call[channel];
2855 /* If we started with no call attached and there is one now,
2856 * another thread is also running this routine and has gotten
2857 * the connection channel. We should drop this packet in the tests
2858 * below. If there was a call on this connection and it's now
2859 * gone, then we'll be making a new call below.
2860 * If there was previously a call and it's now different then
2861 * the old call was freed and another thread running this routine
2862 * has created a call on this channel. One of these two threads
2863 * has a packet for the old call and the code below handles those
2867 MUTEX_ENTER(&call->lock);
2869 /* This packet can't be for this call. If the new call address is
2870 * 0 then no call is running on this channel. If there is a call
2871 * then, since this is a client connection we're getting data for
2872 * it must be for the previous call.
2874 if (rx_stats_active)
2875 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2876 MUTEX_ENTER(&conn->conn_data_lock);
2878 MUTEX_EXIT(&conn->conn_data_lock);
2883 currentCallNumber = conn->callNumber[channel];
2885 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2886 if (np->header.callNumber < currentCallNumber) {
2887 if (rx_stats_active)
2888 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2889 #ifdef RX_ENABLE_LOCKS
2891 MUTEX_EXIT(&call->lock);
2893 MUTEX_ENTER(&conn->conn_data_lock);
2895 MUTEX_EXIT(&conn->conn_data_lock);
2899 MUTEX_ENTER(&conn->conn_call_lock);
2900 call = rxi_NewCall(conn, channel);
2901 MUTEX_EXIT(&conn->conn_call_lock);
2902 *call->callNumber = np->header.callNumber;
2904 if (np->header.callNumber == 0)
2905 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d",
2906 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2907 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2908 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2910 call->state = RX_STATE_PRECALL;
2911 clock_GetTime(&call->queueTime);
2912 hzero(call->bytesSent);
2913 hzero(call->bytesRcvd);
2915 * If the number of queued calls exceeds the overload
2916 * threshold then abort this call.
2918 if ((rx_BusyThreshold > 0) &&
2919 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
2920 struct rx_packet *tp;
2922 rxi_CallError(call, rx_BusyError);
2923 tp = rxi_SendCallAbort(call, np, 1, 0);
2924 MUTEX_EXIT(&call->lock);
2925 MUTEX_ENTER(&conn->conn_data_lock);
2927 MUTEX_EXIT(&conn->conn_data_lock);
2928 if (rx_stats_active)
2929 rx_atomic_inc(&rx_stats.nBusies);
2932 rxi_KeepAliveOn(call);
2933 } else if (np->header.callNumber != currentCallNumber) {
2934 /* Wait until the transmit queue is idle before deciding
2935 * whether to reset the current call. Chances are that the
2936 * call will be in ether DALLY or HOLD state once the TQ_BUSY
2939 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2940 while ((call->state == RX_STATE_ACTIVE)
2941 && (call->flags & RX_CALL_TQ_BUSY)) {
2942 call->flags |= RX_CALL_TQ_WAIT;
2944 #ifdef RX_ENABLE_LOCKS
2945 osirx_AssertMine(&call->lock, "rxi_Start lock3");
2946 CV_WAIT(&call->cv_tq, &call->lock);
2947 #else /* RX_ENABLE_LOCKS */
2948 osi_rxSleep(&call->tq);
2949 #endif /* RX_ENABLE_LOCKS */
2951 if (call->tqWaiters == 0)
2952 call->flags &= ~RX_CALL_TQ_WAIT;
2954 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2955 /* If the new call cannot be taken right now send a busy and set
2956 * the error condition in this call, so that it terminates as
2957 * quickly as possible */
2958 if (call->state == RX_STATE_ACTIVE) {
2959 struct rx_packet *tp;
2961 rxi_CallError(call, RX_CALL_DEAD);
2962 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
2964 MUTEX_EXIT(&call->lock);
2965 MUTEX_ENTER(&conn->conn_data_lock);
2967 MUTEX_EXIT(&conn->conn_data_lock);
2970 rxi_ResetCall(call, 0);
2971 *call->callNumber = np->header.callNumber;
2973 if (np->header.callNumber == 0)
2974 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d",
2975 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2976 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2977 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
2979 call->state = RX_STATE_PRECALL;
2980 clock_GetTime(&call->queueTime);
2981 hzero(call->bytesSent);
2982 hzero(call->bytesRcvd);
2984 * If the number of queued calls exceeds the overload
2985 * threshold then abort this call.
2987 if ((rx_BusyThreshold > 0) &&
2988 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
2989 struct rx_packet *tp;
2991 rxi_CallError(call, rx_BusyError);
2992 tp = rxi_SendCallAbort(call, np, 1, 0);
2993 MUTEX_EXIT(&call->lock);
2994 MUTEX_ENTER(&conn->conn_data_lock);
2996 MUTEX_EXIT(&conn->conn_data_lock);
2997 if (rx_stats_active)
2998 rx_atomic_inc(&rx_stats.nBusies);
3001 rxi_KeepAliveOn(call);
3003 /* Continuing call; do nothing here. */
3005 } else { /* we're the client */
3006 /* Ignore all incoming acknowledgements for calls in DALLY state */
3007 if (call && (call->state == RX_STATE_DALLY)
3008 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3009 if (rx_stats_active)
3010 rx_atomic_inc(&rx_stats.ignorePacketDally);
3011 #ifdef RX_ENABLE_LOCKS
3013 MUTEX_EXIT(&call->lock);
3016 MUTEX_ENTER(&conn->conn_data_lock);
3018 MUTEX_EXIT(&conn->conn_data_lock);
3022 /* Ignore anything that's not relevant to the current call. If there
3023 * isn't a current call, then no packet is relevant. */
3024 if (!call || (np->header.callNumber != currentCallNumber)) {
3025 if (rx_stats_active)
3026 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3027 #ifdef RX_ENABLE_LOCKS
3029 MUTEX_EXIT(&call->lock);
3032 MUTEX_ENTER(&conn->conn_data_lock);
3034 MUTEX_EXIT(&conn->conn_data_lock);
3037 /* If the service security object index stamped in the packet does not
3038 * match the connection's security index, ignore the packet */
3039 if (np->header.securityIndex != conn->securityIndex) {
3040 #ifdef RX_ENABLE_LOCKS
3041 MUTEX_EXIT(&call->lock);
3043 MUTEX_ENTER(&conn->conn_data_lock);
3045 MUTEX_EXIT(&conn->conn_data_lock);
3049 /* If we're receiving the response, then all transmit packets are
3050 * implicitly acknowledged. Get rid of them. */
3051 if (np->header.type == RX_PACKET_TYPE_DATA) {
3052 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3053 /* XXX Hack. Because we must release the global rx lock when
3054 * sending packets (osi_NetSend) we drop all acks while we're
3055 * traversing the tq in rxi_Start sending packets out because
3056 * packets may move to the freePacketQueue as result of being here!
3057 * So we drop these packets until we're safely out of the
3058 * traversing. Really ugly!
3059 * For fine grain RX locking, we set the acked field in the
3060 * packets and let rxi_Start remove them from the transmit queue.
3062 if (call->flags & RX_CALL_TQ_BUSY) {
3063 #ifdef RX_ENABLE_LOCKS
3064 rxi_SetAcksInTransmitQueue(call);
3067 return np; /* xmitting; drop packet */
3070 rxi_ClearTransmitQueue(call, 0);
3072 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3073 rxi_ClearTransmitQueue(call, 0);
3074 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3076 if (np->header.type == RX_PACKET_TYPE_ACK) {
3077 /* now check to see if this is an ack packet acknowledging that the
3078 * server actually *lost* some hard-acked data. If this happens we
3079 * ignore this packet, as it may indicate that the server restarted in
3080 * the middle of a call. It is also possible that this is an old ack
3081 * packet. We don't abort the connection in this case, because this
3082 * *might* just be an old ack packet. The right way to detect a server
3083 * restart in the midst of a call is to notice that the server epoch
3085 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3086 * XXX unacknowledged. I think that this is off-by-one, but
3087 * XXX I don't dare change it just yet, since it will
3088 * XXX interact badly with the server-restart detection
3089 * XXX code in receiveackpacket. */
3090 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3091 if (rx_stats_active)
3092 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3093 MUTEX_EXIT(&call->lock);
3094 MUTEX_ENTER(&conn->conn_data_lock);
3096 MUTEX_EXIT(&conn->conn_data_lock);
3100 } /* else not a data packet */
3103 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3104 /* Set remote user defined status from packet */
3105 call->remoteStatus = np->header.userStatus;
3107 /* Note the gap between the expected next packet and the actual
3108 * packet that arrived, when the new packet has a smaller serial number
3109 * than expected. Rioses frequently reorder packets all by themselves,
3110 * so this will be quite important with very large window sizes.
3111 * Skew is checked against 0 here to avoid any dependence on the type of
3112 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3114 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3115 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3116 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3118 MUTEX_ENTER(&conn->conn_data_lock);
3119 skew = conn->lastSerial - np->header.serial;
3120 conn->lastSerial = np->header.serial;
3121 MUTEX_EXIT(&conn->conn_data_lock);
3123 struct rx_peer *peer;
3125 if (skew > peer->inPacketSkew) {
3126 dpf(("*** In skew changed from %d to %d\n",
3127 peer->inPacketSkew, skew));
3128 peer->inPacketSkew = skew;
3132 /* Now do packet type-specific processing */
3133 switch (np->header.type) {
3134 case RX_PACKET_TYPE_DATA:
3135 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3138 case RX_PACKET_TYPE_ACK:
3139 /* Respond immediately to ack packets requesting acknowledgement
3141 if (np->header.flags & RX_REQUEST_ACK) {
3143 (void)rxi_SendCallAbort(call, 0, 1, 0);
3145 (void)rxi_SendAck(call, 0, np->header.serial,
3146 RX_ACK_PING_RESPONSE, 1);
3148 np = rxi_ReceiveAckPacket(call, np, 1);
3150 case RX_PACKET_TYPE_ABORT: {
3151 /* An abort packet: reset the call, passing the error up to the user. */
3152 /* What if error is zero? */
3153 /* What if the error is -1? the application will treat it as a timeout. */
3154 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3155 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d", errdata));
3156 rxi_CallError(call, errdata);
3157 MUTEX_EXIT(&call->lock);
3158 MUTEX_ENTER(&conn->conn_data_lock);
3160 MUTEX_EXIT(&conn->conn_data_lock);
3161 return np; /* xmitting; drop packet */
3163 case RX_PACKET_TYPE_BUSY:
3166 case RX_PACKET_TYPE_ACKALL:
3167 /* All packets acknowledged, so we can drop all packets previously
3168 * readied for sending */
3169 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3170 /* XXX Hack. We because we can't release the global rx lock when
3171 * sending packets (osi_NetSend) we drop all ack pkts while we're
3172 * traversing the tq in rxi_Start sending packets out because
3173 * packets may move to the freePacketQueue as result of being
3174 * here! So we drop these packets until we're safely out of the
3175 * traversing. Really ugly!
3176 * For fine grain RX locking, we set the acked field in the packets
3177 * and let rxi_Start remove the packets from the transmit queue.
3179 if (call->flags & RX_CALL_TQ_BUSY) {
3180 #ifdef RX_ENABLE_LOCKS
3181 rxi_SetAcksInTransmitQueue(call);
3183 #else /* RX_ENABLE_LOCKS */
3184 MUTEX_EXIT(&call->lock);
3185 MUTEX_ENTER(&conn->conn_data_lock);
3187 MUTEX_EXIT(&conn->conn_data_lock);
3188 return np; /* xmitting; drop packet */
3189 #endif /* RX_ENABLE_LOCKS */
3191 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3192 rxi_ClearTransmitQueue(call, 0);
3193 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3196 /* Should not reach here, unless the peer is broken: send an abort
3198 rxi_CallError(call, RX_PROTOCOL_ERROR);
3199 np = rxi_SendCallAbort(call, np, 1, 0);
3202 /* Note when this last legitimate packet was received, for keep-alive
3203 * processing. Note, we delay getting the time until now in the hope that
3204 * the packet will be delivered to the user before any get time is required
3205 * (if not, then the time won't actually be re-evaluated here). */
3206 call->lastReceiveTime = clock_Sec();
3207 MUTEX_EXIT(&call->lock);
3208 MUTEX_ENTER(&conn->conn_data_lock);
3210 MUTEX_EXIT(&conn->conn_data_lock);
3214 /* return true if this is an "interesting" connection from the point of view
3215 of someone trying to debug the system */
3217 rxi_IsConnInteresting(struct rx_connection *aconn)
3220 struct rx_call *tcall;
3222 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3225 for (i = 0; i < RX_MAXCALLS; i++) {
3226 tcall = aconn->call[i];
3228 if ((tcall->state == RX_STATE_PRECALL)
3229 || (tcall->state == RX_STATE_ACTIVE))
3231 if ((tcall->mode == RX_MODE_SENDING)
3232 || (tcall->mode == RX_MODE_RECEIVING))
3240 /* if this is one of the last few packets AND it wouldn't be used by the
3241 receiving call to immediately satisfy a read request, then drop it on
3242 the floor, since accepting it might prevent a lock-holding thread from
3243 making progress in its reading. If a call has been cleared while in
3244 the precall state then ignore all subsequent packets until the call
3245 is assigned to a thread. */
3248 TooLow(struct rx_packet *ap, struct rx_call *acall)
3252 MUTEX_ENTER(&rx_quota_mutex);
3253 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3254 && (acall->state == RX_STATE_PRECALL))
3255 || ((rx_nFreePackets < rxi_dataQuota + 2)
3256 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3257 && (acall->flags & RX_CALL_READER_WAIT)))) {
3260 MUTEX_EXIT(&rx_quota_mutex);
3266 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3268 struct rx_connection *conn = arg1;
3269 struct rx_call *acall = arg2;
3270 struct rx_call *call = acall;
3271 struct clock when, now;
3274 MUTEX_ENTER(&conn->conn_data_lock);
3275 conn->checkReachEvent = NULL;
3276 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3279 MUTEX_EXIT(&conn->conn_data_lock);
3283 MUTEX_ENTER(&conn->conn_call_lock);
3284 MUTEX_ENTER(&conn->conn_data_lock);
3285 for (i = 0; i < RX_MAXCALLS; i++) {
3286 struct rx_call *tc = conn->call[i];
3287 if (tc && tc->state == RX_STATE_PRECALL) {
3293 /* Indicate that rxi_CheckReachEvent is no longer running by
3294 * clearing the flag. Must be atomic under conn_data_lock to
3295 * avoid a new call slipping by: rxi_CheckConnReach holds
3296 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3298 conn->flags &= ~RX_CONN_ATTACHWAIT;
3299 MUTEX_EXIT(&conn->conn_data_lock);
3300 MUTEX_EXIT(&conn->conn_call_lock);
3305 MUTEX_ENTER(&call->lock);
3306 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3308 MUTEX_EXIT(&call->lock);
3310 clock_GetTime(&now);
3312 when.sec += RX_CHECKREACH_TIMEOUT;
3313 MUTEX_ENTER(&conn->conn_data_lock);
3314 if (!conn->checkReachEvent) {
3316 conn->checkReachEvent =
3317 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3320 MUTEX_EXIT(&conn->conn_data_lock);
3326 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3328 struct rx_service *service = conn->service;
3329 struct rx_peer *peer = conn->peer;
3330 afs_uint32 now, lastReach;
3332 if (service->checkReach == 0)
3336 MUTEX_ENTER(&peer->peer_lock);
3337 lastReach = peer->lastReachTime;
3338 MUTEX_EXIT(&peer->peer_lock);
3339 if (now - lastReach < RX_CHECKREACH_TTL)
3342 MUTEX_ENTER(&conn->conn_data_lock);
3343 if (conn->flags & RX_CONN_ATTACHWAIT) {
3344 MUTEX_EXIT(&conn->conn_data_lock);
3347 conn->flags |= RX_CONN_ATTACHWAIT;
3348 MUTEX_EXIT(&conn->conn_data_lock);
3349 if (!conn->checkReachEvent)
3350 rxi_CheckReachEvent(NULL, conn, call);
3355 /* try to attach call, if authentication is complete */
3357 TryAttach(struct rx_call *acall, osi_socket socket,
3358 int *tnop, struct rx_call **newcallp,
3361 struct rx_connection *conn = acall->conn;
3363 if (conn->type == RX_SERVER_CONNECTION
3364 && acall->state == RX_STATE_PRECALL) {
3365 /* Don't attach until we have any req'd. authentication. */
3366 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3367 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3368 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3369 /* Note: this does not necessarily succeed; there
3370 * may not any proc available
3373 rxi_ChallengeOn(acall->conn);
3378 /* A data packet has been received off the interface. This packet is
3379 * appropriate to the call (the call is in the right state, etc.). This
3380 * routine can return a packet to the caller, for re-use */
3383 rxi_ReceiveDataPacket(struct rx_call *call,
3384 struct rx_packet *np, int istack,
3385 osi_socket socket, afs_uint32 host, u_short port,
3386 int *tnop, struct rx_call **newcallp)
3388 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3393 afs_uint32 serial=0, flags=0;
3395 struct rx_packet *tnp;
3396 struct clock when, now;
3397 if (rx_stats_active)
3398 rx_atomic_inc(&rx_stats.dataPacketsRead);
3401 /* If there are no packet buffers, drop this new packet, unless we can find
3402 * packet buffers from inactive calls */
3404 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3405 MUTEX_ENTER(&rx_freePktQ_lock);
3406 rxi_NeedMorePackets = TRUE;
3407 MUTEX_EXIT(&rx_freePktQ_lock);
3408 if (rx_stats_active)
3409 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3410 call->rprev = np->header.serial;
3411 rxi_calltrace(RX_TRACE_DROP, call);
3412 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems", np));
3414 rxi_ClearReceiveQueue(call);
3415 clock_GetTime(&now);
3417 clock_Add(&when, &rx_softAckDelay);
3418 if (!call->delayedAckEvent
3419 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3420 rxevent_Cancel(call->delayedAckEvent, call,
3421 RX_CALL_REFCOUNT_DELAY);
3422 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3423 call->delayedAckEvent =
3424 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3426 /* we've damaged this call already, might as well do it in. */
3432 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3433 * packet is one of several packets transmitted as a single
3434 * datagram. Do not send any soft or hard acks until all packets
3435 * in a jumbogram have been processed. Send negative acks right away.
3437 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3438 /* tnp is non-null when there are more packets in the
3439 * current jumbo gram */
3446 seq = np->header.seq;
3447 serial = np->header.serial;
3448 flags = np->header.flags;
3450 /* If the call is in an error state, send an abort message */
3452 return rxi_SendCallAbort(call, np, istack, 0);
3454 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3455 * AFS 3.5 jumbogram. */
3456 if (flags & RX_JUMBO_PACKET) {
3457 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3462 if (np->header.spare != 0) {
3463 MUTEX_ENTER(&call->conn->conn_data_lock);
3464 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3465 MUTEX_EXIT(&call->conn->conn_data_lock);
3468 /* The usual case is that this is the expected next packet */
3469 if (seq == call->rnext) {
3471 /* Check to make sure it is not a duplicate of one already queued */
3472 if (queue_IsNotEmpty(&call->rq)
3473 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3474 if (rx_stats_active)
3475 rx_atomic_inc(&rx_stats.dupPacketsRead);
3476 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate", np));
3477 rxevent_Cancel(call->delayedAckEvent, call,
3478 RX_CALL_REFCOUNT_DELAY);
3479 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3485 /* It's the next packet. Stick it on the receive queue
3486 * for this call. Set newPackets to make sure we wake
3487 * the reader once all packets have been processed */
3488 #ifdef RX_TRACK_PACKETS
3489 np->flags |= RX_PKTFLAG_RQ;
3491 queue_Prepend(&call->rq, np);
3492 #ifdef RXDEBUG_PACKET
3494 #endif /* RXDEBUG_PACKET */
3496 np = NULL; /* We can't use this anymore */
3499 /* If an ack is requested then set a flag to make sure we
3500 * send an acknowledgement for this packet */
3501 if (flags & RX_REQUEST_ACK) {
3502 ackNeeded = RX_ACK_REQUESTED;
3505 /* Keep track of whether we have received the last packet */
3506 if (flags & RX_LAST_PACKET) {
3507 call->flags |= RX_CALL_HAVE_LAST;
3511 /* Check whether we have all of the packets for this call */
3512 if (call->flags & RX_CALL_HAVE_LAST) {
3513 afs_uint32 tseq; /* temporary sequence number */
3514 struct rx_packet *tp; /* Temporary packet pointer */
3515 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3517 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3518 if (tseq != tp->header.seq)
3520 if (tp->header.flags & RX_LAST_PACKET) {
3521 call->flags |= RX_CALL_RECEIVE_DONE;
3528 /* Provide asynchronous notification for those who want it
3529 * (e.g. multi rx) */
3530 if (call->arrivalProc) {
3531 (*call->arrivalProc) (call, call->arrivalProcHandle,
3532 call->arrivalProcArg);
3533 call->arrivalProc = (void (*)())0;
3536 /* Update last packet received */
3539 /* If there is no server process serving this call, grab
3540 * one, if available. We only need to do this once. If a
3541 * server thread is available, this thread becomes a server
3542 * thread and the server thread becomes a listener thread. */
3544 TryAttach(call, socket, tnop, newcallp, 0);
3547 /* This is not the expected next packet. */
3549 /* Determine whether this is a new or old packet, and if it's
3550 * a new one, whether it fits into the current receive window.
3551 * Also figure out whether the packet was delivered in sequence.
3552 * We use the prev variable to determine whether the new packet
3553 * is the successor of its immediate predecessor in the
3554 * receive queue, and the missing flag to determine whether
3555 * any of this packets predecessors are missing. */
3557 afs_uint32 prev; /* "Previous packet" sequence number */
3558 struct rx_packet *tp; /* Temporary packet pointer */
3559 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3560 int missing; /* Are any predecessors missing? */
3562 /* If the new packet's sequence number has been sent to the
3563 * application already, then this is a duplicate */
3564 if (seq < call->rnext) {
3565 if (rx_stats_active)
3566 rx_atomic_inc(&rx_stats.dupPacketsRead);
3567 rxevent_Cancel(call->delayedAckEvent, call,
3568 RX_CALL_REFCOUNT_DELAY);
3569 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3575 /* If the sequence number is greater than what can be
3576 * accomodated by the current window, then send a negative
3577 * acknowledge and drop the packet */
3578 if ((call->rnext + call->rwind) <= seq) {
3579 rxevent_Cancel(call->delayedAckEvent, call,
3580 RX_CALL_REFCOUNT_DELAY);
3581 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3588 /* Look for the packet in the queue of old received packets */
3589 for (prev = call->rnext - 1, missing =
3590 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3591 /*Check for duplicate packet */
3592 if (seq == tp->header.seq) {
3593 if (rx_stats_active)
3594 rx_atomic_inc(&rx_stats.dupPacketsRead);
3595 rxevent_Cancel(call->delayedAckEvent, call,
3596 RX_CALL_REFCOUNT_DELAY);
3597 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3603 /* If we find a higher sequence packet, break out and
3604 * insert the new packet here. */
3605 if (seq < tp->header.seq)
3607 /* Check for missing packet */
3608 if (tp->header.seq != prev + 1) {
3612 prev = tp->header.seq;
3615 /* Keep track of whether we have received the last packet. */
3616 if (flags & RX_LAST_PACKET) {
3617 call->flags |= RX_CALL_HAVE_LAST;
3620 /* It's within the window: add it to the the receive queue.
3621 * tp is left by the previous loop either pointing at the
3622 * packet before which to insert the new packet, or at the
3623 * queue head if the queue is empty or the packet should be
3625 #ifdef RX_TRACK_PACKETS
3626 np->flags |= RX_PKTFLAG_RQ;
3628 #ifdef RXDEBUG_PACKET
3630 #endif /* RXDEBUG_PACKET */
3631 queue_InsertBefore(tp, np);
3635 /* Check whether we have all of the packets for this call */
3636 if ((call->flags & RX_CALL_HAVE_LAST)
3637 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3638 afs_uint32 tseq; /* temporary sequence number */
3641 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3642 if (tseq != tp->header.seq)
3644 if (tp->header.flags & RX_LAST_PACKET) {
3645 call->flags |= RX_CALL_RECEIVE_DONE;
3652 /* We need to send an ack of the packet is out of sequence,
3653 * or if an ack was requested by the peer. */
3654 if (seq != prev + 1 || missing) {
3655 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3656 } else if (flags & RX_REQUEST_ACK) {
3657 ackNeeded = RX_ACK_REQUESTED;
3660 /* Acknowledge the last packet for each call */
3661 if (flags & RX_LAST_PACKET) {
3672 * If the receiver is waiting for an iovec, fill the iovec
3673 * using the data from the receive queue */
3674 if (call->flags & RX_CALL_IOVEC_WAIT) {
3675 didHardAck = rxi_FillReadVec(call, serial);
3676 /* the call may have been aborted */
3685 /* Wakeup the reader if any */
3686 if ((call->flags & RX_CALL_READER_WAIT)
3687 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3688 || (call->iovNext >= call->iovMax)
3689 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3690 call->flags &= ~RX_CALL_READER_WAIT;
3691 #ifdef RX_ENABLE_LOCKS
3692 CV_BROADCAST(&call->cv_rq);
3694 osi_rxWakeup(&call->rq);
3700 * Send an ack when requested by the peer, or once every
3701 * rxi_SoftAckRate packets until the last packet has been
3702 * received. Always send a soft ack for the last packet in
3703 * the server's reply. */
3705 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3706 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3707 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3708 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3709 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3710 } else if (call->nSoftAcks) {
3711 clock_GetTime(&now);
3713 if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3714 clock_Add(&when, &rx_lastAckDelay);
3716 clock_Add(&when, &rx_softAckDelay);
3718 if (!call->delayedAckEvent
3719 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3720 rxevent_Cancel(call->delayedAckEvent, call,
3721 RX_CALL_REFCOUNT_DELAY);
3722 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3723 call->delayedAckEvent =
3724 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3726 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
3727 rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3734 static void rxi_ComputeRate();
3738 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3740 struct rx_peer *peer = conn->peer;
3742 MUTEX_ENTER(&peer->peer_lock);
3743 peer->lastReachTime = clock_Sec();
3744 MUTEX_EXIT(&peer->peer_lock);
3746 MUTEX_ENTER(&conn->conn_data_lock);
3747 if (conn->flags & RX_CONN_ATTACHWAIT) {
3750 conn->flags &= ~RX_CONN_ATTACHWAIT;
3751 MUTEX_EXIT(&conn->conn_data_lock);
3753 for (i = 0; i < RX_MAXCALLS; i++) {
3754 struct rx_call *call = conn->call[i];
3757 MUTEX_ENTER(&call->lock);
3758 /* tnop can be null if newcallp is null */
3759 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
3761 MUTEX_EXIT(&call->lock);
3765 MUTEX_EXIT(&conn->conn_data_lock);
3768 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
3770 rx_ack_reason(int reason)
3773 case RX_ACK_REQUESTED:
3775 case RX_ACK_DUPLICATE:
3777 case RX_ACK_OUT_OF_SEQUENCE:
3779 case RX_ACK_EXCEEDS_WINDOW:
3781 case RX_ACK_NOSPACE:
3785 case RX_ACK_PING_RESPONSE:
3798 /* rxi_ComputePeerNetStats
3800 * Called exclusively by rxi_ReceiveAckPacket to compute network link
3801 * estimates (like RTT and throughput) based on ack packets. Caller
3802 * must ensure that the packet in question is the right one (i.e.
3803 * serial number matches).
3806 rxi_ComputePeerNetStats(struct rx_call *call, struct rx_packet *p,
3807 struct rx_ackPacket *ap, struct rx_packet *np)
3809 struct rx_peer *peer = call->conn->peer;
3811 /* Use RTT if not delayed by client and
3812 * ignore packets that were retransmitted. */
3813 if (!(p->flags & RX_PKTFLAG_ACKED) &&
3814 ap->reason != RX_ACK_DELAY &&
3815 clock_Eq(&p->timeSent, &p->firstSent))
3816 rxi_ComputeRoundTripTime(p, &p->timeSent, peer);
3818 rxi_ComputeRate(peer, call, p, np, ap->reason);
3822 /* The real smarts of the whole thing. */
3824 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
3827 struct rx_ackPacket *ap;
3829 struct rx_packet *tp;
3830 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
3831 struct rx_connection *conn = call->conn;
3832 struct rx_peer *peer = conn->peer;
3835 /* because there are CM's that are bogus, sending weird values for this. */
3836 afs_uint32 skew = 0;
3841 int newAckCount = 0;
3842 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
3843 int pktsize = 0; /* Set if we need to update the peer mtu */
3844 int conn_data_locked = 0;
3846 if (rx_stats_active)
3847 rx_atomic_inc(&rx_stats.ackPacketsRead);
3848 ap = (struct rx_ackPacket *)rx_DataOf(np);
3849 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
3851 return np; /* truncated ack packet */
3853 /* depends on ack packet struct */
3854 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
3855 first = ntohl(ap->firstPacket);
3856 serial = ntohl(ap->serial);
3857 /* temporarily disabled -- needs to degrade over time
3858 * skew = ntohs(ap->maxSkew); */
3860 /* Ignore ack packets received out of order */
3861 if (first < call->tfirst) {
3865 if (np->header.flags & RX_SLOW_START_OK) {
3866 call->flags |= RX_CALL_SLOW_START_OK;
3869 if (ap->reason == RX_ACK_PING_RESPONSE)
3870 rxi_UpdatePeerReach(conn, call);
3872 if (conn->lastPacketSizeSeq) {
3873 MUTEX_ENTER(&conn->conn_data_lock);
3874 conn_data_locked = 1;
3875 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
3876 pktsize = conn->lastPacketSize;
3877 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
3880 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
3881 if (!conn_data_locked) {
3882 MUTEX_ENTER(&conn->conn_data_lock);
3883 conn_data_locked = 1;
3885 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
3886 /* process mtu ping ack */
3887 pktsize = conn->lastPingSize;
3888 conn->lastPingSizeSer = conn->lastPingSize = 0;
3892 if (conn_data_locked) {
3893 MUTEX_EXIT(&conn->conn_data_lock);
3894 conn_data_locked = 0;
3898 if (rxdebug_active) {
3902 len = _snprintf(msg, sizeof(msg),
3903 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
3904 GetCurrentThreadId(), rx_ack_reason(ap->reason),
3905 ntohl(ap->serial), ntohl(ap->previousPacket),
3906 (unsigned int)np->header.seq, (unsigned int)skew,
3907 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
3911 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
3912 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
3916 OutputDebugString(msg);
3918 #else /* AFS_NT40_ENV */
3921 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
3922 ap->reason, ntohl(ap->previousPacket),
3923 (unsigned int)np->header.seq, (unsigned int)serial,
3924 (unsigned int)skew, ntohl(ap->firstPacket));
3927 for (offset = 0; offset < nAcks; offset++)
3928 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
3933 #endif /* AFS_NT40_ENV */
3936 MUTEX_ENTER(&peer->peer_lock);
3939 * Start somewhere. Can't assume we can send what we can receive,
3940 * but we are clearly receiving.
3942 if (!peer->maxPacketSize)
3943 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
3945 if (pktsize > peer->maxPacketSize) {
3946 peer->maxPacketSize = pktsize;
3947 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
3948 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
3949 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
3950 rxi_ScheduleGrowMTUEvent(call, 1);
3955 /* Update the outgoing packet skew value to the latest value of
3956 * the peer's incoming packet skew value. The ack packet, of
3957 * course, could arrive out of order, but that won't affect things
3959 peer->outPacketSkew = skew;
3961 /* Check for packets that no longer need to be transmitted, and
3962 * discard them. This only applies to packets positively
3963 * acknowledged as having been sent to the peer's upper level.
3964 * All other packets must be retained. So only packets with
3965 * sequence numbers < ap->firstPacket are candidates. */
3966 for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
3967 if (tp->header.seq >= first)
3969 call->tfirst = tp->header.seq + 1;
3970 rxi_ComputePeerNetStats(call, tp, ap, np);
3971 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
3974 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3975 /* XXX Hack. Because we have to release the global rx lock when sending
3976 * packets (osi_NetSend) we drop all acks while we're traversing the tq
3977 * in rxi_Start sending packets out because packets may move to the
3978 * freePacketQueue as result of being here! So we drop these packets until
3979 * we're safely out of the traversing. Really ugly!
3980 * To make it even uglier, if we're using fine grain locking, we can
3981 * set the ack bits in the packets and have rxi_Start remove the packets
3982 * when it's done transmitting.
3984 if (call->flags & RX_CALL_TQ_BUSY) {
3985 #ifdef RX_ENABLE_LOCKS
3986 tp->flags |= RX_PKTFLAG_ACKED;
3987 call->flags |= RX_CALL_TQ_SOME_ACKED;
3988 #else /* RX_ENABLE_LOCKS */
3990 #endif /* RX_ENABLE_LOCKS */
3992 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3995 #ifdef RX_TRACK_PACKETS
3996 tp->flags &= ~RX_PKTFLAG_TQ;
3998 #ifdef RXDEBUG_PACKET
4000 #endif /* RXDEBUG_PACKET */
4001 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4006 /* Give rate detector a chance to respond to ping requests */
4007 if (ap->reason == RX_ACK_PING_RESPONSE) {
4008 rxi_ComputeRate(peer, call, 0, np, ap->reason);
4012 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4014 /* Now go through explicit acks/nacks and record the results in
4015 * the waiting packets. These are packets that can't be released
4016 * yet, even with a positive acknowledge. This positive
4017 * acknowledge only means the packet has been received by the
4018 * peer, not that it will be retained long enough to be sent to
4019 * the peer's upper level. In addition, reset the transmit timers
4020 * of any missing packets (those packets that must be missing
4021 * because this packet was out of sequence) */
4023 call->nSoftAcked = 0;
4024 for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4025 /* Update round trip time if the ack was stimulated on receipt
4027 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4028 #ifdef RX_ENABLE_LOCKS
4029 if (tp->header.seq >= first)
4030 #endif /* RX_ENABLE_LOCKS */
4031 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4032 rxi_ComputePeerNetStats(call, tp, ap, np);
4034 /* Set the acknowledge flag per packet based on the
4035 * information in the ack packet. An acknowlegded packet can
4036 * be downgraded when the server has discarded a packet it
4037 * soacked previously, or when an ack packet is received
4038 * out of sequence. */
4039 if (tp->header.seq < first) {
4040 /* Implicit ack information */
4041 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4044 tp->flags |= RX_PKTFLAG_ACKED;
4045 } else if (tp->header.seq < first + nAcks) {
4046 /* Explicit ack information: set it in the packet appropriately */
4047 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4048 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4050 tp->flags |= RX_PKTFLAG_ACKED;
4057 } else /* RX_ACK_TYPE_NACK */ {
4058 tp->flags &= ~RX_PKTFLAG_ACKED;
4062 tp->flags &= ~RX_PKTFLAG_ACKED;
4067 * Following the suggestion of Phil Kern, we back off the peer's
4068 * timeout value for future packets until a successful response
4069 * is received for an initial transmission.
4071 if (missing && !peer->backedOff) {
4072 struct clock c = peer->timeout;
4073 struct clock max_to = {3, 0};
4075 clock_Add(&peer->timeout, &c);
4076 if (clock_Gt(&peer->timeout, &max_to))
4077 peer->timeout = max_to;
4078 peer->backedOff = 1;
4081 /* If packet isn't yet acked, and it has been transmitted at least
4082 * once, reset retransmit time using latest timeout
4083 * ie, this should readjust the retransmit timer for all outstanding
4084 * packets... So we don't just retransmit when we should know better*/
4086 if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4087 tp->retryTime = tp->timeSent;
4088 clock_Add(&tp->retryTime, &peer->timeout);
4089 /* shift by eight because one quarter-sec ~ 256 milliseconds */
4090 clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4094 /* If the window has been extended by this acknowledge packet,
4095 * then wakeup a sender waiting in alloc for window space, or try
4096 * sending packets now, if he's been sitting on packets due to
4097 * lack of window space */
4098 if (call->tnext < (call->tfirst + call->twind)) {
4099 #ifdef RX_ENABLE_LOCKS
4100 CV_SIGNAL(&call->cv_twind);
4102 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4103 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4104 osi_rxWakeup(&call->twind);
4107 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4108 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4112 /* if the ack packet has a receivelen field hanging off it,
4113 * update our state */
4114 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4117 /* If the ack packet has a "recommended" size that is less than
4118 * what I am using now, reduce my size to match */
4119 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4120 (int)sizeof(afs_int32), &tSize);
4121 tSize = (afs_uint32) ntohl(tSize);
4122 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4124 /* Get the maximum packet size to send to this peer */
4125 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4127 tSize = (afs_uint32) ntohl(tSize);
4128 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4129 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4131 /* sanity check - peer might have restarted with different params.
4132 * If peer says "send less", dammit, send less... Peer should never
4133 * be unable to accept packets of the size that prior AFS versions would
4134 * send without asking. */
4135 if (peer->maxMTU != tSize) {
4136 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4138 peer->maxMTU = tSize;
4139 peer->MTU = MIN(tSize, peer->MTU);
4140 call->MTU = MIN(call->MTU, tSize);
4143 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4146 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4147 (int)sizeof(afs_int32), &tSize);
4148 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4149 if (tSize < call->twind) { /* smaller than our send */
4150 call->twind = tSize; /* window, we must send less... */
4151 call->ssthresh = MIN(call->twind, call->ssthresh);
4152 call->conn->twind[call->channel] = call->twind;
4155 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4156 * network MTU confused with the loopback MTU. Calculate the
4157 * maximum MTU here for use in the slow start code below.
4159 /* Did peer restart with older RX version? */
4160 if (peer->maxDgramPackets > 1) {
4161 peer->maxDgramPackets = 1;
4163 } else if (np->length >=
4164 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4167 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4168 sizeof(afs_int32), &tSize);
4169 tSize = (afs_uint32) ntohl(tSize);
4171 * As of AFS 3.5 we set the send window to match the receive window.
4173 if (tSize < call->twind) {
4174 call->twind = tSize;
4175 call->conn->twind[call->channel] = call->twind;
4176 call->ssthresh = MIN(call->twind, call->ssthresh);
4177 } else if (tSize > call->twind) {
4178 call->twind = tSize;
4179 call->conn->twind[call->channel] = call->twind;
4183 * As of AFS 3.5, a jumbogram is more than one fixed size
4184 * packet transmitted in a single UDP datagram. If the remote
4185 * MTU is smaller than our local MTU then never send a datagram
4186 * larger than the natural MTU.
4189 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4190 (int)sizeof(afs_int32), &tSize);
4191 maxDgramPackets = (afs_uint32) ntohl(tSize);
4192 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4194 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4195 maxDgramPackets = MIN(maxDgramPackets, tSize);
4196 if (maxDgramPackets > 1) {
4197 peer->maxDgramPackets = maxDgramPackets;
4198 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4200 peer->maxDgramPackets = 1;
4201 call->MTU = peer->natMTU;
4203 } else if (peer->maxDgramPackets > 1) {
4204 /* Restarted with lower version of RX */
4205 peer->maxDgramPackets = 1;
4207 } else if (peer->maxDgramPackets > 1
4208 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4209 /* Restarted with lower version of RX */
4210 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4211 peer->natMTU = OLD_MAX_PACKET_SIZE;
4212 peer->MTU = OLD_MAX_PACKET_SIZE;
4213 peer->maxDgramPackets = 1;
4214 peer->nDgramPackets = 1;
4216 call->MTU = OLD_MAX_PACKET_SIZE;
4221 * Calculate how many datagrams were successfully received after
4222 * the first missing packet and adjust the negative ack counter
4227 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4228 if (call->nNacks < nNacked) {
4229 call->nNacks = nNacked;
4232 call->nAcks += newAckCount;
4236 if (call->flags & RX_CALL_FAST_RECOVER) {
4238 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4240 call->flags &= ~RX_CALL_FAST_RECOVER;
4241 call->cwind = call->nextCwind;
4242 call->nextCwind = 0;
4245 call->nCwindAcks = 0;
4246 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4247 /* Three negative acks in a row trigger congestion recovery */
4248 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4249 MUTEX_EXIT(&peer->peer_lock);
4250 if (call->flags & RX_CALL_FAST_RECOVER_WAIT) {
4251 /* someone else is waiting to start recovery */
4254 call->flags |= RX_CALL_FAST_RECOVER_WAIT;
4255 rxi_WaitforTQBusy(call);
4256 MUTEX_ENTER(&peer->peer_lock);
4257 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4258 call->flags &= ~RX_CALL_FAST_RECOVER_WAIT;
4259 call->flags |= RX_CALL_FAST_RECOVER;
4260 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4262 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4263 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4264 call->nextCwind = call->ssthresh;
4267 peer->MTU = call->MTU;
4268 peer->cwind = call->nextCwind;
4269 peer->nDgramPackets = call->nDgramPackets;
4271 call->congestSeq = peer->congestSeq;
4272 /* Reset the resend times on the packets that were nacked
4273 * so we will retransmit as soon as the window permits*/
4274 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4276 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4277 clock_Zero(&tp->retryTime);
4279 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4284 /* If cwind is smaller than ssthresh, then increase
4285 * the window one packet for each ack we receive (exponential
4287 * If cwind is greater than or equal to ssthresh then increase
4288 * the congestion window by one packet for each cwind acks we
4289 * receive (linear growth). */
4290 if (call->cwind < call->ssthresh) {
4292 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4293 call->nCwindAcks = 0;
4295 call->nCwindAcks += newAckCount;
4296 if (call->nCwindAcks >= call->cwind) {
4297 call->nCwindAcks = 0;
4298 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4302 * If we have received several acknowledgements in a row then
4303 * it is time to increase the size of our datagrams
4305 if ((int)call->nAcks > rx_nDgramThreshold) {
4306 if (peer->maxDgramPackets > 1) {
4307 if (call->nDgramPackets < peer->maxDgramPackets) {
4308 call->nDgramPackets++;
4310 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4311 } else if (call->MTU < peer->maxMTU) {
4312 /* don't upgrade if we can't handle it */
4313 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4314 call->MTU = peer->ifMTU;
4316 call->MTU += peer->natMTU;
4317 call->MTU = MIN(call->MTU, peer->maxMTU);
4324 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4326 /* Servers need to hold the call until all response packets have
4327 * been acknowledged. Soft acks are good enough since clients
4328 * are not allowed to clear their receive queues. */
4329 if (call->state == RX_STATE_HOLD
4330 && call->tfirst + call->nSoftAcked >= call->tnext) {
4331 call->state = RX_STATE_DALLY;
4332 rxi_ClearTransmitQueue(call, 0);
4333 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4334 } else if (!queue_IsEmpty(&call->tq)) {
4335 rxi_Start(0, call, 0, istack);
4340 /* Received a response to a challenge packet */
4342 rxi_ReceiveResponsePacket(struct rx_connection *conn,