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>
13 #include "afs/param.h"
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
30 # include "inet/common.h"
32 # include "inet/ip_ire.h"
34 # include "afs/afs_args.h"
35 # include "afs/afs_osi.h"
36 # ifdef RX_KERNEL_TRACE
37 # include "rx_kcommon.h"
39 # if defined(AFS_AIX_ENV)
43 # undef RXDEBUG /* turn off debugging */
45 # if defined(AFS_SGI_ENV)
46 # include "sys/debug.h"
49 # include "afs/sysincludes.h"
50 # include "afsincludes.h"
51 # endif /* !UKERNEL */
52 # include "afs/lock.h"
53 # include "rx_kmutex.h"
54 # include "rx_kernel.h"
55 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
56 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
57 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
58 extern afs_int32 afs_termState;
60 # include "sys/lockl.h"
61 # include "sys/lock_def.h"
62 # endif /* AFS_AIX41_ENV */
63 # include "afs/rxgen_consts.h"
66 # include <sys/types.h>
76 # include <afs/afsutil.h>
77 # include <WINNT\afsreg.h>
79 # include <sys/socket.h>
80 # include <sys/file.h>
82 # include <sys/stat.h>
83 # include <netinet/in.h>
84 # include <sys/time.h>
92 #include "rx_atomic.h"
93 #include "rx_globals.h"
95 #include "rx_internal.h"
98 #include <afs/rxgen_consts.h>
101 #ifdef AFS_PTHREAD_ENV
103 int (*registerProgram) (pid_t, char *) = 0;
104 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
107 int (*registerProgram) (PROCESS, char *) = 0;
108 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
112 /* Local static routines */
113 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
114 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
115 struct rx_peer *, struct clock *);
117 #ifdef RX_ENABLE_LOCKS
118 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
121 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
123 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
124 rx_atomic_t rxi_start_in_error;
126 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
129 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
130 * currently allocated within rx. This number is used to allocate the
131 * memory required to return the statistics when queried.
132 * Protected by the rx_rpc_stats mutex.
135 static unsigned int rxi_rpc_peer_stat_cnt;
138 * rxi_rpc_process_stat_cnt counts the total number of local process stat
139 * structures currently allocated within rx. The number is used to allocate
140 * the memory required to return the statistics when queried.
141 * Protected by the rx_rpc_stats mutex.
144 static unsigned int rxi_rpc_process_stat_cnt;
147 * rxi_busyChannelError is the error to return to the application when a call
148 * channel appears busy (inferred from the receipt of RX_PACKET_TYPE_BUSY
149 * packets on the channel), and there are other call channels in the
150 * connection that are not busy. If 0, we do not return errors upon receiving
151 * busy packets; we just keep trying on the same call channel until we hit a
154 static afs_int32 rxi_busyChannelError = 0;
156 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
157 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
159 #if !defined(offsetof)
160 #include <stddef.h> /* for definition of offsetof() */
163 #ifdef RX_ENABLE_LOCKS
164 afs_kmutex_t rx_atomic_mutex;
167 #ifdef AFS_PTHREAD_ENV
170 * Use procedural initialization of mutexes/condition variables
174 extern afs_kmutex_t rx_quota_mutex;
175 extern afs_kmutex_t rx_pthread_mutex;
176 extern afs_kmutex_t rx_packets_mutex;
177 extern afs_kmutex_t rx_refcnt_mutex;
178 extern afs_kmutex_t des_init_mutex;
179 extern afs_kmutex_t des_random_mutex;
180 extern afs_kmutex_t rx_clock_mutex;
181 extern afs_kmutex_t rxi_connCacheMutex;
182 extern afs_kmutex_t rx_event_mutex;
183 extern afs_kmutex_t osi_malloc_mutex;
184 extern afs_kmutex_t event_handler_mutex;
185 extern afs_kmutex_t listener_mutex;
186 extern afs_kmutex_t rx_if_init_mutex;
187 extern afs_kmutex_t rx_if_mutex;
188 extern afs_kmutex_t rxkad_client_uid_mutex;
189 extern afs_kmutex_t rxkad_random_mutex;
191 extern afs_kcondvar_t rx_event_handler_cond;
192 extern afs_kcondvar_t rx_listener_cond;
194 static afs_kmutex_t epoch_mutex;
195 static afs_kmutex_t rx_init_mutex;
196 static afs_kmutex_t rx_debug_mutex;
197 static afs_kmutex_t rx_rpc_stats;
200 rxi_InitPthread(void)
202 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
216 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
217 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
220 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
222 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
223 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
225 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
226 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
228 rxkad_global_stats_init();
230 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
231 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
232 #ifdef RX_ENABLE_LOCKS
235 #endif /* RX_LOCKS_DB */
236 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
237 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
239 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
241 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
243 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
245 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
246 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
247 #endif /* RX_ENABLE_LOCKS */
250 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
251 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
253 * The rx_stats_mutex mutex protects the following global variables:
254 * rxi_lowConnRefCount
255 * rxi_lowPeerRefCount
264 * The rx_quota_mutex mutex protects the following global variables:
272 * The rx_freePktQ_lock protects the following global variables:
277 * The rx_packets_mutex mutex protects the following global variables:
285 * The rx_pthread_mutex mutex protects the following global variables:
286 * rxi_fcfs_thread_num
289 #define INIT_PTHREAD_LOCKS
293 /* Variables for handling the minProcs implementation. availProcs gives the
294 * number of threads available in the pool at this moment (not counting dudes
295 * executing right now). totalMin gives the total number of procs required
296 * for handling all minProcs requests. minDeficit is a dynamic variable
297 * tracking the # of procs required to satisfy all of the remaining minProcs
299 * For fine grain locking to work, the quota check and the reservation of
300 * a server thread has to come while rxi_availProcs and rxi_minDeficit
301 * are locked. To this end, the code has been modified under #ifdef
302 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
303 * same time. A new function, ReturnToServerPool() returns the allocation.
305 * A call can be on several queue's (but only one at a time). When
306 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
307 * that no one else is touching the queue. To this end, we store the address
308 * of the queue lock in the call structure (under the call lock) when we
309 * put the call on a queue, and we clear the call_queue_lock when the
310 * call is removed from a queue (once the call lock has been obtained).
311 * This allows rxi_ResetCall to safely synchronize with others wishing
312 * to manipulate the queue.
315 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
316 static afs_kmutex_t rx_rpc_stats;
317 void rxi_StartUnlocked(struct rxevent *event, void *call,
318 void *arg1, int istack);
321 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
322 ** pretty good that the next packet coming in is from the same connection
323 ** as the last packet, since we're send multiple packets in a transmit window.
325 struct rx_connection *rxLastConn = 0;
327 #ifdef RX_ENABLE_LOCKS
328 /* The locking hierarchy for rx fine grain locking is composed of these
331 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
332 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
333 * call->lock - locks call data fields.
334 * These are independent of each other:
335 * rx_freeCallQueue_lock
340 * serverQueueEntry->lock
341 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
343 * peer->lock - locks peer data fields.
344 * conn_data_lock - that more than one thread is not updating a conn data
345 * field at the same time.
356 * Do we need a lock to protect the peer field in the conn structure?
357 * conn->peer was previously a constant for all intents and so has no
358 * lock protecting this field. The multihomed client delta introduced
359 * a RX code change : change the peer field in the connection structure
360 * to that remote interface from which the last packet for this
361 * connection was sent out. This may become an issue if further changes
364 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
365 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
367 /* rxdb_fileID is used to identify the lock location, along with line#. */
368 static int rxdb_fileID = RXDB_FILE_RX;
369 #endif /* RX_LOCKS_DB */
370 #else /* RX_ENABLE_LOCKS */
371 #define SET_CALL_QUEUE_LOCK(C, L)
372 #define CLEAR_CALL_QUEUE_LOCK(C)
373 #endif /* RX_ENABLE_LOCKS */
374 struct rx_serverQueueEntry *rx_waitForPacket = 0;
375 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
377 /* ------------Exported Interfaces------------- */
379 /* This function allows rxkad to set the epoch to a suitably random number
380 * which rx_NewConnection will use in the future. The principle purpose is to
381 * get rxnull connections to use the same epoch as the rxkad connections do, at
382 * least once the first rxkad connection is established. This is important now
383 * that the host/port addresses aren't used in FindConnection: the uniqueness
384 * of epoch/cid matters and the start time won't do. */
386 #ifdef AFS_PTHREAD_ENV
388 * This mutex protects the following global variables:
392 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
393 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
397 #endif /* AFS_PTHREAD_ENV */
400 rx_SetEpoch(afs_uint32 epoch)
407 /* Initialize rx. A port number may be mentioned, in which case this
408 * becomes the default port number for any service installed later.
409 * If 0 is provided for the port number, a random port will be chosen
410 * by the kernel. Whether this will ever overlap anything in
411 * /etc/services is anybody's guess... Returns 0 on success, -1 on
416 int rxinit_status = 1;
417 #ifdef AFS_PTHREAD_ENV
419 * This mutex protects the following global variables:
423 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
424 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
427 #define UNLOCK_RX_INIT
431 rx_InitHost(u_int host, u_int port)
438 char *htable, *ptable;
445 if (rxinit_status == 0) {
446 tmp_status = rxinit_status;
448 return tmp_status; /* Already started; return previous error code. */
454 if (afs_winsockInit() < 0)
460 * Initialize anything necessary to provide a non-premptive threading
463 rxi_InitializeThreadSupport();
466 /* Allocate and initialize a socket for client and perhaps server
469 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
470 if (rx_socket == OSI_NULLSOCKET) {
474 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
477 #endif /* RX_LOCKS_DB */
478 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
479 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
480 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
481 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
482 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
483 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
484 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
485 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
486 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
488 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
490 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
492 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
494 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
495 #if defined(AFS_HPUX110_ENV)
497 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
498 #endif /* AFS_HPUX110_ENV */
499 #endif /* RX_ENABLE_LOCKS && KERNEL */
502 rx_connDeadTime = 12;
503 rx_tranquil = 0; /* reset flag */
504 rxi_ResetStatistics();
506 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
507 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
508 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
509 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
510 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
511 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
513 /* Malloc up a bunch of packets & buffers */
515 queue_Init(&rx_freePacketQueue);
516 rxi_NeedMorePackets = FALSE;
517 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
519 /* enforce a minimum number of allocated packets */
520 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
521 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
523 /* allocate the initial free packet pool */
524 #ifdef RX_ENABLE_TSFPQ
525 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
526 #else /* RX_ENABLE_TSFPQ */
527 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
528 #endif /* RX_ENABLE_TSFPQ */
535 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
536 tv.tv_sec = clock_now.sec;
537 tv.tv_usec = clock_now.usec;
538 srand((unsigned int)tv.tv_usec);
545 #if defined(KERNEL) && !defined(UKERNEL)
546 /* Really, this should never happen in a real kernel */
549 struct sockaddr_in addr;
551 int addrlen = sizeof(addr);
553 socklen_t addrlen = sizeof(addr);
555 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
559 rx_port = addr.sin_port;
562 rx_stats.minRtt.sec = 9999999;
564 rx_SetEpoch(tv.tv_sec | 0x80000000);
566 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
567 * will provide a randomer value. */
569 MUTEX_ENTER(&rx_quota_mutex);
570 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
571 MUTEX_EXIT(&rx_quota_mutex);
572 /* *Slightly* random start time for the cid. This is just to help
573 * out with the hashing function at the peer */
574 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
575 rx_connHashTable = (struct rx_connection **)htable;
576 rx_peerHashTable = (struct rx_peer **)ptable;
578 rx_lastAckDelay.sec = 0;
579 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
580 rx_hardAckDelay.sec = 0;
581 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
582 rx_softAckDelay.sec = 0;
583 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
585 rxevent_Init(20, rxi_ReScheduleEvents);
587 /* Initialize various global queues */
588 queue_Init(&rx_idleServerQueue);
589 queue_Init(&rx_incomingCallQueue);
590 queue_Init(&rx_freeCallQueue);
592 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
593 /* Initialize our list of usable IP addresses. */
597 /* Start listener process (exact function is dependent on the
598 * implementation environment--kernel or user space) */
602 tmp_status = rxinit_status = 0;
610 return rx_InitHost(htonl(INADDR_ANY), port);
614 * Sets the error generated when a busy call channel is detected.
616 * @param[in] error The error to return for a call on a busy channel.
618 * @pre Neither rx_Init nor rx_InitHost have been called yet
621 rx_SetBusyChannelError(afs_int32 error)
623 osi_Assert(rxinit_status != 0);
624 rxi_busyChannelError = error;
627 /* called with unincremented nRequestsRunning to see if it is OK to start
628 * a new thread in this service. Could be "no" for two reasons: over the
629 * max quota, or would prevent others from reaching their min quota.
631 #ifdef RX_ENABLE_LOCKS
632 /* This verion of QuotaOK reserves quota if it's ok while the
633 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
636 QuotaOK(struct rx_service *aservice)
638 /* check if over max quota */
639 if (aservice->nRequestsRunning >= aservice->maxProcs) {
643 /* under min quota, we're OK */
644 /* otherwise, can use only if there are enough to allow everyone
645 * to go to their min quota after this guy starts.
648 MUTEX_ENTER(&rx_quota_mutex);
649 if ((aservice->nRequestsRunning < aservice->minProcs)
650 || (rxi_availProcs > rxi_minDeficit)) {
651 aservice->nRequestsRunning++;
652 /* just started call in minProcs pool, need fewer to maintain
654 if (aservice->nRequestsRunning <= aservice->minProcs)
657 MUTEX_EXIT(&rx_quota_mutex);
660 MUTEX_EXIT(&rx_quota_mutex);
666 ReturnToServerPool(struct rx_service *aservice)
668 aservice->nRequestsRunning--;
669 MUTEX_ENTER(&rx_quota_mutex);
670 if (aservice->nRequestsRunning < aservice->minProcs)
673 MUTEX_EXIT(&rx_quota_mutex);
676 #else /* RX_ENABLE_LOCKS */
678 QuotaOK(struct rx_service *aservice)
681 /* under min quota, we're OK */
682 if (aservice->nRequestsRunning < aservice->minProcs)
685 /* check if over max quota */
686 if (aservice->nRequestsRunning >= aservice->maxProcs)
689 /* otherwise, can use only if there are enough to allow everyone
690 * to go to their min quota after this guy starts.
692 MUTEX_ENTER(&rx_quota_mutex);
693 if (rxi_availProcs > rxi_minDeficit)
695 MUTEX_EXIT(&rx_quota_mutex);
698 #endif /* RX_ENABLE_LOCKS */
701 /* Called by rx_StartServer to start up lwp's to service calls.
702 NExistingProcs gives the number of procs already existing, and which
703 therefore needn't be created. */
705 rxi_StartServerProcs(int nExistingProcs)
707 struct rx_service *service;
712 /* For each service, reserve N processes, where N is the "minimum"
713 * number of processes that MUST be able to execute a request in parallel,
714 * at any time, for that process. Also compute the maximum difference
715 * between any service's maximum number of processes that can run
716 * (i.e. the maximum number that ever will be run, and a guarantee
717 * that this number will run if other services aren't running), and its
718 * minimum number. The result is the extra number of processes that
719 * we need in order to provide the latter guarantee */
720 for (i = 0; i < RX_MAX_SERVICES; i++) {
722 service = rx_services[i];
723 if (service == (struct rx_service *)0)
725 nProcs += service->minProcs;
726 diff = service->maxProcs - service->minProcs;
730 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
731 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
732 for (i = 0; i < nProcs; i++) {
733 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
739 /* This routine is only required on Windows */
741 rx_StartClientThread(void)
743 #ifdef AFS_PTHREAD_ENV
745 pid = pthread_self();
746 #endif /* AFS_PTHREAD_ENV */
748 #endif /* AFS_NT40_ENV */
750 /* This routine must be called if any services are exported. If the
751 * donateMe flag is set, the calling process is donated to the server
754 rx_StartServer(int donateMe)
756 struct rx_service *service;
762 /* Start server processes, if necessary (exact function is dependent
763 * on the implementation environment--kernel or user space). DonateMe
764 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
765 * case, one less new proc will be created rx_StartServerProcs.
767 rxi_StartServerProcs(donateMe);
769 /* count up the # of threads in minProcs, and add set the min deficit to
770 * be that value, too.
772 for (i = 0; i < RX_MAX_SERVICES; i++) {
773 service = rx_services[i];
774 if (service == (struct rx_service *)0)
776 MUTEX_ENTER(&rx_quota_mutex);
777 rxi_totalMin += service->minProcs;
778 /* below works even if a thread is running, since minDeficit would
779 * still have been decremented and later re-incremented.
781 rxi_minDeficit += service->minProcs;
782 MUTEX_EXIT(&rx_quota_mutex);
785 /* Turn on reaping of idle server connections */
786 rxi_ReapConnections(NULL, NULL, NULL);
795 #ifdef AFS_PTHREAD_ENV
797 pid = afs_pointer_to_int(pthread_self());
798 #else /* AFS_PTHREAD_ENV */
800 LWP_CurrentProcess(&pid);
801 #endif /* AFS_PTHREAD_ENV */
803 sprintf(name, "srv_%d", ++nProcs);
805 (*registerProgram) (pid, name);
807 #endif /* AFS_NT40_ENV */
808 rx_ServerProc(NULL); /* Never returns */
810 #ifdef RX_ENABLE_TSFPQ
811 /* no use leaving packets around in this thread's local queue if
812 * it isn't getting donated to the server thread pool.
814 rxi_FlushLocalPacketsTSFPQ();
815 #endif /* RX_ENABLE_TSFPQ */
819 /* Create a new client connection to the specified service, using the
820 * specified security object to implement the security model for this
822 struct rx_connection *
823 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
824 struct rx_securityClass *securityObject,
825 int serviceSecurityIndex)
829 struct rx_connection *conn;
834 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
835 "serviceSecurityIndex %d)\n",
836 ntohl(shost), ntohs(sport), sservice, securityObject,
837 serviceSecurityIndex));
839 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
840 * the case of kmem_alloc? */
841 conn = rxi_AllocConnection();
842 #ifdef RX_ENABLE_LOCKS
843 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
844 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
845 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
848 MUTEX_ENTER(&rx_connHashTable_lock);
849 cid = (rx_nextCid += RX_MAXCALLS);
850 conn->type = RX_CLIENT_CONNECTION;
852 conn->epoch = rx_epoch;
853 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
854 conn->serviceId = sservice;
855 conn->securityObject = securityObject;
856 conn->securityData = (void *) 0;
857 conn->securityIndex = serviceSecurityIndex;
858 rx_SetConnDeadTime(conn, rx_connDeadTime);
859 rx_SetConnSecondsUntilNatPing(conn, 0);
860 conn->ackRate = RX_FAST_ACK_RATE;
862 conn->specific = NULL;
863 conn->challengeEvent = NULL;
864 conn->delayedAbortEvent = NULL;
865 conn->abortCount = 0;
867 for (i = 0; i < RX_MAXCALLS; i++) {
868 conn->twind[i] = rx_initSendWindow;
869 conn->rwind[i] = rx_initReceiveWindow;
870 conn->lastBusy[i] = 0;
873 RXS_NewConnection(securityObject, conn);
875 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
877 conn->refCount++; /* no lock required since only this thread knows... */
878 conn->next = rx_connHashTable[hashindex];
879 rx_connHashTable[hashindex] = conn;
881 rx_atomic_inc(&rx_stats.nClientConns);
882 MUTEX_EXIT(&rx_connHashTable_lock);
888 * Ensure a connection's timeout values are valid.
890 * @param[in] conn The connection to check
892 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
893 * unless idleDeadTime and/or hardDeadTime are not set
897 rxi_CheckConnTimeouts(struct rx_connection *conn)
899 /* a connection's timeouts must have the relationship
900 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
901 * total loss of network to a peer may cause an idle timeout instead of a
902 * dead timeout, simply because the idle timeout gets hit first. Also set
903 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
904 /* this logic is slightly complicated by the fact that
905 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
907 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
908 if (conn->idleDeadTime) {
909 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
911 if (conn->hardDeadTime) {
912 if (conn->idleDeadTime) {
913 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
915 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
921 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
923 /* The idea is to set the dead time to a value that allows several
924 * keepalives to be dropped without timing out the connection. */
925 conn->secondsUntilDead = seconds;
926 rxi_CheckConnTimeouts(conn);
927 conn->secondsUntilPing = conn->secondsUntilDead / 6;
931 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
933 conn->hardDeadTime = seconds;
934 rxi_CheckConnTimeouts(conn);
938 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
940 conn->idleDeadTime = seconds;
941 rxi_CheckConnTimeouts(conn);
944 int rxi_lowPeerRefCount = 0;
945 int rxi_lowConnRefCount = 0;
948 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
949 * NOTE: must not be called with rx_connHashTable_lock held.
952 rxi_CleanupConnection(struct rx_connection *conn)
954 /* Notify the service exporter, if requested, that this connection
955 * is being destroyed */
956 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
957 (*conn->service->destroyConnProc) (conn);
959 /* Notify the security module that this connection is being destroyed */
960 RXS_DestroyConnection(conn->securityObject, conn);
962 /* If this is the last connection using the rx_peer struct, set its
963 * idle time to now. rxi_ReapConnections will reap it if it's still
964 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
966 MUTEX_ENTER(&rx_peerHashTable_lock);
967 if (conn->peer->refCount < 2) {
968 conn->peer->idleWhen = clock_Sec();
969 if (conn->peer->refCount < 1) {
970 conn->peer->refCount = 1;
971 if (rx_stats_active) {
972 MUTEX_ENTER(&rx_stats_mutex);
973 rxi_lowPeerRefCount++;
974 MUTEX_EXIT(&rx_stats_mutex);
978 conn->peer->refCount--;
979 MUTEX_EXIT(&rx_peerHashTable_lock);
983 if (conn->type == RX_SERVER_CONNECTION)
984 rx_atomic_dec(&rx_stats.nServerConns);
986 rx_atomic_dec(&rx_stats.nClientConns);
989 if (conn->specific) {
991 for (i = 0; i < conn->nSpecific; i++) {
992 if (conn->specific[i] && rxi_keyCreate_destructor[i])
993 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
994 conn->specific[i] = NULL;
996 free(conn->specific);
998 conn->specific = NULL;
1000 #endif /* !KERNEL */
1002 MUTEX_DESTROY(&conn->conn_call_lock);
1003 MUTEX_DESTROY(&conn->conn_data_lock);
1004 CV_DESTROY(&conn->conn_call_cv);
1006 rxi_FreeConnection(conn);
1009 /* Destroy the specified connection */
1011 rxi_DestroyConnection(struct rx_connection *conn)
1013 MUTEX_ENTER(&rx_connHashTable_lock);
1014 rxi_DestroyConnectionNoLock(conn);
1015 /* conn should be at the head of the cleanup list */
1016 if (conn == rx_connCleanup_list) {
1017 rx_connCleanup_list = rx_connCleanup_list->next;
1018 MUTEX_EXIT(&rx_connHashTable_lock);
1019 rxi_CleanupConnection(conn);
1021 #ifdef RX_ENABLE_LOCKS
1023 MUTEX_EXIT(&rx_connHashTable_lock);
1025 #endif /* RX_ENABLE_LOCKS */
1029 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1031 struct rx_connection **conn_ptr;
1033 struct rx_packet *packet;
1040 MUTEX_ENTER(&conn->conn_data_lock);
1041 MUTEX_ENTER(&rx_refcnt_mutex);
1042 if (conn->refCount > 0)
1045 if (rx_stats_active) {
1046 MUTEX_ENTER(&rx_stats_mutex);
1047 rxi_lowConnRefCount++;
1048 MUTEX_EXIT(&rx_stats_mutex);
1052 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1053 /* Busy; wait till the last guy before proceeding */
1054 MUTEX_EXIT(&rx_refcnt_mutex);
1055 MUTEX_EXIT(&conn->conn_data_lock);
1060 /* If the client previously called rx_NewCall, but it is still
1061 * waiting, treat this as a running call, and wait to destroy the
1062 * connection later when the call completes. */
1063 if ((conn->type == RX_CLIENT_CONNECTION)
1064 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1065 conn->flags |= RX_CONN_DESTROY_ME;
1066 MUTEX_EXIT(&conn->conn_data_lock);
1070 MUTEX_EXIT(&rx_refcnt_mutex);
1071 MUTEX_EXIT(&conn->conn_data_lock);
1073 /* Check for extant references to this connection */
1074 for (i = 0; i < RX_MAXCALLS; i++) {
1075 struct rx_call *call = conn->call[i];
1078 if (conn->type == RX_CLIENT_CONNECTION) {
1079 MUTEX_ENTER(&call->lock);
1080 if (call->delayedAckEvent) {
1081 /* Push the final acknowledgment out now--there
1082 * won't be a subsequent call to acknowledge the
1083 * last reply packets */
1084 rxevent_Cancel(call->delayedAckEvent, call,
1085 RX_CALL_REFCOUNT_DELAY);
1086 if (call->state == RX_STATE_PRECALL
1087 || call->state == RX_STATE_ACTIVE) {
1088 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1090 rxi_AckAll(NULL, call, 0);
1093 MUTEX_EXIT(&call->lock);
1097 #ifdef RX_ENABLE_LOCKS
1099 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1100 MUTEX_EXIT(&conn->conn_data_lock);
1102 /* Someone is accessing a packet right now. */
1106 #endif /* RX_ENABLE_LOCKS */
1109 /* Don't destroy the connection if there are any call
1110 * structures still in use */
1111 MUTEX_ENTER(&conn->conn_data_lock);
1112 conn->flags |= RX_CONN_DESTROY_ME;
1113 MUTEX_EXIT(&conn->conn_data_lock);
1118 if (conn->natKeepAliveEvent) {
1119 rxi_NatKeepAliveOff(conn);
1122 if (conn->delayedAbortEvent) {
1123 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1124 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1126 MUTEX_ENTER(&conn->conn_data_lock);
1127 rxi_SendConnectionAbort(conn, packet, 0, 1);
1128 MUTEX_EXIT(&conn->conn_data_lock);
1129 rxi_FreePacket(packet);
1133 /* Remove from connection hash table before proceeding */
1135 &rx_connHashTable[CONN_HASH
1136 (peer->host, peer->port, conn->cid, conn->epoch,
1138 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1139 if (*conn_ptr == conn) {
1140 *conn_ptr = conn->next;
1144 /* if the conn that we are destroying was the last connection, then we
1145 * clear rxLastConn as well */
1146 if (rxLastConn == conn)
1149 /* Make sure the connection is completely reset before deleting it. */
1150 /* get rid of pending events that could zap us later */
1151 if (conn->challengeEvent)
1152 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1153 if (conn->checkReachEvent)
1154 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1155 if (conn->natKeepAliveEvent)
1156 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1158 /* Add the connection to the list of destroyed connections that
1159 * need to be cleaned up. This is necessary to avoid deadlocks
1160 * in the routines we call to inform others that this connection is
1161 * being destroyed. */
1162 conn->next = rx_connCleanup_list;
1163 rx_connCleanup_list = conn;
1166 /* Externally available version */
1168 rx_DestroyConnection(struct rx_connection *conn)
1173 rxi_DestroyConnection(conn);
1178 rx_GetConnection(struct rx_connection *conn)
1183 MUTEX_ENTER(&rx_refcnt_mutex);
1185 MUTEX_EXIT(&rx_refcnt_mutex);
1189 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1190 /* Wait for the transmit queue to no longer be busy.
1191 * requires the call->lock to be held */
1193 rxi_WaitforTQBusy(struct rx_call *call) {
1194 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1195 call->flags |= RX_CALL_TQ_WAIT;
1197 #ifdef RX_ENABLE_LOCKS
1198 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1199 CV_WAIT(&call->cv_tq, &call->lock);
1200 #else /* RX_ENABLE_LOCKS */
1201 osi_rxSleep(&call->tq);
1202 #endif /* RX_ENABLE_LOCKS */
1204 if (call->tqWaiters == 0) {
1205 call->flags &= ~RX_CALL_TQ_WAIT;
1212 rxi_WakeUpTransmitQueue(struct rx_call *call)
1214 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1215 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1216 call, call->tqWaiters, call->flags));
1217 #ifdef RX_ENABLE_LOCKS
1218 osirx_AssertMine(&call->lock, "rxi_Start start");
1219 CV_BROADCAST(&call->cv_tq);
1220 #else /* RX_ENABLE_LOCKS */
1221 osi_rxWakeup(&call->tq);
1222 #endif /* RX_ENABLE_LOCKS */
1226 /* Start a new rx remote procedure call, on the specified connection.
1227 * If wait is set to 1, wait for a free call channel; otherwise return
1228 * 0. Maxtime gives the maximum number of seconds this call may take,
1229 * after rx_NewCall returns. After this time interval, a call to any
1230 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1231 * For fine grain locking, we hold the conn_call_lock in order to
1232 * to ensure that we don't get signalle after we found a call in an active
1233 * state and before we go to sleep.
1236 rx_NewCall(struct rx_connection *conn)
1238 int i, wait, ignoreBusy = 1;
1239 struct rx_call *call;
1240 struct clock queueTime;
1241 afs_uint32 leastBusy = 0;
1245 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1248 clock_GetTime(&queueTime);
1250 * Check if there are others waiting for a new call.
1251 * If so, let them go first to avoid starving them.
1252 * This is a fairly simple scheme, and might not be
1253 * a complete solution for large numbers of waiters.
1255 * makeCallWaiters keeps track of the number of
1256 * threads waiting to make calls and the
1257 * RX_CONN_MAKECALL_WAITING flag bit is used to
1258 * indicate that there are indeed calls waiting.
1259 * The flag is set when the waiter is incremented.
1260 * It is only cleared when makeCallWaiters is 0.
1261 * This prevents us from accidently destroying the
1262 * connection while it is potentially about to be used.
1264 MUTEX_ENTER(&conn->conn_call_lock);
1265 MUTEX_ENTER(&conn->conn_data_lock);
1266 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1267 conn->flags |= RX_CONN_MAKECALL_WAITING;
1268 conn->makeCallWaiters++;
1269 MUTEX_EXIT(&conn->conn_data_lock);
1271 #ifdef RX_ENABLE_LOCKS
1272 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1276 MUTEX_ENTER(&conn->conn_data_lock);
1277 conn->makeCallWaiters--;
1278 if (conn->makeCallWaiters == 0)
1279 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1282 /* We are now the active thread in rx_NewCall */
1283 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1284 MUTEX_EXIT(&conn->conn_data_lock);
1289 for (i = 0; i < RX_MAXCALLS; i++) {
1290 call = conn->call[i];
1292 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1293 /* we're not ignoring busy call slots; only look at the
1294 * call slot that is the "least" busy */
1298 if (call->state == RX_STATE_DALLY) {
1299 MUTEX_ENTER(&call->lock);
1300 if (call->state == RX_STATE_DALLY) {
1301 if (ignoreBusy && conn->lastBusy[i]) {
1302 /* if we're ignoring busy call slots, skip any ones that
1303 * have lastBusy set */
1304 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1305 leastBusy = conn->lastBusy[i];
1307 MUTEX_EXIT(&call->lock);
1312 * We are setting the state to RX_STATE_RESET to
1313 * ensure that no one else will attempt to use this
1314 * call once we drop the conn->conn_call_lock and
1315 * call->lock. We must drop the conn->conn_call_lock
1316 * before calling rxi_ResetCall because the process
1317 * of clearing the transmit queue can block for an
1318 * extended period of time. If we block while holding
1319 * the conn->conn_call_lock, then all rx_EndCall
1320 * processing will block as well. This has a detrimental
1321 * effect on overall system performance.
1323 call->state = RX_STATE_RESET;
1324 MUTEX_EXIT(&conn->conn_call_lock);
1325 MUTEX_ENTER(&rx_refcnt_mutex);
1326 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1327 MUTEX_EXIT(&rx_refcnt_mutex);
1328 rxi_ResetCall(call, 0);
1329 (*call->callNumber)++;
1330 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1334 * If we failed to be able to safely obtain the
1335 * conn->conn_call_lock we will have to drop the
1336 * call->lock to avoid a deadlock. When the call->lock
1337 * is released the state of the call can change. If it
1338 * is no longer RX_STATE_RESET then some other thread is
1341 MUTEX_EXIT(&call->lock);
1342 MUTEX_ENTER(&conn->conn_call_lock);
1343 MUTEX_ENTER(&call->lock);
1345 if (call->state == RX_STATE_RESET)
1349 * If we get here it means that after dropping
1350 * the conn->conn_call_lock and call->lock that
1351 * the call is no longer ours. If we can't find
1352 * a free call in the remaining slots we should
1353 * not go immediately to RX_CONN_MAKECALL_WAITING
1354 * because by dropping the conn->conn_call_lock
1355 * we have given up synchronization with rx_EndCall.
1356 * Instead, cycle through one more time to see if
1357 * we can find a call that can call our own.
1359 MUTEX_ENTER(&rx_refcnt_mutex);
1360 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1361 MUTEX_EXIT(&rx_refcnt_mutex);
1364 MUTEX_EXIT(&call->lock);
1367 if (ignoreBusy && conn->lastBusy[i]) {
1368 /* if we're ignoring busy call slots, skip any ones that
1369 * have lastBusy set */
1370 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1371 leastBusy = conn->lastBusy[i];
1376 /* rxi_NewCall returns with mutex locked */
1377 call = rxi_NewCall(conn, i);
1378 MUTEX_ENTER(&rx_refcnt_mutex);
1379 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1380 MUTEX_EXIT(&rx_refcnt_mutex);
1384 if (i < RX_MAXCALLS) {
1385 conn->lastBusy[i] = 0;
1390 if (leastBusy && ignoreBusy) {
1391 /* we didn't find a useable call slot, but we did see at least one
1392 * 'busy' slot; look again and only use a slot with the 'least
1398 MUTEX_ENTER(&conn->conn_data_lock);
1399 conn->flags |= RX_CONN_MAKECALL_WAITING;
1400 conn->makeCallWaiters++;
1401 MUTEX_EXIT(&conn->conn_data_lock);
1403 #ifdef RX_ENABLE_LOCKS
1404 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1408 MUTEX_ENTER(&conn->conn_data_lock);
1409 conn->makeCallWaiters--;
1410 if (conn->makeCallWaiters == 0)
1411 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1412 MUTEX_EXIT(&conn->conn_data_lock);
1414 /* Client is initially in send mode */
1415 call->state = RX_STATE_ACTIVE;
1416 call->error = conn->error;
1418 call->mode = RX_MODE_ERROR;
1420 call->mode = RX_MODE_SENDING;
1422 /* remember start time for call in case we have hard dead time limit */
1423 call->queueTime = queueTime;
1424 clock_GetTime(&call->startTime);
1425 hzero(call->bytesSent);
1426 hzero(call->bytesRcvd);
1428 /* Turn on busy protocol. */
1429 rxi_KeepAliveOn(call);
1431 /* Attempt MTU discovery */
1432 rxi_GrowMTUOn(call);
1435 * We are no longer the active thread in rx_NewCall
1437 MUTEX_ENTER(&conn->conn_data_lock);
1438 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1439 MUTEX_EXIT(&conn->conn_data_lock);
1442 * Wake up anyone else who might be giving us a chance to
1443 * run (see code above that avoids resource starvation).
1445 #ifdef RX_ENABLE_LOCKS
1446 CV_BROADCAST(&conn->conn_call_cv);
1450 MUTEX_EXIT(&conn->conn_call_lock);
1452 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1453 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1454 osi_Panic("rx_NewCall call about to be used without an empty tq");
1456 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1458 MUTEX_EXIT(&call->lock);
1461 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1466 rxi_HasActiveCalls(struct rx_connection *aconn)
1469 struct rx_call *tcall;
1473 for (i = 0; i < RX_MAXCALLS; i++) {
1474 if ((tcall = aconn->call[i])) {
1475 if ((tcall->state == RX_STATE_ACTIVE)
1476 || (tcall->state == RX_STATE_PRECALL)) {
1487 rxi_GetCallNumberVector(struct rx_connection *aconn,
1488 afs_int32 * aint32s)
1491 struct rx_call *tcall;
1495 for (i = 0; i < RX_MAXCALLS; i++) {
1496 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1497 aint32s[i] = aconn->callNumber[i] + 1;
1499 aint32s[i] = aconn->callNumber[i];
1506 rxi_SetCallNumberVector(struct rx_connection *aconn,
1507 afs_int32 * aint32s)
1510 struct rx_call *tcall;
1514 for (i = 0; i < RX_MAXCALLS; i++) {
1515 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1516 aconn->callNumber[i] = aint32s[i] - 1;
1518 aconn->callNumber[i] = aint32s[i];
1524 /* Advertise a new service. A service is named locally by a UDP port
1525 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1528 char *serviceName; Name for identification purposes (e.g. the
1529 service name might be used for probing for
1532 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1533 char *serviceName, struct rx_securityClass **securityObjects,
1534 int nSecurityObjects,
1535 afs_int32(*serviceProc) (struct rx_call * acall))
1537 osi_socket socket = OSI_NULLSOCKET;
1538 struct rx_service *tservice;
1544 if (serviceId == 0) {
1546 "rx_NewService: service id for service %s is not non-zero.\n",
1553 "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",
1561 tservice = rxi_AllocService();
1564 #ifdef RX_ENABLE_LOCKS
1565 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1568 for (i = 0; i < RX_MAX_SERVICES; i++) {
1569 struct rx_service *service = rx_services[i];
1571 if (port == service->servicePort && host == service->serviceHost) {
1572 if (service->serviceId == serviceId) {
1573 /* The identical service has already been
1574 * installed; if the caller was intending to
1575 * change the security classes used by this
1576 * service, he/she loses. */
1578 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1579 serviceName, serviceId, service->serviceName);
1581 rxi_FreeService(tservice);
1584 /* Different service, same port: re-use the socket
1585 * which is bound to the same port */
1586 socket = service->socket;
1589 if (socket == OSI_NULLSOCKET) {
1590 /* If we don't already have a socket (from another
1591 * service on same port) get a new one */
1592 socket = rxi_GetHostUDPSocket(host, port);
1593 if (socket == OSI_NULLSOCKET) {
1595 rxi_FreeService(tservice);
1600 service->socket = socket;
1601 service->serviceHost = host;
1602 service->servicePort = port;
1603 service->serviceId = serviceId;
1604 service->serviceName = serviceName;
1605 service->nSecurityObjects = nSecurityObjects;
1606 service->securityObjects = securityObjects;
1607 service->minProcs = 0;
1608 service->maxProcs = 1;
1609 service->idleDeadTime = 60;
1610 service->idleDeadErr = 0;
1611 service->connDeadTime = rx_connDeadTime;
1612 service->executeRequestProc = serviceProc;
1613 service->checkReach = 0;
1614 service->nSpecific = 0;
1615 service->specific = NULL;
1616 rx_services[i] = service; /* not visible until now */
1622 rxi_FreeService(tservice);
1623 (osi_Msg "rx_NewService: cannot support > %d services\n",
1628 /* Set configuration options for all of a service's security objects */
1631 rx_SetSecurityConfiguration(struct rx_service *service,
1632 rx_securityConfigVariables type,
1636 for (i = 0; i<service->nSecurityObjects; i++) {
1637 if (service->securityObjects[i]) {
1638 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1646 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1647 struct rx_securityClass **securityObjects, int nSecurityObjects,
1648 afs_int32(*serviceProc) (struct rx_call * acall))
1650 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1653 /* Generic request processing loop. This routine should be called
1654 * by the implementation dependent rx_ServerProc. If socketp is
1655 * non-null, it will be set to the file descriptor that this thread
1656 * is now listening on. If socketp is null, this routine will never
1659 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1661 struct rx_call *call;
1663 struct rx_service *tservice = NULL;
1670 call = rx_GetCall(threadID, tservice, socketp);
1671 if (socketp && *socketp != OSI_NULLSOCKET) {
1672 /* We are now a listener thread */
1677 /* if server is restarting( typically smooth shutdown) then do not
1678 * allow any new calls.
1681 if (rx_tranquil && (call != NULL)) {
1685 MUTEX_ENTER(&call->lock);
1687 rxi_CallError(call, RX_RESTARTING);
1688 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1690 MUTEX_EXIT(&call->lock);
1694 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1695 #ifdef RX_ENABLE_LOCKS
1697 #endif /* RX_ENABLE_LOCKS */
1698 afs_termState = AFSOP_STOP_AFS;
1699 afs_osi_Wakeup(&afs_termState);
1700 #ifdef RX_ENABLE_LOCKS
1702 #endif /* RX_ENABLE_LOCKS */
1707 tservice = call->conn->service;
1709 if (tservice->beforeProc)
1710 (*tservice->beforeProc) (call);
1712 code = tservice->executeRequestProc(call);
1714 if (tservice->afterProc)
1715 (*tservice->afterProc) (call, code);
1717 rx_EndCall(call, code);
1718 if (rx_stats_active) {
1719 MUTEX_ENTER(&rx_stats_mutex);
1721 MUTEX_EXIT(&rx_stats_mutex);
1728 rx_WakeupServerProcs(void)
1730 struct rx_serverQueueEntry *np, *tqp;
1734 MUTEX_ENTER(&rx_serverPool_lock);
1736 #ifdef RX_ENABLE_LOCKS
1737 if (rx_waitForPacket)
1738 CV_BROADCAST(&rx_waitForPacket->cv);
1739 #else /* RX_ENABLE_LOCKS */
1740 if (rx_waitForPacket)
1741 osi_rxWakeup(rx_waitForPacket);
1742 #endif /* RX_ENABLE_LOCKS */
1743 MUTEX_ENTER(&freeSQEList_lock);
1744 for (np = rx_FreeSQEList; np; np = tqp) {
1745 tqp = *(struct rx_serverQueueEntry **)np;
1746 #ifdef RX_ENABLE_LOCKS
1747 CV_BROADCAST(&np->cv);
1748 #else /* RX_ENABLE_LOCKS */
1750 #endif /* RX_ENABLE_LOCKS */
1752 MUTEX_EXIT(&freeSQEList_lock);
1753 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1754 #ifdef RX_ENABLE_LOCKS
1755 CV_BROADCAST(&np->cv);
1756 #else /* RX_ENABLE_LOCKS */
1758 #endif /* RX_ENABLE_LOCKS */
1760 MUTEX_EXIT(&rx_serverPool_lock);
1765 * One thing that seems to happen is that all the server threads get
1766 * tied up on some empty or slow call, and then a whole bunch of calls
1767 * arrive at once, using up the packet pool, so now there are more
1768 * empty calls. The most critical resources here are server threads
1769 * and the free packet pool. The "doreclaim" code seems to help in
1770 * general. I think that eventually we arrive in this state: there
1771 * are lots of pending calls which do have all their packets present,
1772 * so they won't be reclaimed, are multi-packet calls, so they won't
1773 * be scheduled until later, and thus are tying up most of the free
1774 * packet pool for a very long time.
1776 * 1. schedule multi-packet calls if all the packets are present.
1777 * Probably CPU-bound operation, useful to return packets to pool.
1778 * Do what if there is a full window, but the last packet isn't here?
1779 * 3. preserve one thread which *only* runs "best" calls, otherwise
1780 * it sleeps and waits for that type of call.
1781 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1782 * the current dataquota business is badly broken. The quota isn't adjusted
1783 * to reflect how many packets are presently queued for a running call.
1784 * So, when we schedule a queued call with a full window of packets queued
1785 * up for it, that *should* free up a window full of packets for other 2d-class
1786 * calls to be able to use from the packet pool. But it doesn't.
1788 * NB. Most of the time, this code doesn't run -- since idle server threads
1789 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1790 * as a new call arrives.
1792 /* Sleep until a call arrives. Returns a pointer to the call, ready
1793 * for an rx_Read. */
1794 #ifdef RX_ENABLE_LOCKS
1796 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1798 struct rx_serverQueueEntry *sq;
1799 struct rx_call *call = (struct rx_call *)0;
1800 struct rx_service *service = NULL;
1803 MUTEX_ENTER(&freeSQEList_lock);
1805 if ((sq = rx_FreeSQEList)) {
1806 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1807 MUTEX_EXIT(&freeSQEList_lock);
1808 } else { /* otherwise allocate a new one and return that */
1809 MUTEX_EXIT(&freeSQEList_lock);
1810 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1811 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1812 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1815 MUTEX_ENTER(&rx_serverPool_lock);
1816 if (cur_service != NULL) {
1817 ReturnToServerPool(cur_service);
1820 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1821 struct rx_call *tcall, *ncall, *choice2 = NULL;
1823 /* Scan for eligible incoming calls. A call is not eligible
1824 * if the maximum number of calls for its service type are
1825 * already executing */
1826 /* One thread will process calls FCFS (to prevent starvation),
1827 * while the other threads may run ahead looking for calls which
1828 * have all their input data available immediately. This helps
1829 * keep threads from blocking, waiting for data from the client. */
1830 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1831 service = tcall->conn->service;
1832 if (!QuotaOK(service)) {
1835 MUTEX_ENTER(&rx_pthread_mutex);
1836 if (tno == rxi_fcfs_thread_num
1837 || !tcall->queue_item_header.next) {
1838 MUTEX_EXIT(&rx_pthread_mutex);
1839 /* If we're the fcfs thread , then we'll just use
1840 * this call. If we haven't been able to find an optimal
1841 * choice, and we're at the end of the list, then use a
1842 * 2d choice if one has been identified. Otherwise... */
1843 call = (choice2 ? choice2 : tcall);
1844 service = call->conn->service;
1846 MUTEX_EXIT(&rx_pthread_mutex);
1847 if (!queue_IsEmpty(&tcall->rq)) {
1848 struct rx_packet *rp;
1849 rp = queue_First(&tcall->rq, rx_packet);
1850 if (rp->header.seq == 1) {
1852 || (rp->header.flags & RX_LAST_PACKET)) {
1854 } else if (rxi_2dchoice && !choice2
1855 && !(tcall->flags & RX_CALL_CLEARED)
1856 && (tcall->rprev > rxi_HardAckRate)) {
1866 ReturnToServerPool(service);
1873 MUTEX_EXIT(&rx_serverPool_lock);
1874 MUTEX_ENTER(&call->lock);
1876 if (call->flags & RX_CALL_WAIT_PROC) {
1877 call->flags &= ~RX_CALL_WAIT_PROC;
1878 rx_atomic_dec(&rx_nWaiting);
1881 if (call->state != RX_STATE_PRECALL || call->error) {
1882 MUTEX_EXIT(&call->lock);
1883 MUTEX_ENTER(&rx_serverPool_lock);
1884 ReturnToServerPool(service);
1889 if (queue_IsEmpty(&call->rq)
1890 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1891 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1893 CLEAR_CALL_QUEUE_LOCK(call);
1896 /* If there are no eligible incoming calls, add this process
1897 * to the idle server queue, to wait for one */
1901 *socketp = OSI_NULLSOCKET;
1903 sq->socketp = socketp;
1904 queue_Append(&rx_idleServerQueue, sq);
1905 #ifndef AFS_AIX41_ENV
1906 rx_waitForPacket = sq;
1908 rx_waitingForPacket = sq;
1909 #endif /* AFS_AIX41_ENV */
1911 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1913 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1914 MUTEX_EXIT(&rx_serverPool_lock);
1915 return (struct rx_call *)0;
1918 } while (!(call = sq->newcall)
1919 && !(socketp && *socketp != OSI_NULLSOCKET));
1920 MUTEX_EXIT(&rx_serverPool_lock);
1922 MUTEX_ENTER(&call->lock);
1928 MUTEX_ENTER(&freeSQEList_lock);
1929 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1930 rx_FreeSQEList = sq;
1931 MUTEX_EXIT(&freeSQEList_lock);
1934 clock_GetTime(&call->startTime);
1935 call->state = RX_STATE_ACTIVE;
1936 call->mode = RX_MODE_RECEIVING;
1937 #ifdef RX_KERNEL_TRACE
1938 if (ICL_SETACTIVE(afs_iclSetp)) {
1939 int glockOwner = ISAFS_GLOCK();
1942 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1943 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1950 rxi_calltrace(RX_CALL_START, call);
1951 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1952 call->conn->service->servicePort, call->conn->service->serviceId,
1955 MUTEX_EXIT(&call->lock);
1956 MUTEX_ENTER(&rx_refcnt_mutex);
1957 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1958 MUTEX_EXIT(&rx_refcnt_mutex);
1960 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1965 #else /* RX_ENABLE_LOCKS */
1967 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1969 struct rx_serverQueueEntry *sq;
1970 struct rx_call *call = (struct rx_call *)0, *choice2;
1971 struct rx_service *service = NULL;
1975 MUTEX_ENTER(&freeSQEList_lock);
1977 if ((sq = rx_FreeSQEList)) {
1978 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1979 MUTEX_EXIT(&freeSQEList_lock);
1980 } else { /* otherwise allocate a new one and return that */
1981 MUTEX_EXIT(&freeSQEList_lock);
1982 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1983 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1984 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1986 MUTEX_ENTER(&sq->lock);
1988 if (cur_service != NULL) {
1989 cur_service->nRequestsRunning--;
1990 MUTEX_ENTER(&rx_quota_mutex);
1991 if (cur_service->nRequestsRunning < cur_service->minProcs)
1994 MUTEX_EXIT(&rx_quota_mutex);
1996 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1997 struct rx_call *tcall, *ncall;
1998 /* Scan for eligible incoming calls. A call is not eligible
1999 * if the maximum number of calls for its service type are
2000 * already executing */
2001 /* One thread will process calls FCFS (to prevent starvation),
2002 * while the other threads may run ahead looking for calls which
2003 * have all their input data available immediately. This helps
2004 * keep threads from blocking, waiting for data from the client. */
2005 choice2 = (struct rx_call *)0;
2006 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2007 service = tcall->conn->service;
2008 if (QuotaOK(service)) {
2009 MUTEX_ENTER(&rx_pthread_mutex);
2010 if (tno == rxi_fcfs_thread_num
2011 || !tcall->queue_item_header.next) {
2012 MUTEX_EXIT(&rx_pthread_mutex);
2013 /* If we're the fcfs thread, then we'll just use
2014 * this call. If we haven't been able to find an optimal
2015 * choice, and we're at the end of the list, then use a
2016 * 2d choice if one has been identified. Otherwise... */
2017 call = (choice2 ? choice2 : tcall);
2018 service = call->conn->service;
2020 MUTEX_EXIT(&rx_pthread_mutex);
2021 if (!queue_IsEmpty(&tcall->rq)) {
2022 struct rx_packet *rp;
2023 rp = queue_First(&tcall->rq, rx_packet);
2024 if (rp->header.seq == 1
2026 || (rp->header.flags & RX_LAST_PACKET))) {
2028 } else if (rxi_2dchoice && !choice2
2029 && !(tcall->flags & RX_CALL_CLEARED)
2030 && (tcall->rprev > rxi_HardAckRate)) {
2044 /* we can't schedule a call if there's no data!!! */
2045 /* send an ack if there's no data, if we're missing the
2046 * first packet, or we're missing something between first
2047 * and last -- there's a "hole" in the incoming data. */
2048 if (queue_IsEmpty(&call->rq)
2049 || queue_First(&call->rq, rx_packet)->header.seq != 1
2050 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2051 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2053 call->flags &= (~RX_CALL_WAIT_PROC);
2054 service->nRequestsRunning++;
2055 /* just started call in minProcs pool, need fewer to maintain
2057 MUTEX_ENTER(&rx_quota_mutex);
2058 if (service->nRequestsRunning <= service->minProcs)
2061 MUTEX_EXIT(&rx_quota_mutex);
2062 rx_atomic_dec(&rx_nWaiting);
2063 /* MUTEX_EXIT(&call->lock); */
2065 /* If there are no eligible incoming calls, add this process
2066 * to the idle server queue, to wait for one */
2069 *socketp = OSI_NULLSOCKET;
2071 sq->socketp = socketp;
2072 queue_Append(&rx_idleServerQueue, sq);
2076 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2078 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2079 return (struct rx_call *)0;
2082 } while (!(call = sq->newcall)
2083 && !(socketp && *socketp != OSI_NULLSOCKET));
2085 MUTEX_EXIT(&sq->lock);
2087 MUTEX_ENTER(&freeSQEList_lock);
2088 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2089 rx_FreeSQEList = sq;
2090 MUTEX_EXIT(&freeSQEList_lock);
2093 clock_GetTime(&call->startTime);
2094 call->state = RX_STATE_ACTIVE;
2095 call->mode = RX_MODE_RECEIVING;
2096 #ifdef RX_KERNEL_TRACE
2097 if (ICL_SETACTIVE(afs_iclSetp)) {
2098 int glockOwner = ISAFS_GLOCK();
2101 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2102 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2109 rxi_calltrace(RX_CALL_START, call);
2110 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2111 call->conn->service->servicePort, call->conn->service->serviceId,
2114 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2121 #endif /* RX_ENABLE_LOCKS */
2125 /* Establish a procedure to be called when a packet arrives for a
2126 * call. This routine will be called at most once after each call,
2127 * and will also be called if there is an error condition on the or
2128 * the call is complete. Used by multi rx to build a selection
2129 * function which determines which of several calls is likely to be a
2130 * good one to read from.
2131 * NOTE: the way this is currently implemented it is probably only a
2132 * good idea to (1) use it immediately after a newcall (clients only)
2133 * and (2) only use it once. Other uses currently void your warranty
2136 rx_SetArrivalProc(struct rx_call *call,
2137 void (*proc) (struct rx_call * call,
2140 void * handle, int arg)
2142 call->arrivalProc = proc;
2143 call->arrivalProcHandle = handle;
2144 call->arrivalProcArg = arg;
2147 /* Call is finished (possibly prematurely). Return rc to the peer, if
2148 * appropriate, and return the final error code from the conversation
2152 rx_EndCall(struct rx_call *call, afs_int32 rc)
2154 struct rx_connection *conn = call->conn;
2158 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2159 call, rc, call->error, call->abortCode));
2162 MUTEX_ENTER(&call->lock);
2164 if (rc == 0 && call->error == 0) {
2165 call->abortCode = 0;
2166 call->abortCount = 0;
2169 call->arrivalProc = (void (*)())0;
2170 if (rc && call->error == 0) {
2171 rxi_CallError(call, rc);
2172 call->mode = RX_MODE_ERROR;
2173 /* Send an abort message to the peer if this error code has
2174 * only just been set. If it was set previously, assume the
2175 * peer has already been sent the error code or will request it
2177 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2179 if (conn->type == RX_SERVER_CONNECTION) {
2180 /* Make sure reply or at least dummy reply is sent */
2181 if (call->mode == RX_MODE_RECEIVING) {
2182 MUTEX_EXIT(&call->lock);
2183 rxi_WriteProc(call, 0, 0);
2184 MUTEX_ENTER(&call->lock);
2186 if (call->mode == RX_MODE_SENDING) {
2187 MUTEX_EXIT(&call->lock);
2188 rxi_FlushWrite(call);
2189 MUTEX_ENTER(&call->lock);
2191 rxi_calltrace(RX_CALL_END, call);
2192 /* Call goes to hold state until reply packets are acknowledged */
2193 if (call->tfirst + call->nSoftAcked < call->tnext) {
2194 call->state = RX_STATE_HOLD;
2196 call->state = RX_STATE_DALLY;
2197 rxi_ClearTransmitQueue(call, 0);
2198 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2199 rxevent_Cancel(call->keepAliveEvent, call,
2200 RX_CALL_REFCOUNT_ALIVE);
2202 } else { /* Client connection */
2204 /* Make sure server receives input packets, in the case where
2205 * no reply arguments are expected */
2206 if ((call->mode == RX_MODE_SENDING)
2207 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2208 MUTEX_EXIT(&call->lock);
2209 (void)rxi_ReadProc(call, &dummy, 1);
2210 MUTEX_ENTER(&call->lock);
2213 /* If we had an outstanding delayed ack, be nice to the server
2214 * and force-send it now.
2216 if (call->delayedAckEvent) {
2217 rxevent_Cancel(call->delayedAckEvent, call,
2218 RX_CALL_REFCOUNT_DELAY);
2219 call->delayedAckEvent = NULL;
2220 rxi_SendDelayedAck(NULL, call, NULL);
2223 /* We need to release the call lock since it's lower than the
2224 * conn_call_lock and we don't want to hold the conn_call_lock
2225 * over the rx_ReadProc call. The conn_call_lock needs to be held
2226 * here for the case where rx_NewCall is perusing the calls on
2227 * the connection structure. We don't want to signal until
2228 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2229 * have checked this call, found it active and by the time it
2230 * goes to sleep, will have missed the signal.
2232 MUTEX_EXIT(&call->lock);
2233 MUTEX_ENTER(&conn->conn_call_lock);
2234 MUTEX_ENTER(&call->lock);
2236 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2237 conn->lastBusy[call->channel] = 0;
2240 MUTEX_ENTER(&conn->conn_data_lock);
2241 conn->flags |= RX_CONN_BUSY;
2242 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2243 MUTEX_EXIT(&conn->conn_data_lock);
2244 #ifdef RX_ENABLE_LOCKS
2245 CV_BROADCAST(&conn->conn_call_cv);
2250 #ifdef RX_ENABLE_LOCKS
2252 MUTEX_EXIT(&conn->conn_data_lock);
2254 #endif /* RX_ENABLE_LOCKS */
2255 call->state = RX_STATE_DALLY;
2257 error = call->error;
2259 /* currentPacket, nLeft, and NFree must be zeroed here, because
2260 * ResetCall cannot: ResetCall may be called at splnet(), in the
2261 * kernel version, and may interrupt the macros rx_Read or
2262 * rx_Write, which run at normal priority for efficiency. */
2263 if (call->currentPacket) {
2264 #ifdef RX_TRACK_PACKETS
2265 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2267 rxi_FreePacket(call->currentPacket);
2268 call->currentPacket = (struct rx_packet *)0;
2271 call->nLeft = call->nFree = call->curlen = 0;
2273 /* Free any packets from the last call to ReadvProc/WritevProc */
2274 #ifdef RXDEBUG_PACKET
2276 #endif /* RXDEBUG_PACKET */
2277 rxi_FreePackets(0, &call->iovq);
2278 MUTEX_EXIT(&call->lock);
2280 MUTEX_ENTER(&rx_refcnt_mutex);
2281 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2282 MUTEX_EXIT(&rx_refcnt_mutex);
2283 if (conn->type == RX_CLIENT_CONNECTION) {
2284 MUTEX_ENTER(&conn->conn_data_lock);
2285 conn->flags &= ~RX_CONN_BUSY;
2286 MUTEX_EXIT(&conn->conn_data_lock);
2287 MUTEX_EXIT(&conn->conn_call_lock);
2291 * Map errors to the local host's errno.h format.
2293 error = ntoh_syserr_conv(error);
2297 #if !defined(KERNEL)
2299 /* Call this routine when shutting down a server or client (especially
2300 * clients). This will allow Rx to gracefully garbage collect server
2301 * connections, and reduce the number of retries that a server might
2302 * make to a dead client.
2303 * This is not quite right, since some calls may still be ongoing and
2304 * we can't lock them to destroy them. */
2308 struct rx_connection **conn_ptr, **conn_end;
2312 if (rxinit_status == 1) {
2314 return; /* Already shutdown. */
2316 rxi_DeleteCachedConnections();
2317 if (rx_connHashTable) {
2318 MUTEX_ENTER(&rx_connHashTable_lock);
2319 for (conn_ptr = &rx_connHashTable[0], conn_end =
2320 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2322 struct rx_connection *conn, *next;
2323 for (conn = *conn_ptr; conn; conn = next) {
2325 if (conn->type == RX_CLIENT_CONNECTION) {
2326 MUTEX_ENTER(&rx_refcnt_mutex);
2328 MUTEX_EXIT(&rx_refcnt_mutex);
2329 #ifdef RX_ENABLE_LOCKS
2330 rxi_DestroyConnectionNoLock(conn);
2331 #else /* RX_ENABLE_LOCKS */
2332 rxi_DestroyConnection(conn);
2333 #endif /* RX_ENABLE_LOCKS */
2337 #ifdef RX_ENABLE_LOCKS
2338 while (rx_connCleanup_list) {
2339 struct rx_connection *conn;
2340 conn = rx_connCleanup_list;
2341 rx_connCleanup_list = rx_connCleanup_list->next;
2342 MUTEX_EXIT(&rx_connHashTable_lock);
2343 rxi_CleanupConnection(conn);
2344 MUTEX_ENTER(&rx_connHashTable_lock);
2346 MUTEX_EXIT(&rx_connHashTable_lock);
2347 #endif /* RX_ENABLE_LOCKS */
2352 afs_winsockCleanup();
2360 /* if we wakeup packet waiter too often, can get in loop with two
2361 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2363 rxi_PacketsUnWait(void)
2365 if (!rx_waitingForPackets) {
2369 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2370 return; /* still over quota */
2373 rx_waitingForPackets = 0;
2374 #ifdef RX_ENABLE_LOCKS
2375 CV_BROADCAST(&rx_waitingForPackets_cv);
2377 osi_rxWakeup(&rx_waitingForPackets);
2383 /* ------------------Internal interfaces------------------------- */
2385 /* Return this process's service structure for the
2386 * specified socket and service */
2388 rxi_FindService(osi_socket socket, u_short serviceId)
2390 struct rx_service **sp;
2391 for (sp = &rx_services[0]; *sp; sp++) {
2392 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2398 #ifdef RXDEBUG_PACKET
2399 #ifdef KDUMP_RX_LOCK
2400 static struct rx_call_rx_lock *rx_allCallsp = 0;
2402 static struct rx_call *rx_allCallsp = 0;
2404 #endif /* RXDEBUG_PACKET */
2406 /* Allocate a call structure, for the indicated channel of the
2407 * supplied connection. The mode and state of the call must be set by
2408 * the caller. Returns the call with mutex locked. */
2410 rxi_NewCall(struct rx_connection *conn, int channel)
2412 struct rx_call *call;
2413 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2414 struct rx_call *cp; /* Call pointer temp */
2415 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2416 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2418 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2420 /* Grab an existing call structure, or allocate a new one.
2421 * Existing call structures are assumed to have been left reset by
2423 MUTEX_ENTER(&rx_freeCallQueue_lock);
2425 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2427 * EXCEPT that the TQ might not yet be cleared out.
2428 * Skip over those with in-use TQs.
2431 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2432 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2438 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2439 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2440 call = queue_First(&rx_freeCallQueue, rx_call);
2441 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2443 if (rx_stats_active)
2444 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2445 MUTEX_EXIT(&rx_freeCallQueue_lock);
2446 MUTEX_ENTER(&call->lock);
2447 CLEAR_CALL_QUEUE_LOCK(call);
2448 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2449 /* Now, if TQ wasn't cleared earlier, do it now. */
2450 rxi_WaitforTQBusy(call);
2451 if (call->flags & RX_CALL_TQ_CLEARME) {
2452 rxi_ClearTransmitQueue(call, 1);
2453 /*queue_Init(&call->tq);*/
2455 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2456 /* Bind the call to its connection structure */
2458 rxi_ResetCall(call, 1);
2461 call = rxi_Alloc(sizeof(struct rx_call));
2462 #ifdef RXDEBUG_PACKET
2463 call->allNextp = rx_allCallsp;
2464 rx_allCallsp = call;
2466 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2467 #else /* RXDEBUG_PACKET */
2468 rx_atomic_inc(&rx_stats.nCallStructs);
2469 #endif /* RXDEBUG_PACKET */
2471 MUTEX_EXIT(&rx_freeCallQueue_lock);
2472 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2473 MUTEX_ENTER(&call->lock);
2474 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2475 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2476 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2478 /* Initialize once-only items */
2479 queue_Init(&call->tq);
2480 queue_Init(&call->rq);
2481 queue_Init(&call->iovq);
2482 #ifdef RXDEBUG_PACKET
2483 call->rqc = call->tqc = call->iovqc = 0;
2484 #endif /* RXDEBUG_PACKET */
2485 /* Bind the call to its connection structure (prereq for reset) */
2487 rxi_ResetCall(call, 1);
2489 call->channel = channel;
2490 call->callNumber = &conn->callNumber[channel];
2491 call->rwind = conn->rwind[channel];
2492 call->twind = conn->twind[channel];
2493 /* Note that the next expected call number is retained (in
2494 * conn->callNumber[i]), even if we reallocate the call structure
2496 conn->call[channel] = call;
2497 /* if the channel's never been used (== 0), we should start at 1, otherwise
2498 * the call number is valid from the last time this channel was used */
2499 if (*call->callNumber == 0)
2500 *call->callNumber = 1;
2505 /* A call has been inactive long enough that so we can throw away
2506 * state, including the call structure, which is placed on the call
2509 * call->lock amd rx_refcnt_mutex are held upon entry.
2510 * haveCTLock is set when called from rxi_ReapConnections.
2513 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2515 int channel = call->channel;
2516 struct rx_connection *conn = call->conn;
2519 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2520 (*call->callNumber)++;
2522 * We are setting the state to RX_STATE_RESET to
2523 * ensure that no one else will attempt to use this
2524 * call once we drop the refcnt lock. We must drop
2525 * the refcnt lock before calling rxi_ResetCall
2526 * because it cannot be held across acquiring the
2527 * freepktQ lock. NewCall does the same.
2529 call->state = RX_STATE_RESET;
2530 MUTEX_EXIT(&rx_refcnt_mutex);
2531 rxi_ResetCall(call, 0);
2532 call->conn->call[channel] = (struct rx_call *)0;
2534 MUTEX_ENTER(&rx_freeCallQueue_lock);
2535 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2536 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2537 /* A call may be free even though its transmit queue is still in use.
2538 * Since we search the call list from head to tail, put busy calls at
2539 * the head of the list, and idle calls at the tail.
2541 if (call->flags & RX_CALL_TQ_BUSY)
2542 queue_Prepend(&rx_freeCallQueue, call);
2544 queue_Append(&rx_freeCallQueue, call);
2545 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2546 queue_Append(&rx_freeCallQueue, call);
2547 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2548 if (rx_stats_active)
2549 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2550 MUTEX_EXIT(&rx_freeCallQueue_lock);
2552 /* Destroy the connection if it was previously slated for
2553 * destruction, i.e. the Rx client code previously called
2554 * rx_DestroyConnection (client connections), or
2555 * rxi_ReapConnections called the same routine (server
2556 * connections). Only do this, however, if there are no
2557 * outstanding calls. Note that for fine grain locking, there appears
2558 * to be a deadlock in that rxi_FreeCall has a call locked and
2559 * DestroyConnectionNoLock locks each call in the conn. But note a
2560 * few lines up where we have removed this call from the conn.
2561 * If someone else destroys a connection, they either have no
2562 * call lock held or are going through this section of code.
2564 MUTEX_ENTER(&conn->conn_data_lock);
2565 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2566 MUTEX_ENTER(&rx_refcnt_mutex);
2568 MUTEX_EXIT(&rx_refcnt_mutex);
2569 MUTEX_EXIT(&conn->conn_data_lock);
2570 #ifdef RX_ENABLE_LOCKS
2572 rxi_DestroyConnectionNoLock(conn);
2574 rxi_DestroyConnection(conn);
2575 #else /* RX_ENABLE_LOCKS */
2576 rxi_DestroyConnection(conn);
2577 #endif /* RX_ENABLE_LOCKS */
2579 MUTEX_EXIT(&conn->conn_data_lock);
2581 MUTEX_ENTER(&rx_refcnt_mutex);
2584 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2585 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2588 rxi_Alloc(size_t size)
2592 if (rx_stats_active) {
2593 rx_atomic_add(&rxi_Allocsize, (int) size);
2594 rx_atomic_inc(&rxi_Alloccnt);
2598 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2599 afs_osi_Alloc_NoSleep(size);
2604 osi_Panic("rxi_Alloc error");
2610 rxi_Free(void *addr, size_t size)
2612 if (rx_stats_active) {
2613 rx_atomic_sub(&rxi_Allocsize, (int) size);
2614 rx_atomic_dec(&rxi_Alloccnt);
2616 osi_Free(addr, size);
2620 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2622 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2623 struct rx_peer *next = NULL;
2627 MUTEX_ENTER(&rx_peerHashTable_lock);
2629 peer_ptr = &rx_peerHashTable[0];
2630 peer_end = &rx_peerHashTable[rx_hashTableSize];
2633 for ( ; peer_ptr < peer_end; peer_ptr++) {
2636 for ( ; peer; peer = next) {
2638 if (host == peer->host)
2643 hashIndex = PEER_HASH(host, port);
2644 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2645 if ((peer->host == host) && (peer->port == port))
2650 MUTEX_ENTER(&rx_peerHashTable_lock);
2655 MUTEX_EXIT(&rx_peerHashTable_lock);
2657 MUTEX_ENTER(&peer->peer_lock);
2658 /* We don't handle dropping below min, so don't */
2659 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2660 peer->ifMTU=MIN(mtu, peer->ifMTU);
2661 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2662 /* if we tweaked this down, need to tune our peer MTU too */
2663 peer->MTU = MIN(peer->MTU, peer->natMTU);
2664 /* if we discovered a sub-1500 mtu, degrade */
2665 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2666 peer->maxDgramPackets = 1;
2667 /* We no longer have valid peer packet information */
2668 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2669 peer->maxPacketSize = 0;
2670 MUTEX_EXIT(&peer->peer_lock);
2672 MUTEX_ENTER(&rx_peerHashTable_lock);
2674 if (host && !port) {
2676 /* pick up where we left off */
2680 MUTEX_EXIT(&rx_peerHashTable_lock);
2683 /* Find the peer process represented by the supplied (host,port)
2684 * combination. If there is no appropriate active peer structure, a
2685 * new one will be allocated and initialized
2686 * The origPeer, if set, is a pointer to a peer structure on which the
2687 * refcount will be be decremented. This is used to replace the peer
2688 * structure hanging off a connection structure */
2690 rxi_FindPeer(afs_uint32 host, u_short port,
2691 struct rx_peer *origPeer, int create)
2695 hashIndex = PEER_HASH(host, port);
2696 MUTEX_ENTER(&rx_peerHashTable_lock);
2697 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2698 if ((pp->host == host) && (pp->port == port))
2703 pp = rxi_AllocPeer(); /* This bzero's *pp */
2704 pp->host = host; /* set here or in InitPeerParams is zero */
2706 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2707 queue_Init(&pp->congestionQueue);
2708 queue_Init(&pp->rpcStats);
2709 pp->next = rx_peerHashTable[hashIndex];
2710 rx_peerHashTable[hashIndex] = pp;
2711 rxi_InitPeerParams(pp);
2712 if (rx_stats_active)
2713 rx_atomic_inc(&rx_stats.nPeerStructs);
2720 origPeer->refCount--;
2721 MUTEX_EXIT(&rx_peerHashTable_lock);
2726 /* Find the connection at (host, port) started at epoch, and with the
2727 * given connection id. Creates the server connection if necessary.
2728 * The type specifies whether a client connection or a server
2729 * connection is desired. In both cases, (host, port) specify the
2730 * peer's (host, pair) pair. Client connections are not made
2731 * automatically by this routine. The parameter socket gives the
2732 * socket descriptor on which the packet was received. This is used,
2733 * in the case of server connections, to check that *new* connections
2734 * come via a valid (port, serviceId). Finally, the securityIndex
2735 * parameter must match the existing index for the connection. If a
2736 * server connection is created, it will be created using the supplied
2737 * index, if the index is valid for this service */
2738 struct rx_connection *
2739 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2740 u_short port, u_short serviceId, afs_uint32 cid,
2741 afs_uint32 epoch, int type, u_int securityIndex)
2743 int hashindex, flag, i;
2744 struct rx_connection *conn;
2745 hashindex = CONN_HASH(host, port, cid, epoch, type);
2746 MUTEX_ENTER(&rx_connHashTable_lock);
2747 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2748 rx_connHashTable[hashindex],
2751 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2752 && (epoch == conn->epoch)) {
2753 struct rx_peer *pp = conn->peer;
2754 if (securityIndex != conn->securityIndex) {
2755 /* this isn't supposed to happen, but someone could forge a packet
2756 * like this, and there seems to be some CM bug that makes this
2757 * happen from time to time -- in which case, the fileserver
2759 MUTEX_EXIT(&rx_connHashTable_lock);
2760 return (struct rx_connection *)0;
2762 if (pp->host == host && pp->port == port)
2764 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2766 /* So what happens when it's a callback connection? */
2767 if ( /*type == RX_CLIENT_CONNECTION && */
2768 (conn->epoch & 0x80000000))
2772 /* the connection rxLastConn that was used the last time is not the
2773 ** one we are looking for now. Hence, start searching in the hash */
2775 conn = rx_connHashTable[hashindex];
2780 struct rx_service *service;
2781 if (type == RX_CLIENT_CONNECTION) {
2782 MUTEX_EXIT(&rx_connHashTable_lock);
2783 return (struct rx_connection *)0;
2785 service = rxi_FindService(socket, serviceId);
2786 if (!service || (securityIndex >= service->nSecurityObjects)
2787 || (service->securityObjects[securityIndex] == 0)) {
2788 MUTEX_EXIT(&rx_connHashTable_lock);
2789 return (struct rx_connection *)0;
2791 conn = rxi_AllocConnection(); /* This bzero's the connection */
2792 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2793 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2794 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2795 conn->next = rx_connHashTable[hashindex];
2796 rx_connHashTable[hashindex] = conn;
2797 conn->peer = rxi_FindPeer(host, port, 0, 1);
2798 conn->type = RX_SERVER_CONNECTION;
2799 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2800 conn->epoch = epoch;
2801 conn->cid = cid & RX_CIDMASK;
2802 /* conn->serial = conn->lastSerial = 0; */
2803 /* conn->timeout = 0; */
2804 conn->ackRate = RX_FAST_ACK_RATE;
2805 conn->service = service;
2806 conn->serviceId = serviceId;
2807 conn->securityIndex = securityIndex;
2808 conn->securityObject = service->securityObjects[securityIndex];
2809 conn->nSpecific = 0;
2810 conn->specific = NULL;
2811 rx_SetConnDeadTime(conn, service->connDeadTime);
2812 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2813 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2814 for (i = 0; i < RX_MAXCALLS; i++) {
2815 conn->twind[i] = rx_initSendWindow;
2816 conn->rwind[i] = rx_initReceiveWindow;
2818 /* Notify security object of the new connection */
2819 RXS_NewConnection(conn->securityObject, conn);
2820 /* XXXX Connection timeout? */
2821 if (service->newConnProc)
2822 (*service->newConnProc) (conn);
2823 if (rx_stats_active)
2824 rx_atomic_inc(&rx_stats.nServerConns);
2827 MUTEX_ENTER(&rx_refcnt_mutex);
2829 MUTEX_EXIT(&rx_refcnt_mutex);
2831 rxLastConn = conn; /* store this connection as the last conn used */
2832 MUTEX_EXIT(&rx_connHashTable_lock);
2837 * Timeout a call on a busy call channel if appropriate.
2839 * @param[in] call The busy call.
2841 * @pre 'call' is marked as busy (namely,
2842 * call->conn->lastBusy[call->channel] != 0)
2844 * @pre call->lock is held
2845 * @pre rxi_busyChannelError is nonzero
2847 * @note call->lock is dropped and reacquired
2850 rxi_CheckBusy(struct rx_call *call)
2852 struct rx_connection *conn = call->conn;
2853 int channel = call->channel;
2854 int freechannel = 0;
2856 afs_uint32 callNumber = *call->callNumber;
2858 MUTEX_EXIT(&call->lock);
2860 MUTEX_ENTER(&conn->conn_call_lock);
2862 /* Are there any other call slots on this conn that we should try? Look for
2863 * slots that are empty and are either non-busy, or were marked as busy
2864 * longer than conn->secondsUntilDead seconds before this call started. */
2866 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
2868 /* only look at channels that aren't us */
2872 if (conn->lastBusy[i]) {
2873 /* if this channel looked busy too recently, don't look at it */
2874 if (conn->lastBusy[i] >= call->startTime.sec) {
2877 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
2882 if (conn->call[i]) {
2883 struct rx_call *tcall = conn->call[i];
2884 MUTEX_ENTER(&tcall->lock);
2885 if (tcall->state == RX_STATE_DALLY) {
2888 MUTEX_EXIT(&tcall->lock);
2894 MUTEX_EXIT(&conn->conn_call_lock);
2896 MUTEX_ENTER(&call->lock);
2898 /* Since the call->lock and conn->conn_call_lock have been released it is
2899 * possible that (1) the call may no longer be busy and/or (2) the call may
2900 * have been reused by another waiting thread. Therefore, we must confirm
2901 * that the call state has not changed when deciding whether or not to
2902 * force this application thread to retry by forcing a Timeout error. */
2904 if (freechannel && *call->callNumber == callNumber &&
2905 (call->flags & RX_CALL_PEER_BUSY)) {
2906 /* Since 'freechannel' is set, there exists another channel in this
2907 * rx_conn that the application thread might be able to use. We know
2908 * that we have the correct call since callNumber is unchanged, and we
2909 * know that the call is still busy. So, set the call error state to
2910 * rxi_busyChannelError so the application can retry the request,
2911 * presumably on a less-busy call channel. */
2913 rxi_CallError(call, rxi_busyChannelError);
2917 /* There are two packet tracing routines available for testing and monitoring
2918 * Rx. One is called just after every packet is received and the other is
2919 * called just before every packet is sent. Received packets, have had their
2920 * headers decoded, and packets to be sent have not yet had their headers
2921 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2922 * containing the network address. Both can be modified. The return value, if
2923 * non-zero, indicates that the packet should be dropped. */
2925 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2926 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2928 /* A packet has been received off the interface. Np is the packet, socket is
2929 * the socket number it was received from (useful in determining which service
2930 * this packet corresponds to), and (host, port) reflect the host,port of the
2931 * sender. This call returns the packet to the caller if it is finished with
2932 * it, rather than de-allocating it, just as a small performance hack */
2935 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2936 afs_uint32 host, u_short port, int *tnop,
2937 struct rx_call **newcallp)
2939 struct rx_call *call;
2940 struct rx_connection *conn;
2942 afs_uint32 currentCallNumber;
2948 struct rx_packet *tnp;
2951 /* We don't print out the packet until now because (1) the time may not be
2952 * accurate enough until now in the lwp implementation (rx_Listener only gets
2953 * the time after the packet is read) and (2) from a protocol point of view,
2954 * this is the first time the packet has been seen */
2955 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2956 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2957 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2958 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2959 np->header.epoch, np->header.cid, np->header.callNumber,
2960 np->header.seq, np->header.flags, np));
2963 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2964 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2967 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2968 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2971 /* If an input tracer function is defined, call it with the packet and
2972 * network address. Note this function may modify its arguments. */
2973 if (rx_justReceived) {
2974 struct sockaddr_in addr;
2976 addr.sin_family = AF_INET;
2977 addr.sin_port = port;
2978 addr.sin_addr.s_addr = host;
2979 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2980 addr.sin_len = sizeof(addr);
2981 #endif /* AFS_OSF_ENV */
2982 drop = (*rx_justReceived) (np, &addr);
2983 /* drop packet if return value is non-zero */
2986 port = addr.sin_port; /* in case fcn changed addr */
2987 host = addr.sin_addr.s_addr;
2991 /* If packet was not sent by the client, then *we* must be the client */
2992 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2993 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2995 /* Find the connection (or fabricate one, if we're the server & if
2996 * necessary) associated with this packet */
2998 rxi_FindConnection(socket, host, port, np->header.serviceId,
2999 np->header.cid, np->header.epoch, type,
3000 np->header.securityIndex);
3003 /* If no connection found or fabricated, just ignore the packet.
3004 * (An argument could be made for sending an abort packet for
3009 MUTEX_ENTER(&conn->conn_data_lock);
3010 if (conn->maxSerial < np->header.serial)
3011 conn->maxSerial = np->header.serial;
3012 MUTEX_EXIT(&conn->conn_data_lock);
3014 /* If the connection is in an error state, send an abort packet and ignore
3015 * the incoming packet */
3017 /* Don't respond to an abort packet--we don't want loops! */
3018 MUTEX_ENTER(&conn->conn_data_lock);
3019 if (np->header.type != RX_PACKET_TYPE_ABORT)
3020 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3021 MUTEX_ENTER(&rx_refcnt_mutex);
3023 MUTEX_EXIT(&rx_refcnt_mutex);
3024 MUTEX_EXIT(&conn->conn_data_lock);
3028 /* Check for connection-only requests (i.e. not call specific). */
3029 if (np->header.callNumber == 0) {
3030 switch (np->header.type) {
3031 case RX_PACKET_TYPE_ABORT: {
3032 /* What if the supplied error is zero? */
3033 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3034 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3035 rxi_ConnectionError(conn, errcode);
3036 MUTEX_ENTER(&rx_refcnt_mutex);
3038 MUTEX_EXIT(&rx_refcnt_mutex);
3041 case RX_PACKET_TYPE_CHALLENGE:
3042 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3043 MUTEX_ENTER(&rx_refcnt_mutex);
3045 MUTEX_EXIT(&rx_refcnt_mutex);
3047 case RX_PACKET_TYPE_RESPONSE:
3048 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3049 MUTEX_ENTER(&rx_refcnt_mutex);
3051 MUTEX_EXIT(&rx_refcnt_mutex);
3053 case RX_PACKET_TYPE_PARAMS:
3054 case RX_PACKET_TYPE_PARAMS + 1:
3055 case RX_PACKET_TYPE_PARAMS + 2:
3056 /* ignore these packet types for now */
3057 MUTEX_ENTER(&rx_refcnt_mutex);
3059 MUTEX_EXIT(&rx_refcnt_mutex);
3064 /* Should not reach here, unless the peer is broken: send an
3066 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3067 MUTEX_ENTER(&conn->conn_data_lock);
3068 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3069 MUTEX_ENTER(&rx_refcnt_mutex);
3071 MUTEX_EXIT(&rx_refcnt_mutex);
3072 MUTEX_EXIT(&conn->conn_data_lock);
3077 channel = np->header.cid & RX_CHANNELMASK;
3078 call = conn->call[channel];
3079 #ifdef RX_ENABLE_LOCKS
3081 MUTEX_ENTER(&call->lock);
3082 /* Test to see if call struct is still attached to conn. */
3083 if (call != conn->call[channel]) {
3085 MUTEX_EXIT(&call->lock);
3086 if (type == RX_SERVER_CONNECTION) {
3087 call = conn->call[channel];
3088 /* If we started with no call attached and there is one now,
3089 * another thread is also running this routine and has gotten
3090 * the connection channel. We should drop this packet in the tests
3091 * below. If there was a call on this connection and it's now
3092 * gone, then we'll be making a new call below.
3093 * If there was previously a call and it's now different then
3094 * the old call was freed and another thread running this routine
3095 * has created a call on this channel. One of these two threads
3096 * has a packet for the old call and the code below handles those
3100 MUTEX_ENTER(&call->lock);
3102 /* This packet can't be for this call. If the new call address is
3103 * 0 then no call is running on this channel. If there is a call
3104 * then, since this is a client connection we're getting data for
3105 * it must be for the previous call.
3107 if (rx_stats_active)
3108 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3109 MUTEX_ENTER(&rx_refcnt_mutex);
3111 MUTEX_EXIT(&rx_refcnt_mutex);
3116 currentCallNumber = conn->callNumber[channel];
3118 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3119 if (np->header.callNumber < currentCallNumber) {
3120 if (rx_stats_active)
3121 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3122 #ifdef RX_ENABLE_LOCKS
3124 MUTEX_EXIT(&call->lock);
3126 MUTEX_ENTER(&rx_refcnt_mutex);
3128 MUTEX_EXIT(&rx_refcnt_mutex);
3132 MUTEX_ENTER(&conn->conn_call_lock);
3133 call = rxi_NewCall(conn, channel);
3134 MUTEX_EXIT(&conn->conn_call_lock);
3135 *call->callNumber = np->header.callNumber;
3137 if (np->header.callNumber == 0)
3138 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%.06d len %d\n",
3139 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3140 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3141 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
3143 call->state = RX_STATE_PRECALL;
3144 clock_GetTime(&call->queueTime);
3145 hzero(call->bytesSent);
3146 hzero(call->bytesRcvd);
3148 * If the number of queued calls exceeds the overload
3149 * threshold then abort this call.
3151 if ((rx_BusyThreshold > 0) &&
3152 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3153 struct rx_packet *tp;
3155 rxi_CallError(call, rx_BusyError);
3156 tp = rxi_SendCallAbort(call, np, 1, 0);
3157 MUTEX_EXIT(&call->lock);
3158 MUTEX_ENTER(&rx_refcnt_mutex);
3160 MUTEX_EXIT(&rx_refcnt_mutex);
3161 if (rx_stats_active)
3162 rx_atomic_inc(&rx_stats.nBusies);
3165 rxi_KeepAliveOn(call);
3166 } else if (np->header.callNumber != currentCallNumber) {
3167 /* Wait until the transmit queue is idle before deciding
3168 * whether to reset the current call. Chances are that the
3169 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3172 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3173 if (call->state == RX_STATE_ACTIVE) {
3174 rxi_WaitforTQBusy(call);
3176 * If we entered error state while waiting,
3177 * must call rxi_CallError to permit rxi_ResetCall
3178 * to processed when the tqWaiter count hits zero.
3181 rxi_CallError(call, call->error);
3182 MUTEX_EXIT(&call->lock);
3183 MUTEX_ENTER(&rx_refcnt_mutex);
3185 MUTEX_EXIT(&rx_refcnt_mutex);
3189 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3190 /* If the new call cannot be taken right now send a busy and set
3191 * the error condition in this call, so that it terminates as
3192 * quickly as possible */
3193 if (call->state == RX_STATE_ACTIVE) {
3194 struct rx_packet *tp;
3196 rxi_CallError(call, RX_CALL_DEAD);
3197 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3199 MUTEX_EXIT(&call->lock);
3200 MUTEX_ENTER(&rx_refcnt_mutex);
3202 MUTEX_EXIT(&rx_refcnt_mutex);
3205 rxi_ResetCall(call, 0);
3206 *call->callNumber = np->header.callNumber;
3208 if (np->header.callNumber == 0)
3209 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" resend %d.%06d len %d\n",
3210 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3211 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3212 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3214 call->state = RX_STATE_PRECALL;
3215 clock_GetTime(&call->queueTime);
3216 hzero(call->bytesSent);
3217 hzero(call->bytesRcvd);
3219 * If the number of queued calls exceeds the overload
3220 * threshold then abort this call.
3222 if ((rx_BusyThreshold > 0) &&
3223 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3224 struct rx_packet *tp;
3226 rxi_CallError(call, rx_BusyError);
3227 tp = rxi_SendCallAbort(call, np, 1, 0);
3228 MUTEX_EXIT(&call->lock);
3229 MUTEX_ENTER(&rx_refcnt_mutex);
3231 MUTEX_EXIT(&rx_refcnt_mutex);
3232 if (rx_stats_active)
3233 rx_atomic_inc(&rx_stats.nBusies);
3236 rxi_KeepAliveOn(call);
3238 /* Continuing call; do nothing here. */
3240 } else { /* we're the client */
3241 /* Ignore all incoming acknowledgements for calls in DALLY state */
3242 if (call && (call->state == RX_STATE_DALLY)
3243 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3244 if (rx_stats_active)
3245 rx_atomic_inc(&rx_stats.ignorePacketDally);
3246 #ifdef RX_ENABLE_LOCKS
3248 MUTEX_EXIT(&call->lock);
3251 MUTEX_ENTER(&rx_refcnt_mutex);
3253 MUTEX_EXIT(&rx_refcnt_mutex);
3257 /* Ignore anything that's not relevant to the current call. If there
3258 * isn't a current call, then no packet is relevant. */
3259 if (!call || (np->header.callNumber != currentCallNumber)) {
3260 if (rx_stats_active)
3261 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3262 #ifdef RX_ENABLE_LOCKS
3264 MUTEX_EXIT(&call->lock);
3267 MUTEX_ENTER(&rx_refcnt_mutex);
3269 MUTEX_EXIT(&rx_refcnt_mutex);
3272 /* If the service security object index stamped in the packet does not
3273 * match the connection's security index, ignore the packet */
3274 if (np->header.securityIndex != conn->securityIndex) {
3275 #ifdef RX_ENABLE_LOCKS
3276 MUTEX_EXIT(&call->lock);
3278 MUTEX_ENTER(&rx_refcnt_mutex);
3280 MUTEX_EXIT(&rx_refcnt_mutex);
3284 /* If we're receiving the response, then all transmit packets are
3285 * implicitly acknowledged. Get rid of them. */
3286 if (np->header.type == RX_PACKET_TYPE_DATA) {
3287 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3288 /* XXX Hack. Because we must release the global rx lock when
3289 * sending packets (osi_NetSend) we drop all acks while we're
3290 * traversing the tq in rxi_Start sending packets out because
3291 * packets may move to the freePacketQueue as result of being here!
3292 * So we drop these packets until we're safely out of the
3293 * traversing. Really ugly!
3294 * For fine grain RX locking, we set the acked field in the
3295 * packets and let rxi_Start remove them from the transmit queue.
3297 if (call->flags & RX_CALL_TQ_BUSY) {
3298 #ifdef RX_ENABLE_LOCKS
3299 rxi_SetAcksInTransmitQueue(call);
3301 MUTEX_ENTER(&rx_refcnt_mutex);
3303 MUTEX_EXIT(&rx_refcnt_mutex);
3304 return np; /* xmitting; drop packet */
3307 rxi_ClearTransmitQueue(call, 0);
3309 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3310 rxi_ClearTransmitQueue(call, 0);
3311 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3313 if (np->header.type == RX_PACKET_TYPE_ACK) {
3314 /* now check to see if this is an ack packet acknowledging that the
3315 * server actually *lost* some hard-acked data. If this happens we
3316 * ignore this packet, as it may indicate that the server restarted in
3317 * the middle of a call. It is also possible that this is an old ack
3318 * packet. We don't abort the connection in this case, because this
3319 * *might* just be an old ack packet. The right way to detect a server
3320 * restart in the midst of a call is to notice that the server epoch
3322 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3323 * XXX unacknowledged. I think that this is off-by-one, but
3324 * XXX I don't dare change it just yet, since it will
3325 * XXX interact badly with the server-restart detection
3326 * XXX code in receiveackpacket. */
3327 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3328 if (rx_stats_active)
3329 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3330 MUTEX_EXIT(&call->lock);
3331 MUTEX_ENTER(&rx_refcnt_mutex);
3333 MUTEX_EXIT(&rx_refcnt_mutex);
3337 } /* else not a data packet */
3340 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3341 /* Set remote user defined status from packet */
3342 call->remoteStatus = np->header.userStatus;
3344 /* Note the gap between the expected next packet and the actual
3345 * packet that arrived, when the new packet has a smaller serial number
3346 * than expected. Rioses frequently reorder packets all by themselves,
3347 * so this will be quite important with very large window sizes.
3348 * Skew is checked against 0 here to avoid any dependence on the type of
3349 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3351 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3352 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3353 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3355 MUTEX_ENTER(&conn->conn_data_lock);
3356 skew = conn->lastSerial - np->header.serial;
3357 conn->lastSerial = np->header.serial;
3358 MUTEX_EXIT(&conn->conn_data_lock);
3360 struct rx_peer *peer;
3362 if (skew > peer->inPacketSkew) {
3363 dpf(("*** In skew changed from %d to %d\n",
3364 peer->inPacketSkew, skew));
3365 peer->inPacketSkew = skew;
3369 /* Now do packet type-specific processing */
3370 switch (np->header.type) {
3371 case RX_PACKET_TYPE_DATA:
3372 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3375 case RX_PACKET_TYPE_ACK:
3376 /* Respond immediately to ack packets requesting acknowledgement
3378 if (np->header.flags & RX_REQUEST_ACK) {
3380 (void)rxi_SendCallAbort(call, 0, 1, 0);
3382 (void)rxi_SendAck(call, 0, np->header.serial,
3383 RX_ACK_PING_RESPONSE, 1);
3385 np = rxi_ReceiveAckPacket(call, np, 1);
3387 case RX_PACKET_TYPE_ABORT: {
3388 /* An abort packet: reset the call, passing the error up to the user. */
3389 /* What if error is zero? */
3390 /* What if the error is -1? the application will treat it as a timeout. */
3391 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3392 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3393 rxi_CallError(call, errdata);
3394 MUTEX_EXIT(&call->lock);
3395 MUTEX_ENTER(&rx_refcnt_mutex);
3397 MUTEX_EXIT(&rx_refcnt_mutex);
3398 return np; /* xmitting; drop packet */
3400 case RX_PACKET_TYPE_BUSY: {
3401 struct clock busyTime;
3403 clock_GetTime(&busyTime);
3405 MUTEX_EXIT(&call->lock);
3407 MUTEX_ENTER(&conn->conn_call_lock);
3408 MUTEX_ENTER(&call->lock);
3409 conn->lastBusy[call->channel] = busyTime.sec;
3410 call->flags |= RX_CALL_PEER_BUSY;
3411 MUTEX_EXIT(&call->lock);
3412 MUTEX_EXIT(&conn->conn_call_lock);
3414 MUTEX_ENTER(&rx_refcnt_mutex);
3416 MUTEX_EXIT(&rx_refcnt_mutex);
3420 case RX_PACKET_TYPE_ACKALL:
3421 /* All packets acknowledged, so we can drop all packets previously
3422 * readied for sending */
3423 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3424 /* XXX Hack. We because we can't release the global rx lock when
3425 * sending packets (osi_NetSend) we drop all ack pkts while we're
3426 * traversing the tq in rxi_Start sending packets out because
3427 * packets may move to the freePacketQueue as result of being
3428 * here! So we drop these packets until we're safely out of the
3429 * traversing. Really ugly!
3430 * For fine grain RX locking, we set the acked field in the packets
3431 * and let rxi_Start remove the packets from the transmit queue.
3433 if (call->flags & RX_CALL_TQ_BUSY) {
3434 #ifdef RX_ENABLE_LOCKS
3435 rxi_SetAcksInTransmitQueue(call);
3437 #else /* RX_ENABLE_LOCKS */
3438 MUTEX_EXIT(&call->lock);
3439 MUTEX_ENTER(&rx_refcnt_mutex);
3441 MUTEX_EXIT(&rx_refcnt_mutex);
3442 return np; /* xmitting; drop packet */
3443 #endif /* RX_ENABLE_LOCKS */
3445 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3446 rxi_ClearTransmitQueue(call, 0);
3449 /* Should not reach here, unless the peer is broken: send an abort
3451 rxi_CallError(call, RX_PROTOCOL_ERROR);
3452 np = rxi_SendCallAbort(call, np, 1, 0);
3455 /* Note when this last legitimate packet was received, for keep-alive
3456 * processing. Note, we delay getting the time until now in the hope that
3457 * the packet will be delivered to the user before any get time is required
3458 * (if not, then the time won't actually be re-evaluated here). */
3459 call->lastReceiveTime = clock_Sec();
3460 /* we've received a legit packet, so the channel is not busy */
3461 call->flags &= ~RX_CALL_PEER_BUSY;
3462 MUTEX_EXIT(&call->lock);
3463 MUTEX_ENTER(&rx_refcnt_mutex);
3465 MUTEX_EXIT(&rx_refcnt_mutex);
3469 /* return true if this is an "interesting" connection from the point of view
3470 of someone trying to debug the system */
3472 rxi_IsConnInteresting(struct rx_connection *aconn)
3475 struct rx_call *tcall;
3477 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3480 for (i = 0; i < RX_MAXCALLS; i++) {
3481 tcall = aconn->call[i];
3483 if ((tcall->state == RX_STATE_PRECALL)
3484 || (tcall->state == RX_STATE_ACTIVE))
3486 if ((tcall->mode == RX_MODE_SENDING)
3487 || (tcall->mode == RX_MODE_RECEIVING))
3495 /* if this is one of the last few packets AND it wouldn't be used by the
3496 receiving call to immediately satisfy a read request, then drop it on
3497 the floor, since accepting it might prevent a lock-holding thread from
3498 making progress in its reading. If a call has been cleared while in
3499 the precall state then ignore all subsequent packets until the call
3500 is assigned to a thread. */
3503 TooLow(struct rx_packet *ap, struct rx_call *acall)
3507 MUTEX_ENTER(&rx_quota_mutex);
3508 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3509 && (acall->state == RX_STATE_PRECALL))
3510 || ((rx_nFreePackets < rxi_dataQuota + 2)
3511 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3512 && (acall->flags & RX_CALL_READER_WAIT)))) {
3515 MUTEX_EXIT(&rx_quota_mutex);
3521 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3523 struct rx_connection *conn = arg1;
3524 struct rx_call *acall = arg2;
3525 struct rx_call *call = acall;
3526 struct clock when, now;
3529 MUTEX_ENTER(&conn->conn_data_lock);
3530 conn->checkReachEvent = NULL;
3531 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3533 MUTEX_ENTER(&rx_refcnt_mutex);
3535 MUTEX_EXIT(&rx_refcnt_mutex);
3537 MUTEX_EXIT(&conn->conn_data_lock);
3541 MUTEX_ENTER(&conn->conn_call_lock);
3542 MUTEX_ENTER(&conn->conn_data_lock);
3543 for (i = 0; i < RX_MAXCALLS; i++) {
3544 struct rx_call *tc = conn->call[i];
3545 if (tc && tc->state == RX_STATE_PRECALL) {
3551 /* Indicate that rxi_CheckReachEvent is no longer running by
3552 * clearing the flag. Must be atomic under conn_data_lock to
3553 * avoid a new call slipping by: rxi_CheckConnReach holds
3554 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3556 conn->flags &= ~RX_CONN_ATTACHWAIT;
3557 MUTEX_EXIT(&conn->conn_data_lock);
3558 MUTEX_EXIT(&conn->conn_call_lock);
3563 MUTEX_ENTER(&call->lock);
3564 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3566 MUTEX_EXIT(&call->lock);
3568 clock_GetTime(&now);
3570 when.sec += RX_CHECKREACH_TIMEOUT;
3571 MUTEX_ENTER(&conn->conn_data_lock);
3572 if (!conn->checkReachEvent) {
3573 MUTEX_ENTER(&rx_refcnt_mutex);
3575 MUTEX_EXIT(&rx_refcnt_mutex);
3576 conn->checkReachEvent =
3577 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3580 MUTEX_EXIT(&conn->conn_data_lock);
3586 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3588 struct rx_service *service = conn->service;
3589 struct rx_peer *peer = conn->peer;
3590 afs_uint32 now, lastReach;
3592 if (service->checkReach == 0)
3596 MUTEX_ENTER(&peer->peer_lock);
3597 lastReach = peer->lastReachTime;
3598 MUTEX_EXIT(&peer->peer_lock);
3599 if (now - lastReach < RX_CHECKREACH_TTL)
3602 MUTEX_ENTER(&conn->conn_data_lock);
3603 if (conn->flags & RX_CONN_ATTACHWAIT) {
3604 MUTEX_EXIT(&conn->conn_data_lock);
3607 conn->flags |= RX_CONN_ATTACHWAIT;
3608 MUTEX_EXIT(&conn->conn_data_lock);
3609 if (!conn->checkReachEvent)
3610 rxi_CheckReachEvent(NULL, conn, call);
3615 /* try to attach call, if authentication is complete */
3617 TryAttach(struct rx_call *acall, osi_socket socket,
3618 int *tnop, struct rx_call **newcallp,
3621 struct rx_connection *conn = acall->conn;
3623 if (conn->type == RX_SERVER_CONNECTION
3624 && acall->state == RX_STATE_PRECALL) {
3625 /* Don't attach until we have any req'd. authentication. */
3626 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3627 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3628 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3629 /* Note: this does not necessarily succeed; there
3630 * may not any proc available
3633 rxi_ChallengeOn(acall->conn);
3638 /* A data packet has been received off the interface. This packet is
3639 * appropriate to the call (the call is in the right state, etc.). This
3640 * routine can return a packet to the caller, for re-use */
3643 rxi_ReceiveDataPacket(struct rx_call *call,
3644 struct rx_packet *np, int istack,
3645 osi_socket socket, afs_uint32 host, u_short port,
3646 int *tnop, struct rx_call **newcallp)
3648 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3653 afs_uint32 serial=0, flags=0;
3655 struct rx_packet *tnp;
3656 struct clock when, now;
3657 if (rx_stats_active)
3658 rx_atomic_inc(&rx_stats.dataPacketsRead);
3661 /* If there are no packet buffers, drop this new packet, unless we can find
3662 * packet buffers from inactive calls */
3664 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3665 MUTEX_ENTER(&rx_freePktQ_lock);
3666 rxi_NeedMorePackets = TRUE;
3667 MUTEX_EXIT(&rx_freePktQ_lock);
3668 if (rx_stats_active)
3669 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3670 call->rprev = np->header.serial;
3671 rxi_calltrace(RX_TRACE_DROP, call);
3672 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3674 rxi_ClearReceiveQueue(call);
3675 clock_GetTime(&now);
3677 clock_Add(&when, &rx_softAckDelay);
3678 if (!call->delayedAckEvent
3679 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3680 rxevent_Cancel(call->delayedAckEvent, call,
3681 RX_CALL_REFCOUNT_DELAY);
3682 MUTEX_ENTER(&rx_refcnt_mutex);
3683 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3684 MUTEX_EXIT(&rx_refcnt_mutex);
3686 call->delayedAckEvent =
3687 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3689 /* we've damaged this call already, might as well do it in. */
3695 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3696 * packet is one of several packets transmitted as a single
3697 * datagram. Do not send any soft or hard acks until all packets
3698 * in a jumbogram have been processed. Send negative acks right away.
3700 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3701 /* tnp is non-null when there are more packets in the
3702 * current jumbo gram */
3709 seq = np->header.seq;
3710 serial = np->header.serial;
3711 flags = np->header.flags;
3713 /* If the call is in an error state, send an abort message */
3715 return rxi_SendCallAbort(call, np, istack, 0);
3717 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3718 * AFS 3.5 jumbogram. */