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;
146 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
147 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
149 #if !defined(offsetof)
150 #include <stddef.h> /* for definition of offsetof() */
153 #ifdef RX_ENABLE_LOCKS
154 afs_kmutex_t rx_atomic_mutex;
157 #ifdef AFS_PTHREAD_ENV
160 * Use procedural initialization of mutexes/condition variables
164 extern afs_kmutex_t rx_quota_mutex;
165 extern afs_kmutex_t rx_pthread_mutex;
166 extern afs_kmutex_t rx_packets_mutex;
167 extern afs_kmutex_t rx_refcnt_mutex;
168 extern afs_kmutex_t des_init_mutex;
169 extern afs_kmutex_t des_random_mutex;
170 extern afs_kmutex_t rx_clock_mutex;
171 extern afs_kmutex_t rxi_connCacheMutex;
172 extern afs_kmutex_t rx_event_mutex;
173 extern afs_kmutex_t osi_malloc_mutex;
174 extern afs_kmutex_t event_handler_mutex;
175 extern afs_kmutex_t listener_mutex;
176 extern afs_kmutex_t rx_if_init_mutex;
177 extern afs_kmutex_t rx_if_mutex;
178 extern afs_kmutex_t rxkad_client_uid_mutex;
179 extern afs_kmutex_t rxkad_random_mutex;
181 extern afs_kcondvar_t rx_event_handler_cond;
182 extern afs_kcondvar_t rx_listener_cond;
184 static afs_kmutex_t epoch_mutex;
185 static afs_kmutex_t rx_init_mutex;
186 static afs_kmutex_t rx_debug_mutex;
187 static afs_kmutex_t rx_rpc_stats;
190 rxi_InitPthread(void)
192 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
193 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
194 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
195 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
196 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
197 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
198 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
199 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
200 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
201 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
202 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
203 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
204 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
205 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
206 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
207 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
208 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
209 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
210 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
212 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
213 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
215 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
216 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
218 rxkad_global_stats_init();
220 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
222 #ifdef RX_ENABLE_LOCKS
225 #endif /* RX_LOCKS_DB */
226 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
229 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
231 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
233 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
235 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
236 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
237 #endif /* RX_ENABLE_LOCKS */
240 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
241 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
243 * The rx_stats_mutex mutex protects the following global variables:
244 * rxi_lowConnRefCount
245 * rxi_lowPeerRefCount
254 * The rx_quota_mutex mutex protects the following global variables:
262 * The rx_freePktQ_lock protects the following global variables:
267 * The rx_packets_mutex mutex protects the following global variables:
275 * The rx_pthread_mutex mutex protects the following global variables:
276 * rxi_fcfs_thread_num
279 #define INIT_PTHREAD_LOCKS
283 /* Variables for handling the minProcs implementation. availProcs gives the
284 * number of threads available in the pool at this moment (not counting dudes
285 * executing right now). totalMin gives the total number of procs required
286 * for handling all minProcs requests. minDeficit is a dynamic variable
287 * tracking the # of procs required to satisfy all of the remaining minProcs
289 * For fine grain locking to work, the quota check and the reservation of
290 * a server thread has to come while rxi_availProcs and rxi_minDeficit
291 * are locked. To this end, the code has been modified under #ifdef
292 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
293 * same time. A new function, ReturnToServerPool() returns the allocation.
295 * A call can be on several queue's (but only one at a time). When
296 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
297 * that no one else is touching the queue. To this end, we store the address
298 * of the queue lock in the call structure (under the call lock) when we
299 * put the call on a queue, and we clear the call_queue_lock when the
300 * call is removed from a queue (once the call lock has been obtained).
301 * This allows rxi_ResetCall to safely synchronize with others wishing
302 * to manipulate the queue.
305 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
306 static afs_kmutex_t rx_rpc_stats;
307 void rxi_StartUnlocked(struct rxevent *event, void *call,
308 void *arg1, int istack);
311 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
312 ** pretty good that the next packet coming in is from the same connection
313 ** as the last packet, since we're send multiple packets in a transmit window.
315 struct rx_connection *rxLastConn = 0;
317 #ifdef RX_ENABLE_LOCKS
318 /* The locking hierarchy for rx fine grain locking is composed of these
321 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
322 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
323 * call->lock - locks call data fields.
324 * These are independent of each other:
325 * rx_freeCallQueue_lock
330 * serverQueueEntry->lock
331 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
333 * peer->lock - locks peer data fields.
334 * conn_data_lock - that more than one thread is not updating a conn data
335 * field at the same time.
346 * Do we need a lock to protect the peer field in the conn structure?
347 * conn->peer was previously a constant for all intents and so has no
348 * lock protecting this field. The multihomed client delta introduced
349 * a RX code change : change the peer field in the connection structure
350 * to that remote interface from which the last packet for this
351 * connection was sent out. This may become an issue if further changes
354 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
355 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
357 /* rxdb_fileID is used to identify the lock location, along with line#. */
358 static int rxdb_fileID = RXDB_FILE_RX;
359 #endif /* RX_LOCKS_DB */
360 #else /* RX_ENABLE_LOCKS */
361 #define SET_CALL_QUEUE_LOCK(C, L)
362 #define CLEAR_CALL_QUEUE_LOCK(C)
363 #endif /* RX_ENABLE_LOCKS */
364 struct rx_serverQueueEntry *rx_waitForPacket = 0;
365 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
367 /* ------------Exported Interfaces------------- */
369 /* This function allows rxkad to set the epoch to a suitably random number
370 * which rx_NewConnection will use in the future. The principle purpose is to
371 * get rxnull connections to use the same epoch as the rxkad connections do, at
372 * least once the first rxkad connection is established. This is important now
373 * that the host/port addresses aren't used in FindConnection: the uniqueness
374 * of epoch/cid matters and the start time won't do. */
376 #ifdef AFS_PTHREAD_ENV
378 * This mutex protects the following global variables:
382 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
383 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
387 #endif /* AFS_PTHREAD_ENV */
390 rx_SetEpoch(afs_uint32 epoch)
397 /* Initialize rx. A port number may be mentioned, in which case this
398 * becomes the default port number for any service installed later.
399 * If 0 is provided for the port number, a random port will be chosen
400 * by the kernel. Whether this will ever overlap anything in
401 * /etc/services is anybody's guess... Returns 0 on success, -1 on
406 int rxinit_status = 1;
407 #ifdef AFS_PTHREAD_ENV
409 * This mutex protects the following global variables:
413 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
414 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
417 #define UNLOCK_RX_INIT
421 rx_InitHost(u_int host, u_int port)
428 char *htable, *ptable;
435 if (rxinit_status == 0) {
436 tmp_status = rxinit_status;
438 return tmp_status; /* Already started; return previous error code. */
444 if (afs_winsockInit() < 0)
450 * Initialize anything necessary to provide a non-premptive threading
453 rxi_InitializeThreadSupport();
456 /* Allocate and initialize a socket for client and perhaps server
459 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
460 if (rx_socket == OSI_NULLSOCKET) {
464 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
467 #endif /* RX_LOCKS_DB */
468 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
469 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
470 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
471 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
472 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
473 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
474 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
475 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
476 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
478 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
480 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
482 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
484 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
485 #if defined(AFS_HPUX110_ENV)
487 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
488 #endif /* AFS_HPUX110_ENV */
489 #endif /* RX_ENABLE_LOCKS && KERNEL */
492 rx_connDeadTime = 12;
493 rx_tranquil = 0; /* reset flag */
494 rxi_ResetStatistics();
496 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
497 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
498 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
499 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
500 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
501 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
503 /* Malloc up a bunch of packets & buffers */
505 queue_Init(&rx_freePacketQueue);
506 rxi_NeedMorePackets = FALSE;
507 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
509 /* enforce a minimum number of allocated packets */
510 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
511 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
513 /* allocate the initial free packet pool */
514 #ifdef RX_ENABLE_TSFPQ
515 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
516 #else /* RX_ENABLE_TSFPQ */
517 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
518 #endif /* RX_ENABLE_TSFPQ */
525 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
526 tv.tv_sec = clock_now.sec;
527 tv.tv_usec = clock_now.usec;
528 srand((unsigned int)tv.tv_usec);
535 #if defined(KERNEL) && !defined(UKERNEL)
536 /* Really, this should never happen in a real kernel */
539 struct sockaddr_in addr;
541 int addrlen = sizeof(addr);
543 socklen_t addrlen = sizeof(addr);
545 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
549 rx_port = addr.sin_port;
552 rx_stats.minRtt.sec = 9999999;
554 rx_SetEpoch(tv.tv_sec | 0x80000000);
556 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
557 * will provide a randomer value. */
559 MUTEX_ENTER(&rx_quota_mutex);
560 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
561 MUTEX_EXIT(&rx_quota_mutex);
562 /* *Slightly* random start time for the cid. This is just to help
563 * out with the hashing function at the peer */
564 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
565 rx_connHashTable = (struct rx_connection **)htable;
566 rx_peerHashTable = (struct rx_peer **)ptable;
568 rx_lastAckDelay.sec = 0;
569 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
570 rx_hardAckDelay.sec = 0;
571 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
572 rx_softAckDelay.sec = 0;
573 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
575 rxevent_Init(20, rxi_ReScheduleEvents);
577 /* Initialize various global queues */
578 queue_Init(&rx_idleServerQueue);
579 queue_Init(&rx_incomingCallQueue);
580 queue_Init(&rx_freeCallQueue);
582 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
583 /* Initialize our list of usable IP addresses. */
587 /* Start listener process (exact function is dependent on the
588 * implementation environment--kernel or user space) */
592 tmp_status = rxinit_status = 0;
600 return rx_InitHost(htonl(INADDR_ANY), port);
603 /* called with unincremented nRequestsRunning to see if it is OK to start
604 * a new thread in this service. Could be "no" for two reasons: over the
605 * max quota, or would prevent others from reaching their min quota.
607 #ifdef RX_ENABLE_LOCKS
608 /* This verion of QuotaOK reserves quota if it's ok while the
609 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
612 QuotaOK(struct rx_service *aservice)
614 /* check if over max quota */
615 if (aservice->nRequestsRunning >= aservice->maxProcs) {
619 /* under min quota, we're OK */
620 /* otherwise, can use only if there are enough to allow everyone
621 * to go to their min quota after this guy starts.
624 MUTEX_ENTER(&rx_quota_mutex);
625 if ((aservice->nRequestsRunning < aservice->minProcs)
626 || (rxi_availProcs > rxi_minDeficit)) {
627 aservice->nRequestsRunning++;
628 /* just started call in minProcs pool, need fewer to maintain
630 if (aservice->nRequestsRunning <= aservice->minProcs)
633 MUTEX_EXIT(&rx_quota_mutex);
636 MUTEX_EXIT(&rx_quota_mutex);
642 ReturnToServerPool(struct rx_service *aservice)
644 aservice->nRequestsRunning--;
645 MUTEX_ENTER(&rx_quota_mutex);
646 if (aservice->nRequestsRunning < aservice->minProcs)
649 MUTEX_EXIT(&rx_quota_mutex);
652 #else /* RX_ENABLE_LOCKS */
654 QuotaOK(struct rx_service *aservice)
657 /* under min quota, we're OK */
658 if (aservice->nRequestsRunning < aservice->minProcs)
661 /* check if over max quota */
662 if (aservice->nRequestsRunning >= aservice->maxProcs)
665 /* otherwise, can use only if there are enough to allow everyone
666 * to go to their min quota after this guy starts.
668 MUTEX_ENTER(&rx_quota_mutex);
669 if (rxi_availProcs > rxi_minDeficit)
671 MUTEX_EXIT(&rx_quota_mutex);
674 #endif /* RX_ENABLE_LOCKS */
677 /* Called by rx_StartServer to start up lwp's to service calls.
678 NExistingProcs gives the number of procs already existing, and which
679 therefore needn't be created. */
681 rxi_StartServerProcs(int nExistingProcs)
683 struct rx_service *service;
688 /* For each service, reserve N processes, where N is the "minimum"
689 * number of processes that MUST be able to execute a request in parallel,
690 * at any time, for that process. Also compute the maximum difference
691 * between any service's maximum number of processes that can run
692 * (i.e. the maximum number that ever will be run, and a guarantee
693 * that this number will run if other services aren't running), and its
694 * minimum number. The result is the extra number of processes that
695 * we need in order to provide the latter guarantee */
696 for (i = 0; i < RX_MAX_SERVICES; i++) {
698 service = rx_services[i];
699 if (service == (struct rx_service *)0)
701 nProcs += service->minProcs;
702 diff = service->maxProcs - service->minProcs;
706 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
707 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
708 for (i = 0; i < nProcs; i++) {
709 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
715 /* This routine is only required on Windows */
717 rx_StartClientThread(void)
719 #ifdef AFS_PTHREAD_ENV
721 pid = pthread_self();
722 #endif /* AFS_PTHREAD_ENV */
724 #endif /* AFS_NT40_ENV */
726 /* This routine must be called if any services are exported. If the
727 * donateMe flag is set, the calling process is donated to the server
730 rx_StartServer(int donateMe)
732 struct rx_service *service;
738 /* Start server processes, if necessary (exact function is dependent
739 * on the implementation environment--kernel or user space). DonateMe
740 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
741 * case, one less new proc will be created rx_StartServerProcs.
743 rxi_StartServerProcs(donateMe);
745 /* count up the # of threads in minProcs, and add set the min deficit to
746 * be that value, too.
748 for (i = 0; i < RX_MAX_SERVICES; i++) {
749 service = rx_services[i];
750 if (service == (struct rx_service *)0)
752 MUTEX_ENTER(&rx_quota_mutex);
753 rxi_totalMin += service->minProcs;
754 /* below works even if a thread is running, since minDeficit would
755 * still have been decremented and later re-incremented.
757 rxi_minDeficit += service->minProcs;
758 MUTEX_EXIT(&rx_quota_mutex);
761 /* Turn on reaping of idle server connections */
762 rxi_ReapConnections(NULL, NULL, NULL);
771 #ifdef AFS_PTHREAD_ENV
773 pid = afs_pointer_to_int(pthread_self());
774 #else /* AFS_PTHREAD_ENV */
776 LWP_CurrentProcess(&pid);
777 #endif /* AFS_PTHREAD_ENV */
779 sprintf(name, "srv_%d", ++nProcs);
781 (*registerProgram) (pid, name);
783 #endif /* AFS_NT40_ENV */
784 rx_ServerProc(NULL); /* Never returns */
786 #ifdef RX_ENABLE_TSFPQ
787 /* no use leaving packets around in this thread's local queue if
788 * it isn't getting donated to the server thread pool.
790 rxi_FlushLocalPacketsTSFPQ();
791 #endif /* RX_ENABLE_TSFPQ */
795 /* Create a new client connection to the specified service, using the
796 * specified security object to implement the security model for this
798 struct rx_connection *
799 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
800 struct rx_securityClass *securityObject,
801 int serviceSecurityIndex)
805 struct rx_connection *conn;
810 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
811 "serviceSecurityIndex %d)\n",
812 ntohl(shost), ntohs(sport), sservice, securityObject,
813 serviceSecurityIndex));
815 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
816 * the case of kmem_alloc? */
817 conn = rxi_AllocConnection();
818 #ifdef RX_ENABLE_LOCKS
819 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
820 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
821 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
824 MUTEX_ENTER(&rx_connHashTable_lock);
825 cid = (rx_nextCid += RX_MAXCALLS);
826 conn->type = RX_CLIENT_CONNECTION;
828 conn->epoch = rx_epoch;
829 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
830 conn->serviceId = sservice;
831 conn->securityObject = securityObject;
832 conn->securityData = (void *) 0;
833 conn->securityIndex = serviceSecurityIndex;
834 rx_SetConnDeadTime(conn, rx_connDeadTime);
835 rx_SetConnSecondsUntilNatPing(conn, 0);
836 conn->ackRate = RX_FAST_ACK_RATE;
838 conn->specific = NULL;
839 conn->challengeEvent = NULL;
840 conn->delayedAbortEvent = NULL;
841 conn->abortCount = 0;
843 for (i = 0; i < RX_MAXCALLS; i++) {
844 conn->twind[i] = rx_initSendWindow;
845 conn->rwind[i] = rx_initReceiveWindow;
848 RXS_NewConnection(securityObject, conn);
850 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
852 conn->refCount++; /* no lock required since only this thread knows... */
853 conn->next = rx_connHashTable[hashindex];
854 rx_connHashTable[hashindex] = conn;
856 rx_atomic_inc(&rx_stats.nClientConns);
857 MUTEX_EXIT(&rx_connHashTable_lock);
863 * Ensure a connection's timeout values are valid.
865 * @param[in] conn The connection to check
867 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
868 * unless idleDeadTime and/or hardDeadTime are not set
872 rxi_CheckConnTimeouts(struct rx_connection *conn)
874 /* a connection's timeouts must have the relationship
875 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
876 * total loss of network to a peer may cause an idle timeout instead of a
877 * dead timeout, simply because the idle timeout gets hit first. Also set
878 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
879 /* this logic is slightly complicated by the fact that
880 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
882 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
883 if (conn->idleDeadTime) {
884 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
886 if (conn->hardDeadTime) {
887 if (conn->idleDeadTime) {
888 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
890 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
896 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
898 /* The idea is to set the dead time to a value that allows several
899 * keepalives to be dropped without timing out the connection. */
900 conn->secondsUntilDead = seconds;
901 rxi_CheckConnTimeouts(conn);
902 conn->secondsUntilPing = conn->secondsUntilDead / 6;
906 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
908 conn->hardDeadTime = seconds;
909 rxi_CheckConnTimeouts(conn);
913 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
915 conn->idleDeadTime = seconds;
916 rxi_CheckConnTimeouts(conn);
919 int rxi_lowPeerRefCount = 0;
920 int rxi_lowConnRefCount = 0;
923 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
924 * NOTE: must not be called with rx_connHashTable_lock held.
927 rxi_CleanupConnection(struct rx_connection *conn)
929 /* Notify the service exporter, if requested, that this connection
930 * is being destroyed */
931 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
932 (*conn->service->destroyConnProc) (conn);
934 /* Notify the security module that this connection is being destroyed */
935 RXS_DestroyConnection(conn->securityObject, conn);
937 /* If this is the last connection using the rx_peer struct, set its
938 * idle time to now. rxi_ReapConnections will reap it if it's still
939 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
941 MUTEX_ENTER(&rx_peerHashTable_lock);
942 if (conn->peer->refCount < 2) {
943 conn->peer->idleWhen = clock_Sec();
944 if (conn->peer->refCount < 1) {
945 conn->peer->refCount = 1;
946 if (rx_stats_active) {
947 MUTEX_ENTER(&rx_stats_mutex);
948 rxi_lowPeerRefCount++;
949 MUTEX_EXIT(&rx_stats_mutex);
953 conn->peer->refCount--;
954 MUTEX_EXIT(&rx_peerHashTable_lock);
958 if (conn->type == RX_SERVER_CONNECTION)
959 rx_atomic_dec(&rx_stats.nServerConns);
961 rx_atomic_dec(&rx_stats.nClientConns);
964 if (conn->specific) {
966 for (i = 0; i < conn->nSpecific; i++) {
967 if (conn->specific[i] && rxi_keyCreate_destructor[i])
968 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
969 conn->specific[i] = NULL;
971 free(conn->specific);
973 conn->specific = NULL;
977 MUTEX_DESTROY(&conn->conn_call_lock);
978 MUTEX_DESTROY(&conn->conn_data_lock);
979 CV_DESTROY(&conn->conn_call_cv);
981 rxi_FreeConnection(conn);
984 /* Destroy the specified connection */
986 rxi_DestroyConnection(struct rx_connection *conn)
988 MUTEX_ENTER(&rx_connHashTable_lock);
989 rxi_DestroyConnectionNoLock(conn);
990 /* conn should be at the head of the cleanup list */
991 if (conn == rx_connCleanup_list) {
992 rx_connCleanup_list = rx_connCleanup_list->next;
993 MUTEX_EXIT(&rx_connHashTable_lock);
994 rxi_CleanupConnection(conn);
996 #ifdef RX_ENABLE_LOCKS
998 MUTEX_EXIT(&rx_connHashTable_lock);
1000 #endif /* RX_ENABLE_LOCKS */
1004 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1006 struct rx_connection **conn_ptr;
1008 struct rx_packet *packet;
1015 MUTEX_ENTER(&conn->conn_data_lock);
1016 MUTEX_ENTER(&rx_refcnt_mutex);
1017 if (conn->refCount > 0)
1020 if (rx_stats_active) {
1021 MUTEX_ENTER(&rx_stats_mutex);
1022 rxi_lowConnRefCount++;
1023 MUTEX_EXIT(&rx_stats_mutex);
1027 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1028 /* Busy; wait till the last guy before proceeding */
1029 MUTEX_EXIT(&rx_refcnt_mutex);
1030 MUTEX_EXIT(&conn->conn_data_lock);
1035 /* If the client previously called rx_NewCall, but it is still
1036 * waiting, treat this as a running call, and wait to destroy the
1037 * connection later when the call completes. */
1038 if ((conn->type == RX_CLIENT_CONNECTION)
1039 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1040 conn->flags |= RX_CONN_DESTROY_ME;
1041 MUTEX_EXIT(&conn->conn_data_lock);
1045 MUTEX_EXIT(&rx_refcnt_mutex);
1046 MUTEX_EXIT(&conn->conn_data_lock);
1048 /* Check for extant references to this connection */
1049 for (i = 0; i < RX_MAXCALLS; i++) {
1050 struct rx_call *call = conn->call[i];
1053 if (conn->type == RX_CLIENT_CONNECTION) {
1054 MUTEX_ENTER(&call->lock);
1055 if (call->delayedAckEvent) {
1056 /* Push the final acknowledgment out now--there
1057 * won't be a subsequent call to acknowledge the
1058 * last reply packets */
1059 rxevent_Cancel(call->delayedAckEvent, call,
1060 RX_CALL_REFCOUNT_DELAY);
1061 if (call->state == RX_STATE_PRECALL
1062 || call->state == RX_STATE_ACTIVE) {
1063 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1065 rxi_AckAll(NULL, call, 0);
1068 MUTEX_EXIT(&call->lock);
1072 #ifdef RX_ENABLE_LOCKS
1074 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1075 MUTEX_EXIT(&conn->conn_data_lock);
1077 /* Someone is accessing a packet right now. */
1081 #endif /* RX_ENABLE_LOCKS */
1084 /* Don't destroy the connection if there are any call
1085 * structures still in use */
1086 MUTEX_ENTER(&conn->conn_data_lock);
1087 conn->flags |= RX_CONN_DESTROY_ME;
1088 MUTEX_EXIT(&conn->conn_data_lock);
1093 if (conn->natKeepAliveEvent) {
1094 rxi_NatKeepAliveOff(conn);
1097 if (conn->delayedAbortEvent) {
1098 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1099 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1101 MUTEX_ENTER(&conn->conn_data_lock);
1102 rxi_SendConnectionAbort(conn, packet, 0, 1);
1103 MUTEX_EXIT(&conn->conn_data_lock);
1104 rxi_FreePacket(packet);
1108 /* Remove from connection hash table before proceeding */
1110 &rx_connHashTable[CONN_HASH
1111 (peer->host, peer->port, conn->cid, conn->epoch,
1113 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1114 if (*conn_ptr == conn) {
1115 *conn_ptr = conn->next;
1119 /* if the conn that we are destroying was the last connection, then we
1120 * clear rxLastConn as well */
1121 if (rxLastConn == conn)
1124 /* Make sure the connection is completely reset before deleting it. */
1125 /* get rid of pending events that could zap us later */
1126 if (conn->challengeEvent)
1127 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1128 if (conn->checkReachEvent)
1129 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1130 if (conn->natKeepAliveEvent)
1131 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1133 /* Add the connection to the list of destroyed connections that
1134 * need to be cleaned up. This is necessary to avoid deadlocks
1135 * in the routines we call to inform others that this connection is
1136 * being destroyed. */
1137 conn->next = rx_connCleanup_list;
1138 rx_connCleanup_list = conn;
1141 /* Externally available version */
1143 rx_DestroyConnection(struct rx_connection *conn)
1148 rxi_DestroyConnection(conn);
1153 rx_GetConnection(struct rx_connection *conn)
1158 MUTEX_ENTER(&rx_refcnt_mutex);
1160 MUTEX_EXIT(&rx_refcnt_mutex);
1164 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1165 /* Wait for the transmit queue to no longer be busy.
1166 * requires the call->lock to be held */
1168 rxi_WaitforTQBusy(struct rx_call *call) {
1169 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1170 call->flags |= RX_CALL_TQ_WAIT;
1172 #ifdef RX_ENABLE_LOCKS
1173 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1174 CV_WAIT(&call->cv_tq, &call->lock);
1175 #else /* RX_ENABLE_LOCKS */
1176 osi_rxSleep(&call->tq);
1177 #endif /* RX_ENABLE_LOCKS */
1179 if (call->tqWaiters == 0) {
1180 call->flags &= ~RX_CALL_TQ_WAIT;
1187 rxi_WakeUpTransmitQueue(struct rx_call *call)
1189 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1190 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1191 call, call->tqWaiters, call->flags));
1192 #ifdef RX_ENABLE_LOCKS
1193 osirx_AssertMine(&call->lock, "rxi_Start start");
1194 CV_BROADCAST(&call->cv_tq);
1195 #else /* RX_ENABLE_LOCKS */
1196 osi_rxWakeup(&call->tq);
1197 #endif /* RX_ENABLE_LOCKS */
1201 /* Start a new rx remote procedure call, on the specified connection.
1202 * If wait is set to 1, wait for a free call channel; otherwise return
1203 * 0. Maxtime gives the maximum number of seconds this call may take,
1204 * after rx_NewCall returns. After this time interval, a call to any
1205 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1206 * For fine grain locking, we hold the conn_call_lock in order to
1207 * to ensure that we don't get signalle after we found a call in an active
1208 * state and before we go to sleep.
1211 rx_NewCall(struct rx_connection *conn)
1214 struct rx_call *call;
1215 struct clock queueTime;
1219 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1222 clock_GetTime(&queueTime);
1224 * Check if there are others waiting for a new call.
1225 * If so, let them go first to avoid starving them.
1226 * This is a fairly simple scheme, and might not be
1227 * a complete solution for large numbers of waiters.
1229 * makeCallWaiters keeps track of the number of
1230 * threads waiting to make calls and the
1231 * RX_CONN_MAKECALL_WAITING flag bit is used to
1232 * indicate that there are indeed calls waiting.
1233 * The flag is set when the waiter is incremented.
1234 * It is only cleared when makeCallWaiters is 0.
1235 * This prevents us from accidently destroying the
1236 * connection while it is potentially about to be used.
1238 MUTEX_ENTER(&conn->conn_call_lock);
1239 MUTEX_ENTER(&conn->conn_data_lock);
1240 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1241 conn->flags |= RX_CONN_MAKECALL_WAITING;
1242 conn->makeCallWaiters++;
1243 MUTEX_EXIT(&conn->conn_data_lock);
1245 #ifdef RX_ENABLE_LOCKS
1246 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1250 MUTEX_ENTER(&conn->conn_data_lock);
1251 conn->makeCallWaiters--;
1252 if (conn->makeCallWaiters == 0)
1253 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1256 /* We are now the active thread in rx_NewCall */
1257 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1258 MUTEX_EXIT(&conn->conn_data_lock);
1263 for (i = 0; i < RX_MAXCALLS; i++) {
1264 call = conn->call[i];
1266 if (call->state == RX_STATE_DALLY) {
1267 MUTEX_ENTER(&call->lock);
1268 if (call->state == RX_STATE_DALLY) {
1270 * We are setting the state to RX_STATE_RESET to
1271 * ensure that no one else will attempt to use this
1272 * call once we drop the conn->conn_call_lock and
1273 * call->lock. We must drop the conn->conn_call_lock
1274 * before calling rxi_ResetCall because the process
1275 * of clearing the transmit queue can block for an
1276 * extended period of time. If we block while holding
1277 * the conn->conn_call_lock, then all rx_EndCall
1278 * processing will block as well. This has a detrimental
1279 * effect on overall system performance.
1281 call->state = RX_STATE_RESET;
1282 MUTEX_EXIT(&conn->conn_call_lock);
1283 MUTEX_ENTER(&rx_refcnt_mutex);
1284 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1285 MUTEX_EXIT(&rx_refcnt_mutex);
1286 rxi_ResetCall(call, 0);
1287 (*call->callNumber)++;
1288 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1292 * If we failed to be able to safely obtain the
1293 * conn->conn_call_lock we will have to drop the
1294 * call->lock to avoid a deadlock. When the call->lock
1295 * is released the state of the call can change. If it
1296 * is no longer RX_STATE_RESET then some other thread is
1299 MUTEX_EXIT(&call->lock);
1300 MUTEX_ENTER(&conn->conn_call_lock);
1301 MUTEX_ENTER(&call->lock);
1303 if (call->state == RX_STATE_RESET)
1307 * If we get here it means that after dropping
1308 * the conn->conn_call_lock and call->lock that
1309 * the call is no longer ours. If we can't find
1310 * a free call in the remaining slots we should
1311 * not go immediately to RX_CONN_MAKECALL_WAITING
1312 * because by dropping the conn->conn_call_lock
1313 * we have given up synchronization with rx_EndCall.
1314 * Instead, cycle through one more time to see if
1315 * we can find a call that can call our own.
1317 MUTEX_ENTER(&rx_refcnt_mutex);
1318 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1319 MUTEX_EXIT(&rx_refcnt_mutex);
1322 MUTEX_EXIT(&call->lock);
1325 /* rxi_NewCall returns with mutex locked */
1326 call = rxi_NewCall(conn, i);
1327 MUTEX_ENTER(&rx_refcnt_mutex);
1328 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1329 MUTEX_EXIT(&rx_refcnt_mutex);
1333 if (i < RX_MAXCALLS) {
1339 MUTEX_ENTER(&conn->conn_data_lock);
1340 conn->flags |= RX_CONN_MAKECALL_WAITING;
1341 conn->makeCallWaiters++;
1342 MUTEX_EXIT(&conn->conn_data_lock);
1344 #ifdef RX_ENABLE_LOCKS
1345 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1349 MUTEX_ENTER(&conn->conn_data_lock);
1350 conn->makeCallWaiters--;
1351 if (conn->makeCallWaiters == 0)
1352 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1353 MUTEX_EXIT(&conn->conn_data_lock);
1355 /* Client is initially in send mode */
1356 call->state = RX_STATE_ACTIVE;
1357 call->error = conn->error;
1359 call->mode = RX_MODE_ERROR;
1361 call->mode = RX_MODE_SENDING;
1363 /* remember start time for call in case we have hard dead time limit */
1364 call->queueTime = queueTime;
1365 clock_GetTime(&call->startTime);
1366 hzero(call->bytesSent);
1367 hzero(call->bytesRcvd);
1369 /* Turn on busy protocol. */
1370 rxi_KeepAliveOn(call);
1372 /* Attempt MTU discovery */
1373 rxi_GrowMTUOn(call);
1376 * We are no longer the active thread in rx_NewCall
1378 MUTEX_ENTER(&conn->conn_data_lock);
1379 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1380 MUTEX_EXIT(&conn->conn_data_lock);
1383 * Wake up anyone else who might be giving us a chance to
1384 * run (see code above that avoids resource starvation).
1386 #ifdef RX_ENABLE_LOCKS
1387 CV_BROADCAST(&conn->conn_call_cv);
1391 MUTEX_EXIT(&conn->conn_call_lock);
1393 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1394 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1395 osi_Panic("rx_NewCall call about to be used without an empty tq");
1397 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1399 MUTEX_EXIT(&call->lock);
1402 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1407 rxi_HasActiveCalls(struct rx_connection *aconn)
1410 struct rx_call *tcall;
1414 for (i = 0; i < RX_MAXCALLS; i++) {
1415 if ((tcall = aconn->call[i])) {
1416 if ((tcall->state == RX_STATE_ACTIVE)
1417 || (tcall->state == RX_STATE_PRECALL)) {
1428 rxi_GetCallNumberVector(struct rx_connection *aconn,
1429 afs_int32 * aint32s)
1432 struct rx_call *tcall;
1436 for (i = 0; i < RX_MAXCALLS; i++) {
1437 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1438 aint32s[i] = aconn->callNumber[i] + 1;
1440 aint32s[i] = aconn->callNumber[i];
1447 rxi_SetCallNumberVector(struct rx_connection *aconn,
1448 afs_int32 * aint32s)
1451 struct rx_call *tcall;
1455 for (i = 0; i < RX_MAXCALLS; i++) {
1456 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1457 aconn->callNumber[i] = aint32s[i] - 1;
1459 aconn->callNumber[i] = aint32s[i];
1465 /* Advertise a new service. A service is named locally by a UDP port
1466 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1469 char *serviceName; Name for identification purposes (e.g. the
1470 service name might be used for probing for
1473 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1474 char *serviceName, struct rx_securityClass **securityObjects,
1475 int nSecurityObjects,
1476 afs_int32(*serviceProc) (struct rx_call * acall))
1478 osi_socket socket = OSI_NULLSOCKET;
1479 struct rx_service *tservice;
1485 if (serviceId == 0) {
1487 "rx_NewService: service id for service %s is not non-zero.\n",
1494 "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",
1502 tservice = rxi_AllocService();
1505 #ifdef RX_ENABLE_LOCKS
1506 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1509 for (i = 0; i < RX_MAX_SERVICES; i++) {
1510 struct rx_service *service = rx_services[i];
1512 if (port == service->servicePort && host == service->serviceHost) {
1513 if (service->serviceId == serviceId) {
1514 /* The identical service has already been
1515 * installed; if the caller was intending to
1516 * change the security classes used by this
1517 * service, he/she loses. */
1519 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1520 serviceName, serviceId, service->serviceName);
1522 rxi_FreeService(tservice);
1525 /* Different service, same port: re-use the socket
1526 * which is bound to the same port */
1527 socket = service->socket;
1530 if (socket == OSI_NULLSOCKET) {
1531 /* If we don't already have a socket (from another
1532 * service on same port) get a new one */
1533 socket = rxi_GetHostUDPSocket(host, port);
1534 if (socket == OSI_NULLSOCKET) {
1536 rxi_FreeService(tservice);
1541 service->socket = socket;
1542 service->serviceHost = host;
1543 service->servicePort = port;
1544 service->serviceId = serviceId;
1545 service->serviceName = serviceName;
1546 service->nSecurityObjects = nSecurityObjects;
1547 service->securityObjects = securityObjects;
1548 service->minProcs = 0;
1549 service->maxProcs = 1;
1550 service->idleDeadTime = 60;
1551 service->idleDeadErr = 0;
1552 service->connDeadTime = rx_connDeadTime;
1553 service->executeRequestProc = serviceProc;
1554 service->checkReach = 0;
1555 service->nSpecific = 0;
1556 service->specific = NULL;
1557 rx_services[i] = service; /* not visible until now */
1563 rxi_FreeService(tservice);
1564 (osi_Msg "rx_NewService: cannot support > %d services\n",
1569 /* Set configuration options for all of a service's security objects */
1572 rx_SetSecurityConfiguration(struct rx_service *service,
1573 rx_securityConfigVariables type,
1577 for (i = 0; i<service->nSecurityObjects; i++) {
1578 if (service->securityObjects[i]) {
1579 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1587 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1588 struct rx_securityClass **securityObjects, int nSecurityObjects,
1589 afs_int32(*serviceProc) (struct rx_call * acall))
1591 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1594 /* Generic request processing loop. This routine should be called
1595 * by the implementation dependent rx_ServerProc. If socketp is
1596 * non-null, it will be set to the file descriptor that this thread
1597 * is now listening on. If socketp is null, this routine will never
1600 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1602 struct rx_call *call;
1604 struct rx_service *tservice = NULL;
1611 call = rx_GetCall(threadID, tservice, socketp);
1612 if (socketp && *socketp != OSI_NULLSOCKET) {
1613 /* We are now a listener thread */
1618 /* if server is restarting( typically smooth shutdown) then do not
1619 * allow any new calls.
1622 if (rx_tranquil && (call != NULL)) {
1626 MUTEX_ENTER(&call->lock);
1628 rxi_CallError(call, RX_RESTARTING);
1629 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1631 MUTEX_EXIT(&call->lock);
1635 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1636 #ifdef RX_ENABLE_LOCKS
1638 #endif /* RX_ENABLE_LOCKS */
1639 afs_termState = AFSOP_STOP_AFS;
1640 afs_osi_Wakeup(&afs_termState);
1641 #ifdef RX_ENABLE_LOCKS
1643 #endif /* RX_ENABLE_LOCKS */
1648 tservice = call->conn->service;
1650 if (tservice->beforeProc)
1651 (*tservice->beforeProc) (call);
1653 code = tservice->executeRequestProc(call);
1655 if (tservice->afterProc)
1656 (*tservice->afterProc) (call, code);
1658 rx_EndCall(call, code);
1659 if (rx_stats_active) {
1660 MUTEX_ENTER(&rx_stats_mutex);
1662 MUTEX_EXIT(&rx_stats_mutex);
1669 rx_WakeupServerProcs(void)
1671 struct rx_serverQueueEntry *np, *tqp;
1675 MUTEX_ENTER(&rx_serverPool_lock);
1677 #ifdef RX_ENABLE_LOCKS
1678 if (rx_waitForPacket)
1679 CV_BROADCAST(&rx_waitForPacket->cv);
1680 #else /* RX_ENABLE_LOCKS */
1681 if (rx_waitForPacket)
1682 osi_rxWakeup(rx_waitForPacket);
1683 #endif /* RX_ENABLE_LOCKS */
1684 MUTEX_ENTER(&freeSQEList_lock);
1685 for (np = rx_FreeSQEList; np; np = tqp) {
1686 tqp = *(struct rx_serverQueueEntry **)np;
1687 #ifdef RX_ENABLE_LOCKS
1688 CV_BROADCAST(&np->cv);
1689 #else /* RX_ENABLE_LOCKS */
1691 #endif /* RX_ENABLE_LOCKS */
1693 MUTEX_EXIT(&freeSQEList_lock);
1694 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1695 #ifdef RX_ENABLE_LOCKS
1696 CV_BROADCAST(&np->cv);
1697 #else /* RX_ENABLE_LOCKS */
1699 #endif /* RX_ENABLE_LOCKS */
1701 MUTEX_EXIT(&rx_serverPool_lock);
1706 * One thing that seems to happen is that all the server threads get
1707 * tied up on some empty or slow call, and then a whole bunch of calls
1708 * arrive at once, using up the packet pool, so now there are more
1709 * empty calls. The most critical resources here are server threads
1710 * and the free packet pool. The "doreclaim" code seems to help in
1711 * general. I think that eventually we arrive in this state: there
1712 * are lots of pending calls which do have all their packets present,
1713 * so they won't be reclaimed, are multi-packet calls, so they won't
1714 * be scheduled until later, and thus are tying up most of the free
1715 * packet pool for a very long time.
1717 * 1. schedule multi-packet calls if all the packets are present.
1718 * Probably CPU-bound operation, useful to return packets to pool.
1719 * Do what if there is a full window, but the last packet isn't here?
1720 * 3. preserve one thread which *only* runs "best" calls, otherwise
1721 * it sleeps and waits for that type of call.
1722 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1723 * the current dataquota business is badly broken. The quota isn't adjusted
1724 * to reflect how many packets are presently queued for a running call.
1725 * So, when we schedule a queued call with a full window of packets queued
1726 * up for it, that *should* free up a window full of packets for other 2d-class
1727 * calls to be able to use from the packet pool. But it doesn't.
1729 * NB. Most of the time, this code doesn't run -- since idle server threads
1730 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1731 * as a new call arrives.
1733 /* Sleep until a call arrives. Returns a pointer to the call, ready
1734 * for an rx_Read. */
1735 #ifdef RX_ENABLE_LOCKS
1737 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1739 struct rx_serverQueueEntry *sq;
1740 struct rx_call *call = (struct rx_call *)0;
1741 struct rx_service *service = NULL;
1744 MUTEX_ENTER(&freeSQEList_lock);
1746 if ((sq = rx_FreeSQEList)) {
1747 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1748 MUTEX_EXIT(&freeSQEList_lock);
1749 } else { /* otherwise allocate a new one and return that */
1750 MUTEX_EXIT(&freeSQEList_lock);
1751 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1752 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1753 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1756 MUTEX_ENTER(&rx_serverPool_lock);
1757 if (cur_service != NULL) {
1758 ReturnToServerPool(cur_service);
1761 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1762 struct rx_call *tcall, *ncall, *choice2 = NULL;
1764 /* Scan for eligible incoming calls. A call is not eligible
1765 * if the maximum number of calls for its service type are
1766 * already executing */
1767 /* One thread will process calls FCFS (to prevent starvation),
1768 * while the other threads may run ahead looking for calls which
1769 * have all their input data available immediately. This helps
1770 * keep threads from blocking, waiting for data from the client. */
1771 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1772 service = tcall->conn->service;
1773 if (!QuotaOK(service)) {
1776 MUTEX_ENTER(&rx_pthread_mutex);
1777 if (tno == rxi_fcfs_thread_num
1778 || !tcall->queue_item_header.next) {
1779 MUTEX_EXIT(&rx_pthread_mutex);
1780 /* If we're the fcfs thread , then we'll just use
1781 * this call. If we haven't been able to find an optimal
1782 * choice, and we're at the end of the list, then use a
1783 * 2d choice if one has been identified. Otherwise... */
1784 call = (choice2 ? choice2 : tcall);
1785 service = call->conn->service;
1787 MUTEX_EXIT(&rx_pthread_mutex);
1788 if (!queue_IsEmpty(&tcall->rq)) {
1789 struct rx_packet *rp;
1790 rp = queue_First(&tcall->rq, rx_packet);
1791 if (rp->header.seq == 1) {
1793 || (rp->header.flags & RX_LAST_PACKET)) {
1795 } else if (rxi_2dchoice && !choice2
1796 && !(tcall->flags & RX_CALL_CLEARED)
1797 && (tcall->rprev > rxi_HardAckRate)) {
1807 ReturnToServerPool(service);
1814 MUTEX_EXIT(&rx_serverPool_lock);
1815 MUTEX_ENTER(&call->lock);
1817 if (call->flags & RX_CALL_WAIT_PROC) {
1818 call->flags &= ~RX_CALL_WAIT_PROC;
1819 rx_atomic_dec(&rx_nWaiting);
1822 if (call->state != RX_STATE_PRECALL || call->error) {
1823 MUTEX_EXIT(&call->lock);
1824 MUTEX_ENTER(&rx_serverPool_lock);
1825 ReturnToServerPool(service);
1830 if (queue_IsEmpty(&call->rq)
1831 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1832 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1834 CLEAR_CALL_QUEUE_LOCK(call);
1837 /* If there are no eligible incoming calls, add this process
1838 * to the idle server queue, to wait for one */
1842 *socketp = OSI_NULLSOCKET;
1844 sq->socketp = socketp;
1845 queue_Append(&rx_idleServerQueue, sq);
1846 #ifndef AFS_AIX41_ENV
1847 rx_waitForPacket = sq;
1849 rx_waitingForPacket = sq;
1850 #endif /* AFS_AIX41_ENV */
1852 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1854 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1855 MUTEX_EXIT(&rx_serverPool_lock);
1856 return (struct rx_call *)0;
1859 } while (!(call = sq->newcall)
1860 && !(socketp && *socketp != OSI_NULLSOCKET));
1861 MUTEX_EXIT(&rx_serverPool_lock);
1863 MUTEX_ENTER(&call->lock);
1869 MUTEX_ENTER(&freeSQEList_lock);
1870 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1871 rx_FreeSQEList = sq;
1872 MUTEX_EXIT(&freeSQEList_lock);
1875 clock_GetTime(&call->startTime);
1876 call->state = RX_STATE_ACTIVE;
1877 call->mode = RX_MODE_RECEIVING;
1878 #ifdef RX_KERNEL_TRACE
1879 if (ICL_SETACTIVE(afs_iclSetp)) {
1880 int glockOwner = ISAFS_GLOCK();
1883 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1884 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1891 rxi_calltrace(RX_CALL_START, call);
1892 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1893 call->conn->service->servicePort, call->conn->service->serviceId,
1896 MUTEX_EXIT(&call->lock);
1897 MUTEX_ENTER(&rx_refcnt_mutex);
1898 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1899 MUTEX_EXIT(&rx_refcnt_mutex);
1901 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1906 #else /* RX_ENABLE_LOCKS */
1908 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1910 struct rx_serverQueueEntry *sq;
1911 struct rx_call *call = (struct rx_call *)0, *choice2;
1912 struct rx_service *service = NULL;
1916 MUTEX_ENTER(&freeSQEList_lock);
1918 if ((sq = rx_FreeSQEList)) {
1919 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1920 MUTEX_EXIT(&freeSQEList_lock);
1921 } else { /* otherwise allocate a new one and return that */
1922 MUTEX_EXIT(&freeSQEList_lock);
1923 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1924 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1925 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1927 MUTEX_ENTER(&sq->lock);
1929 if (cur_service != NULL) {
1930 cur_service->nRequestsRunning--;
1931 MUTEX_ENTER(&rx_quota_mutex);
1932 if (cur_service->nRequestsRunning < cur_service->minProcs)
1935 MUTEX_EXIT(&rx_quota_mutex);
1937 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1938 struct rx_call *tcall, *ncall;
1939 /* Scan for eligible incoming calls. A call is not eligible
1940 * if the maximum number of calls for its service type are
1941 * already executing */
1942 /* One thread will process calls FCFS (to prevent starvation),
1943 * while the other threads may run ahead looking for calls which
1944 * have all their input data available immediately. This helps
1945 * keep threads from blocking, waiting for data from the client. */
1946 choice2 = (struct rx_call *)0;
1947 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1948 service = tcall->conn->service;
1949 if (QuotaOK(service)) {
1950 MUTEX_ENTER(&rx_pthread_mutex);
1951 if (tno == rxi_fcfs_thread_num
1952 || !tcall->queue_item_header.next) {
1953 MUTEX_EXIT(&rx_pthread_mutex);
1954 /* If we're the fcfs thread, then we'll just use
1955 * this call. If we haven't been able to find an optimal
1956 * choice, and we're at the end of the list, then use a
1957 * 2d choice if one has been identified. Otherwise... */
1958 call = (choice2 ? choice2 : tcall);
1959 service = call->conn->service;
1961 MUTEX_EXIT(&rx_pthread_mutex);
1962 if (!queue_IsEmpty(&tcall->rq)) {
1963 struct rx_packet *rp;
1964 rp = queue_First(&tcall->rq, rx_packet);
1965 if (rp->header.seq == 1
1967 || (rp->header.flags & RX_LAST_PACKET))) {
1969 } else if (rxi_2dchoice && !choice2
1970 && !(tcall->flags & RX_CALL_CLEARED)
1971 && (tcall->rprev > rxi_HardAckRate)) {
1985 /* we can't schedule a call if there's no data!!! */
1986 /* send an ack if there's no data, if we're missing the
1987 * first packet, or we're missing something between first
1988 * and last -- there's a "hole" in the incoming data. */
1989 if (queue_IsEmpty(&call->rq)
1990 || queue_First(&call->rq, rx_packet)->header.seq != 1
1991 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1992 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1994 call->flags &= (~RX_CALL_WAIT_PROC);
1995 service->nRequestsRunning++;
1996 /* just started call in minProcs pool, need fewer to maintain
1998 MUTEX_ENTER(&rx_quota_mutex);
1999 if (service->nRequestsRunning <= service->minProcs)
2002 MUTEX_EXIT(&rx_quota_mutex);
2003 rx_atomic_dec(&rx_nWaiting);
2004 /* MUTEX_EXIT(&call->lock); */
2006 /* If there are no eligible incoming calls, add this process
2007 * to the idle server queue, to wait for one */
2010 *socketp = OSI_NULLSOCKET;
2012 sq->socketp = socketp;
2013 queue_Append(&rx_idleServerQueue, sq);
2017 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2019 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2020 return (struct rx_call *)0;
2023 } while (!(call = sq->newcall)
2024 && !(socketp && *socketp != OSI_NULLSOCKET));
2026 MUTEX_EXIT(&sq->lock);
2028 MUTEX_ENTER(&freeSQEList_lock);
2029 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2030 rx_FreeSQEList = sq;
2031 MUTEX_EXIT(&freeSQEList_lock);
2034 clock_GetTime(&call->startTime);
2035 call->state = RX_STATE_ACTIVE;
2036 call->mode = RX_MODE_RECEIVING;
2037 #ifdef RX_KERNEL_TRACE
2038 if (ICL_SETACTIVE(afs_iclSetp)) {
2039 int glockOwner = ISAFS_GLOCK();
2042 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2043 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2050 rxi_calltrace(RX_CALL_START, call);
2051 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2052 call->conn->service->servicePort, call->conn->service->serviceId,
2055 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2062 #endif /* RX_ENABLE_LOCKS */
2066 /* Establish a procedure to be called when a packet arrives for a
2067 * call. This routine will be called at most once after each call,
2068 * and will also be called if there is an error condition on the or
2069 * the call is complete. Used by multi rx to build a selection
2070 * function which determines which of several calls is likely to be a
2071 * good one to read from.
2072 * NOTE: the way this is currently implemented it is probably only a
2073 * good idea to (1) use it immediately after a newcall (clients only)
2074 * and (2) only use it once. Other uses currently void your warranty
2077 rx_SetArrivalProc(struct rx_call *call,
2078 void (*proc) (struct rx_call * call,
2081 void * handle, int arg)
2083 call->arrivalProc = proc;
2084 call->arrivalProcHandle = handle;
2085 call->arrivalProcArg = arg;
2088 /* Call is finished (possibly prematurely). Return rc to the peer, if
2089 * appropriate, and return the final error code from the conversation
2093 rx_EndCall(struct rx_call *call, afs_int32 rc)
2095 struct rx_connection *conn = call->conn;
2099 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2100 call, rc, call->error, call->abortCode));
2103 MUTEX_ENTER(&call->lock);
2105 if (rc == 0 && call->error == 0) {
2106 call->abortCode = 0;
2107 call->abortCount = 0;
2110 call->arrivalProc = (void (*)())0;
2111 if (rc && call->error == 0) {
2112 rxi_CallError(call, rc);
2113 call->mode = RX_MODE_ERROR;
2114 /* Send an abort message to the peer if this error code has
2115 * only just been set. If it was set previously, assume the
2116 * peer has already been sent the error code or will request it
2118 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2120 if (conn->type == RX_SERVER_CONNECTION) {
2121 /* Make sure reply or at least dummy reply is sent */
2122 if (call->mode == RX_MODE_RECEIVING) {
2123 MUTEX_EXIT(&call->lock);
2124 rxi_WriteProc(call, 0, 0);
2125 MUTEX_ENTER(&call->lock);
2127 if (call->mode == RX_MODE_SENDING) {
2128 MUTEX_EXIT(&call->lock);
2129 rxi_FlushWrite(call);
2130 MUTEX_ENTER(&call->lock);
2132 rxi_calltrace(RX_CALL_END, call);
2133 /* Call goes to hold state until reply packets are acknowledged */
2134 if (call->tfirst + call->nSoftAcked < call->tnext) {
2135 call->state = RX_STATE_HOLD;
2137 call->state = RX_STATE_DALLY;
2138 rxi_ClearTransmitQueue(call, 0);
2139 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2140 rxevent_Cancel(call->keepAliveEvent, call,
2141 RX_CALL_REFCOUNT_ALIVE);
2143 } else { /* Client connection */
2145 /* Make sure server receives input packets, in the case where
2146 * no reply arguments are expected */
2147 if ((call->mode == RX_MODE_SENDING)
2148 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2149 MUTEX_EXIT(&call->lock);
2150 (void)rxi_ReadProc(call, &dummy, 1);
2151 MUTEX_ENTER(&call->lock);
2154 /* If we had an outstanding delayed ack, be nice to the server
2155 * and force-send it now.
2157 if (call->delayedAckEvent) {
2158 rxevent_Cancel(call->delayedAckEvent, call,
2159 RX_CALL_REFCOUNT_DELAY);
2160 call->delayedAckEvent = NULL;
2161 rxi_SendDelayedAck(NULL, call, NULL);
2164 /* We need to release the call lock since it's lower than the
2165 * conn_call_lock and we don't want to hold the conn_call_lock
2166 * over the rx_ReadProc call. The conn_call_lock needs to be held
2167 * here for the case where rx_NewCall is perusing the calls on
2168 * the connection structure. We don't want to signal until
2169 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2170 * have checked this call, found it active and by the time it
2171 * goes to sleep, will have missed the signal.
2173 MUTEX_EXIT(&call->lock);
2174 MUTEX_ENTER(&conn->conn_call_lock);
2175 MUTEX_ENTER(&call->lock);
2176 MUTEX_ENTER(&conn->conn_data_lock);
2177 conn->flags |= RX_CONN_BUSY;
2178 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2179 MUTEX_EXIT(&conn->conn_data_lock);
2180 #ifdef RX_ENABLE_LOCKS
2181 CV_BROADCAST(&conn->conn_call_cv);
2186 #ifdef RX_ENABLE_LOCKS
2188 MUTEX_EXIT(&conn->conn_data_lock);
2190 #endif /* RX_ENABLE_LOCKS */
2191 call->state = RX_STATE_DALLY;
2193 error = call->error;
2195 /* currentPacket, nLeft, and NFree must be zeroed here, because
2196 * ResetCall cannot: ResetCall may be called at splnet(), in the
2197 * kernel version, and may interrupt the macros rx_Read or
2198 * rx_Write, which run at normal priority for efficiency. */
2199 if (call->currentPacket) {
2200 #ifdef RX_TRACK_PACKETS
2201 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2203 rxi_FreePacket(call->currentPacket);
2204 call->currentPacket = (struct rx_packet *)0;
2207 call->nLeft = call->nFree = call->curlen = 0;
2209 /* Free any packets from the last call to ReadvProc/WritevProc */
2210 #ifdef RXDEBUG_PACKET
2212 #endif /* RXDEBUG_PACKET */
2213 rxi_FreePackets(0, &call->iovq);
2214 MUTEX_EXIT(&call->lock);
2216 MUTEX_ENTER(&rx_refcnt_mutex);
2217 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2218 MUTEX_EXIT(&rx_refcnt_mutex);
2219 if (conn->type == RX_CLIENT_CONNECTION) {
2220 MUTEX_ENTER(&conn->conn_data_lock);
2221 conn->flags &= ~RX_CONN_BUSY;
2222 MUTEX_EXIT(&conn->conn_data_lock);
2223 MUTEX_EXIT(&conn->conn_call_lock);
2227 * Map errors to the local host's errno.h format.
2229 error = ntoh_syserr_conv(error);
2233 #if !defined(KERNEL)
2235 /* Call this routine when shutting down a server or client (especially
2236 * clients). This will allow Rx to gracefully garbage collect server
2237 * connections, and reduce the number of retries that a server might
2238 * make to a dead client.
2239 * This is not quite right, since some calls may still be ongoing and
2240 * we can't lock them to destroy them. */
2244 struct rx_connection **conn_ptr, **conn_end;
2248 if (rxinit_status == 1) {
2250 return; /* Already shutdown. */
2252 rxi_DeleteCachedConnections();
2253 if (rx_connHashTable) {
2254 MUTEX_ENTER(&rx_connHashTable_lock);
2255 for (conn_ptr = &rx_connHashTable[0], conn_end =
2256 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2258 struct rx_connection *conn, *next;
2259 for (conn = *conn_ptr; conn; conn = next) {
2261 if (conn->type == RX_CLIENT_CONNECTION) {
2262 MUTEX_ENTER(&rx_refcnt_mutex);
2264 MUTEX_EXIT(&rx_refcnt_mutex);
2265 #ifdef RX_ENABLE_LOCKS
2266 rxi_DestroyConnectionNoLock(conn);
2267 #else /* RX_ENABLE_LOCKS */
2268 rxi_DestroyConnection(conn);
2269 #endif /* RX_ENABLE_LOCKS */
2273 #ifdef RX_ENABLE_LOCKS
2274 while (rx_connCleanup_list) {
2275 struct rx_connection *conn;
2276 conn = rx_connCleanup_list;
2277 rx_connCleanup_list = rx_connCleanup_list->next;
2278 MUTEX_EXIT(&rx_connHashTable_lock);
2279 rxi_CleanupConnection(conn);
2280 MUTEX_ENTER(&rx_connHashTable_lock);
2282 MUTEX_EXIT(&rx_connHashTable_lock);
2283 #endif /* RX_ENABLE_LOCKS */
2288 afs_winsockCleanup();
2296 /* if we wakeup packet waiter too often, can get in loop with two
2297 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2299 rxi_PacketsUnWait(void)
2301 if (!rx_waitingForPackets) {
2305 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2306 return; /* still over quota */
2309 rx_waitingForPackets = 0;
2310 #ifdef RX_ENABLE_LOCKS
2311 CV_BROADCAST(&rx_waitingForPackets_cv);
2313 osi_rxWakeup(&rx_waitingForPackets);
2319 /* ------------------Internal interfaces------------------------- */
2321 /* Return this process's service structure for the
2322 * specified socket and service */
2324 rxi_FindService(osi_socket socket, u_short serviceId)
2326 struct rx_service **sp;
2327 for (sp = &rx_services[0]; *sp; sp++) {
2328 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2334 #ifdef RXDEBUG_PACKET
2335 #ifdef KDUMP_RX_LOCK
2336 static struct rx_call_rx_lock *rx_allCallsp = 0;
2338 static struct rx_call *rx_allCallsp = 0;
2340 #endif /* RXDEBUG_PACKET */
2342 /* Allocate a call structure, for the indicated channel of the
2343 * supplied connection. The mode and state of the call must be set by
2344 * the caller. Returns the call with mutex locked. */
2346 rxi_NewCall(struct rx_connection *conn, int channel)
2348 struct rx_call *call;
2349 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2350 struct rx_call *cp; /* Call pointer temp */
2351 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2352 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2354 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2356 /* Grab an existing call structure, or allocate a new one.
2357 * Existing call structures are assumed to have been left reset by
2359 MUTEX_ENTER(&rx_freeCallQueue_lock);
2361 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2363 * EXCEPT that the TQ might not yet be cleared out.
2364 * Skip over those with in-use TQs.
2367 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2368 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2374 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2375 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2376 call = queue_First(&rx_freeCallQueue, rx_call);
2377 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2379 if (rx_stats_active)
2380 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2381 MUTEX_EXIT(&rx_freeCallQueue_lock);
2382 MUTEX_ENTER(&call->lock);
2383 CLEAR_CALL_QUEUE_LOCK(call);
2384 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2385 /* Now, if TQ wasn't cleared earlier, do it now. */
2386 rxi_WaitforTQBusy(call);
2387 if (call->flags & RX_CALL_TQ_CLEARME) {
2388 rxi_ClearTransmitQueue(call, 1);
2389 /*queue_Init(&call->tq);*/
2391 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2392 /* Bind the call to its connection structure */
2394 rxi_ResetCall(call, 1);
2397 call = rxi_Alloc(sizeof(struct rx_call));
2398 #ifdef RXDEBUG_PACKET
2399 call->allNextp = rx_allCallsp;
2400 rx_allCallsp = call;
2402 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2403 #else /* RXDEBUG_PACKET */
2404 rx_atomic_inc(&rx_stats.nCallStructs);
2405 #endif /* RXDEBUG_PACKET */
2407 MUTEX_EXIT(&rx_freeCallQueue_lock);
2408 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2409 MUTEX_ENTER(&call->lock);
2410 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2411 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2412 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2414 /* Initialize once-only items */
2415 queue_Init(&call->tq);
2416 queue_Init(&call->rq);
2417 queue_Init(&call->iovq);
2418 #ifdef RXDEBUG_PACKET
2419 call->rqc = call->tqc = call->iovqc = 0;
2420 #endif /* RXDEBUG_PACKET */
2421 /* Bind the call to its connection structure (prereq for reset) */
2423 rxi_ResetCall(call, 1);
2425 call->channel = channel;
2426 call->callNumber = &conn->callNumber[channel];
2427 call->rwind = conn->rwind[channel];
2428 call->twind = conn->twind[channel];
2429 /* Note that the next expected call number is retained (in
2430 * conn->callNumber[i]), even if we reallocate the call structure
2432 conn->call[channel] = call;
2433 /* if the channel's never been used (== 0), we should start at 1, otherwise
2434 * the call number is valid from the last time this channel was used */
2435 if (*call->callNumber == 0)
2436 *call->callNumber = 1;
2441 /* A call has been inactive long enough that so we can throw away
2442 * state, including the call structure, which is placed on the call
2445 * call->lock amd rx_refcnt_mutex are held upon entry.
2446 * haveCTLock is set when called from rxi_ReapConnections.
2449 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2451 int channel = call->channel;
2452 struct rx_connection *conn = call->conn;
2455 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2456 (*call->callNumber)++;
2458 * We are setting the state to RX_STATE_RESET to
2459 * ensure that no one else will attempt to use this
2460 * call once we drop the refcnt lock. We must drop
2461 * the refcnt lock before calling rxi_ResetCall
2462 * because it cannot be held across acquiring the
2463 * freepktQ lock. NewCall does the same.
2465 call->state = RX_STATE_RESET;
2466 MUTEX_EXIT(&rx_refcnt_mutex);
2467 rxi_ResetCall(call, 0);
2468 call->conn->call[channel] = (struct rx_call *)0;
2470 MUTEX_ENTER(&rx_freeCallQueue_lock);
2471 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2472 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2473 /* A call may be free even though its transmit queue is still in use.
2474 * Since we search the call list from head to tail, put busy calls at
2475 * the head of the list, and idle calls at the tail.
2477 if (call->flags & RX_CALL_TQ_BUSY)
2478 queue_Prepend(&rx_freeCallQueue, call);
2480 queue_Append(&rx_freeCallQueue, call);
2481 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2482 queue_Append(&rx_freeCallQueue, call);
2483 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2484 if (rx_stats_active)
2485 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2486 MUTEX_EXIT(&rx_freeCallQueue_lock);
2488 /* Destroy the connection if it was previously slated for
2489 * destruction, i.e. the Rx client code previously called
2490 * rx_DestroyConnection (client connections), or
2491 * rxi_ReapConnections called the same routine (server
2492 * connections). Only do this, however, if there are no
2493 * outstanding calls. Note that for fine grain locking, there appears
2494 * to be a deadlock in that rxi_FreeCall has a call locked and
2495 * DestroyConnectionNoLock locks each call in the conn. But note a
2496 * few lines up where we have removed this call from the conn.
2497 * If someone else destroys a connection, they either have no
2498 * call lock held or are going through this section of code.
2500 MUTEX_ENTER(&conn->conn_data_lock);
2501 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2502 MUTEX_ENTER(&rx_refcnt_mutex);
2504 MUTEX_EXIT(&rx_refcnt_mutex);
2505 MUTEX_EXIT(&conn->conn_data_lock);
2506 #ifdef RX_ENABLE_LOCKS
2508 rxi_DestroyConnectionNoLock(conn);
2510 rxi_DestroyConnection(conn);
2511 #else /* RX_ENABLE_LOCKS */
2512 rxi_DestroyConnection(conn);
2513 #endif /* RX_ENABLE_LOCKS */
2515 MUTEX_EXIT(&conn->conn_data_lock);
2517 MUTEX_ENTER(&rx_refcnt_mutex);
2520 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2521 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2524 rxi_Alloc(size_t size)
2528 if (rx_stats_active) {
2529 rx_atomic_add(&rxi_Allocsize, (int) size);
2530 rx_atomic_inc(&rxi_Alloccnt);
2534 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2535 afs_osi_Alloc_NoSleep(size);
2540 osi_Panic("rxi_Alloc error");
2546 rxi_Free(void *addr, size_t size)
2548 if (rx_stats_active) {
2549 rx_atomic_sub(&rxi_Allocsize, (int) size);
2550 rx_atomic_dec(&rxi_Alloccnt);
2552 osi_Free(addr, size);
2556 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2558 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2559 struct rx_peer *next = NULL;
2563 MUTEX_ENTER(&rx_peerHashTable_lock);
2565 peer_ptr = &rx_peerHashTable[0];
2566 peer_end = &rx_peerHashTable[rx_hashTableSize];
2569 for ( ; peer_ptr < peer_end; peer_ptr++) {
2572 for ( ; peer; peer = next) {
2574 if (host == peer->host)
2579 hashIndex = PEER_HASH(host, port);
2580 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2581 if ((peer->host == host) && (peer->port == port))
2586 MUTEX_ENTER(&rx_peerHashTable_lock);
2591 MUTEX_EXIT(&rx_peerHashTable_lock);
2593 MUTEX_ENTER(&peer->peer_lock);
2594 /* We don't handle dropping below min, so don't */
2595 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2596 peer->ifMTU=MIN(mtu, peer->ifMTU);
2597 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2598 /* if we tweaked this down, need to tune our peer MTU too */
2599 peer->MTU = MIN(peer->MTU, peer->natMTU);
2600 /* if we discovered a sub-1500 mtu, degrade */
2601 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2602 peer->maxDgramPackets = 1;
2603 /* We no longer have valid peer packet information */
2604 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2605 peer->maxPacketSize = 0;
2606 MUTEX_EXIT(&peer->peer_lock);
2608 MUTEX_ENTER(&rx_peerHashTable_lock);
2610 if (host && !port) {
2612 /* pick up where we left off */
2616 MUTEX_EXIT(&rx_peerHashTable_lock);
2619 /* Find the peer process represented by the supplied (host,port)
2620 * combination. If there is no appropriate active peer structure, a
2621 * new one will be allocated and initialized
2622 * The origPeer, if set, is a pointer to a peer structure on which the
2623 * refcount will be be decremented. This is used to replace the peer
2624 * structure hanging off a connection structure */
2626 rxi_FindPeer(afs_uint32 host, u_short port,
2627 struct rx_peer *origPeer, int create)
2631 hashIndex = PEER_HASH(host, port);
2632 MUTEX_ENTER(&rx_peerHashTable_lock);
2633 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2634 if ((pp->host == host) && (pp->port == port))
2639 pp = rxi_AllocPeer(); /* This bzero's *pp */
2640 pp->host = host; /* set here or in InitPeerParams is zero */
2642 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2643 queue_Init(&pp->congestionQueue);
2644 queue_Init(&pp->rpcStats);
2645 pp->next = rx_peerHashTable[hashIndex];
2646 rx_peerHashTable[hashIndex] = pp;
2647 rxi_InitPeerParams(pp);
2648 if (rx_stats_active)
2649 rx_atomic_inc(&rx_stats.nPeerStructs);
2656 origPeer->refCount--;
2657 MUTEX_EXIT(&rx_peerHashTable_lock);
2662 /* Find the connection at (host, port) started at epoch, and with the
2663 * given connection id. Creates the server connection if necessary.
2664 * The type specifies whether a client connection or a server
2665 * connection is desired. In both cases, (host, port) specify the
2666 * peer's (host, pair) pair. Client connections are not made
2667 * automatically by this routine. The parameter socket gives the
2668 * socket descriptor on which the packet was received. This is used,
2669 * in the case of server connections, to check that *new* connections
2670 * come via a valid (port, serviceId). Finally, the securityIndex
2671 * parameter must match the existing index for the connection. If a
2672 * server connection is created, it will be created using the supplied
2673 * index, if the index is valid for this service */
2674 struct rx_connection *
2675 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2676 u_short port, u_short serviceId, afs_uint32 cid,
2677 afs_uint32 epoch, int type, u_int securityIndex)
2679 int hashindex, flag, i;
2680 struct rx_connection *conn;
2681 hashindex = CONN_HASH(host, port, cid, epoch, type);
2682 MUTEX_ENTER(&rx_connHashTable_lock);
2683 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2684 rx_connHashTable[hashindex],
2687 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2688 && (epoch == conn->epoch)) {
2689 struct rx_peer *pp = conn->peer;
2690 if (securityIndex != conn->securityIndex) {
2691 /* this isn't supposed to happen, but someone could forge a packet
2692 * like this, and there seems to be some CM bug that makes this
2693 * happen from time to time -- in which case, the fileserver
2695 MUTEX_EXIT(&rx_connHashTable_lock);
2696 return (struct rx_connection *)0;
2698 if (pp->host == host && pp->port == port)
2700 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2702 /* So what happens when it's a callback connection? */
2703 if ( /*type == RX_CLIENT_CONNECTION && */
2704 (conn->epoch & 0x80000000))
2708 /* the connection rxLastConn that was used the last time is not the
2709 ** one we are looking for now. Hence, start searching in the hash */
2711 conn = rx_connHashTable[hashindex];
2716 struct rx_service *service;
2717 if (type == RX_CLIENT_CONNECTION) {
2718 MUTEX_EXIT(&rx_connHashTable_lock);
2719 return (struct rx_connection *)0;
2721 service = rxi_FindService(socket, serviceId);
2722 if (!service || (securityIndex >= service->nSecurityObjects)
2723 || (service->securityObjects[securityIndex] == 0)) {
2724 MUTEX_EXIT(&rx_connHashTable_lock);
2725 return (struct rx_connection *)0;
2727 conn = rxi_AllocConnection(); /* This bzero's the connection */
2728 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2729 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2730 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2731 conn->next = rx_connHashTable[hashindex];
2732 rx_connHashTable[hashindex] = conn;
2733 conn->peer = rxi_FindPeer(host, port, 0, 1);
2734 conn->type = RX_SERVER_CONNECTION;
2735 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2736 conn->epoch = epoch;
2737 conn->cid = cid & RX_CIDMASK;
2738 /* conn->serial = conn->lastSerial = 0; */
2739 /* conn->timeout = 0; */
2740 conn->ackRate = RX_FAST_ACK_RATE;
2741 conn->service = service;
2742 conn->serviceId = serviceId;
2743 conn->securityIndex = securityIndex;
2744 conn->securityObject = service->securityObjects[securityIndex];
2745 conn->nSpecific = 0;
2746 conn->specific = NULL;
2747 rx_SetConnDeadTime(conn, service->connDeadTime);
2748 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2749 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2750 for (i = 0; i < RX_MAXCALLS; i++) {
2751 conn->twind[i] = rx_initSendWindow;
2752 conn->rwind[i] = rx_initReceiveWindow;
2754 /* Notify security object of the new connection */
2755 RXS_NewConnection(conn->securityObject, conn);
2756 /* XXXX Connection timeout? */
2757 if (service->newConnProc)
2758 (*service->newConnProc) (conn);
2759 if (rx_stats_active)
2760 rx_atomic_inc(&rx_stats.nServerConns);
2763 MUTEX_ENTER(&rx_refcnt_mutex);
2765 MUTEX_EXIT(&rx_refcnt_mutex);
2767 rxLastConn = conn; /* store this connection as the last conn used */
2768 MUTEX_EXIT(&rx_connHashTable_lock);
2772 /* There are two packet tracing routines available for testing and monitoring
2773 * Rx. One is called just after every packet is received and the other is
2774 * called just before every packet is sent. Received packets, have had their
2775 * headers decoded, and packets to be sent have not yet had their headers
2776 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2777 * containing the network address. Both can be modified. The return value, if
2778 * non-zero, indicates that the packet should be dropped. */
2780 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2781 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2783 /* A packet has been received off the interface. Np is the packet, socket is
2784 * the socket number it was received from (useful in determining which service
2785 * this packet corresponds to), and (host, port) reflect the host,port of the
2786 * sender. This call returns the packet to the caller if it is finished with
2787 * it, rather than de-allocating it, just as a small performance hack */
2790 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2791 afs_uint32 host, u_short port, int *tnop,
2792 struct rx_call **newcallp)
2794 struct rx_call *call;
2795 struct rx_connection *conn;
2797 afs_uint32 currentCallNumber;
2803 struct rx_packet *tnp;
2806 /* We don't print out the packet until now because (1) the time may not be
2807 * accurate enough until now in the lwp implementation (rx_Listener only gets
2808 * the time after the packet is read) and (2) from a protocol point of view,
2809 * this is the first time the packet has been seen */
2810 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2811 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2812 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2813 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2814 np->header.epoch, np->header.cid, np->header.callNumber,
2815 np->header.seq, np->header.flags, np));
2818 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2819 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2822 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2823 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2826 /* If an input tracer function is defined, call it with the packet and
2827 * network address. Note this function may modify its arguments. */
2828 if (rx_justReceived) {
2829 struct sockaddr_in addr;
2831 addr.sin_family = AF_INET;
2832 addr.sin_port = port;
2833 addr.sin_addr.s_addr = host;
2834 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2835 addr.sin_len = sizeof(addr);
2836 #endif /* AFS_OSF_ENV */
2837 drop = (*rx_justReceived) (np, &addr);
2838 /* drop packet if return value is non-zero */
2841 port = addr.sin_port; /* in case fcn changed addr */
2842 host = addr.sin_addr.s_addr;
2846 /* If packet was not sent by the client, then *we* must be the client */
2847 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2848 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2850 /* Find the connection (or fabricate one, if we're the server & if
2851 * necessary) associated with this packet */
2853 rxi_FindConnection(socket, host, port, np->header.serviceId,
2854 np->header.cid, np->header.epoch, type,
2855 np->header.securityIndex);
2858 /* If no connection found or fabricated, just ignore the packet.
2859 * (An argument could be made for sending an abort packet for
2864 MUTEX_ENTER(&conn->conn_data_lock);
2865 if (conn->maxSerial < np->header.serial)
2866 conn->maxSerial = np->header.serial;
2867 MUTEX_EXIT(&conn->conn_data_lock);
2869 /* If the connection is in an error state, send an abort packet and ignore
2870 * the incoming packet */
2872 /* Don't respond to an abort packet--we don't want loops! */
2873 MUTEX_ENTER(&conn->conn_data_lock);
2874 if (np->header.type != RX_PACKET_TYPE_ABORT)
2875 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2876 MUTEX_ENTER(&rx_refcnt_mutex);
2878 MUTEX_EXIT(&rx_refcnt_mutex);
2879 MUTEX_EXIT(&conn->conn_data_lock);
2883 /* Check for connection-only requests (i.e. not call specific). */
2884 if (np->header.callNumber == 0) {
2885 switch (np->header.type) {
2886 case RX_PACKET_TYPE_ABORT: {
2887 /* What if the supplied error is zero? */
2888 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2889 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
2890 rxi_ConnectionError(conn, errcode);
2891 MUTEX_ENTER(&rx_refcnt_mutex);
2893 MUTEX_EXIT(&rx_refcnt_mutex);
2896 case RX_PACKET_TYPE_CHALLENGE:
2897 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2898 MUTEX_ENTER(&rx_refcnt_mutex);
2900 MUTEX_EXIT(&rx_refcnt_mutex);
2902 case RX_PACKET_TYPE_RESPONSE:
2903 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2904 MUTEX_ENTER(&rx_refcnt_mutex);
2906 MUTEX_EXIT(&rx_refcnt_mutex);
2908 case RX_PACKET_TYPE_PARAMS:
2909 case RX_PACKET_TYPE_PARAMS + 1:
2910 case RX_PACKET_TYPE_PARAMS + 2:
2911 /* ignore these packet types for now */
2912 MUTEX_ENTER(&rx_refcnt_mutex);
2914 MUTEX_EXIT(&rx_refcnt_mutex);
2919 /* Should not reach here, unless the peer is broken: send an
2921 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2922 MUTEX_ENTER(&conn->conn_data_lock);
2923 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2924 MUTEX_ENTER(&rx_refcnt_mutex);
2926 MUTEX_EXIT(&rx_refcnt_mutex);
2927 MUTEX_EXIT(&conn->conn_data_lock);
2932 channel = np->header.cid & RX_CHANNELMASK;
2933 call = conn->call[channel];
2934 #ifdef RX_ENABLE_LOCKS
2936 MUTEX_ENTER(&call->lock);
2937 /* Test to see if call struct is still attached to conn. */
2938 if (call != conn->call[channel]) {
2940 MUTEX_EXIT(&call->lock);
2941 if (type == RX_SERVER_CONNECTION) {
2942 call = conn->call[channel];
2943 /* If we started with no call attached and there is one now,
2944 * another thread is also running this routine and has gotten
2945 * the connection channel. We should drop this packet in the tests
2946 * below. If there was a call on this connection and it's now
2947 * gone, then we'll be making a new call below.
2948 * If there was previously a call and it's now different then
2949 * the old call was freed and another thread running this routine
2950 * has created a call on this channel. One of these two threads
2951 * has a packet for the old call and the code below handles those
2955 MUTEX_ENTER(&call->lock);
2957 /* This packet can't be for this call. If the new call address is
2958 * 0 then no call is running on this channel. If there is a call
2959 * then, since this is a client connection we're getting data for
2960 * it must be for the previous call.
2962 if (rx_stats_active)
2963 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2964 MUTEX_ENTER(&rx_refcnt_mutex);
2966 MUTEX_EXIT(&rx_refcnt_mutex);
2971 currentCallNumber = conn->callNumber[channel];
2973 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2974 if (np->header.callNumber < currentCallNumber) {
2975 if (rx_stats_active)
2976 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2977 #ifdef RX_ENABLE_LOCKS
2979 MUTEX_EXIT(&call->lock);
2981 MUTEX_ENTER(&rx_refcnt_mutex);
2983 MUTEX_EXIT(&rx_refcnt_mutex);
2987 MUTEX_ENTER(&conn->conn_call_lock);
2988 call = rxi_NewCall(conn, channel);
2989 MUTEX_EXIT(&conn->conn_call_lock);
2990 *call->callNumber = np->header.callNumber;
2992 if (np->header.callNumber == 0)
2993 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",
2994 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2995 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2996 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2998 call->state = RX_STATE_PRECALL;
2999 clock_GetTime(&call->queueTime);
3000 hzero(call->bytesSent);
3001 hzero(call->bytesRcvd);
3003 * If the number of queued calls exceeds the overload
3004 * threshold then abort this call.
3006 if ((rx_BusyThreshold > 0) &&
3007 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3008 struct rx_packet *tp;
3010 rxi_CallError(call, rx_BusyError);
3011 tp = rxi_SendCallAbort(call, np, 1, 0);
3012 MUTEX_EXIT(&call->lock);
3013 MUTEX_ENTER(&rx_refcnt_mutex);
3015 MUTEX_EXIT(&rx_refcnt_mutex);
3016 if (rx_stats_active)
3017 rx_atomic_inc(&rx_stats.nBusies);
3020 rxi_KeepAliveOn(call);
3021 } else if (np->header.callNumber != currentCallNumber) {
3022 /* Wait until the transmit queue is idle before deciding
3023 * whether to reset the current call. Chances are that the
3024 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3027 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3028 if (call->state == RX_STATE_ACTIVE) {
3029 rxi_WaitforTQBusy(call);
3031 * If we entered error state while waiting,
3032 * must call rxi_CallError to permit rxi_ResetCall
3033 * to processed when the tqWaiter count hits zero.
3036 rxi_CallError(call, call->error);
3037 MUTEX_EXIT(&call->lock);
3038 MUTEX_ENTER(&rx_refcnt_mutex);
3040 MUTEX_EXIT(&rx_refcnt_mutex);
3044 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3045 /* If the new call cannot be taken right now send a busy and set
3046 * the error condition in this call, so that it terminates as
3047 * quickly as possible */
3048 if (call->state == RX_STATE_ACTIVE) {
3049 struct rx_packet *tp;
3051 rxi_CallError(call, RX_CALL_DEAD);
3052 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3054 MUTEX_EXIT(&call->lock);
3055 MUTEX_ENTER(&rx_refcnt_mutex);
3057 MUTEX_EXIT(&rx_refcnt_mutex);
3060 rxi_ResetCall(call, 0);
3061 *call->callNumber = np->header.callNumber;
3063 if (np->header.callNumber == 0)
3064 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",
3065 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3066 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3067 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3069 call->state = RX_STATE_PRECALL;
3070 clock_GetTime(&call->queueTime);
3071 hzero(call->bytesSent);
3072 hzero(call->bytesRcvd);
3074 * If the number of queued calls exceeds the overload
3075 * threshold then abort this call.
3077 if ((rx_BusyThreshold > 0) &&
3078 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3079 struct rx_packet *tp;
3081 rxi_CallError(call, rx_BusyError);
3082 tp = rxi_SendCallAbort(call, np, 1, 0);
3083 MUTEX_EXIT(&call->lock);
3084 MUTEX_ENTER(&rx_refcnt_mutex);
3086 MUTEX_EXIT(&rx_refcnt_mutex);
3087 if (rx_stats_active)
3088 rx_atomic_inc(&rx_stats.nBusies);
3091 rxi_KeepAliveOn(call);
3093 /* Continuing call; do nothing here. */
3095 } else { /* we're the client */
3096 /* Ignore all incoming acknowledgements for calls in DALLY state */
3097 if (call && (call->state == RX_STATE_DALLY)
3098 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3099 if (rx_stats_active)
3100 rx_atomic_inc(&rx_stats.ignorePacketDally);
3101 #ifdef RX_ENABLE_LOCKS
3103 MUTEX_EXIT(&call->lock);
3106 MUTEX_ENTER(&rx_refcnt_mutex);
3108 MUTEX_EXIT(&rx_refcnt_mutex);
3112 /* Ignore anything that's not relevant to the current call. If there
3113 * isn't a current call, then no packet is relevant. */
3114 if (!call || (np->header.callNumber != currentCallNumber)) {
3115 if (rx_stats_active)
3116 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3117 #ifdef RX_ENABLE_LOCKS
3119 MUTEX_EXIT(&call->lock);
3122 MUTEX_ENTER(&rx_refcnt_mutex);
3124 MUTEX_EXIT(&rx_refcnt_mutex);
3127 /* If the service security object index stamped in the packet does not
3128 * match the connection's security index, ignore the packet */
3129 if (np->header.securityIndex != conn->securityIndex) {
3130 #ifdef RX_ENABLE_LOCKS
3131 MUTEX_EXIT(&call->lock);
3133 MUTEX_ENTER(&rx_refcnt_mutex);
3135 MUTEX_EXIT(&rx_refcnt_mutex);
3139 /* If we're receiving the response, then all transmit packets are
3140 * implicitly acknowledged. Get rid of them. */
3141 if (np->header.type == RX_PACKET_TYPE_DATA) {
3142 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3143 /* XXX Hack. Because we must release the global rx lock when
3144 * sending packets (osi_NetSend) we drop all acks while we're
3145 * traversing the tq in rxi_Start sending packets out because
3146 * packets may move to the freePacketQueue as result of being here!
3147 * So we drop these packets until we're safely out of the
3148 * traversing. Really ugly!
3149 * For fine grain RX locking, we set the acked field in the
3150 * packets and let rxi_Start remove them from the transmit queue.
3152 if (call->flags & RX_CALL_TQ_BUSY) {
3153 #ifdef RX_ENABLE_LOCKS
3154 rxi_SetAcksInTransmitQueue(call);
3156 MUTEX_ENTER(&rx_refcnt_mutex);
3158 MUTEX_EXIT(&rx_refcnt_mutex);
3159 return np; /* xmitting; drop packet */
3162 rxi_ClearTransmitQueue(call, 0);
3164 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3165 rxi_ClearTransmitQueue(call, 0);
3166 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3168 if (np->header.type == RX_PACKET_TYPE_ACK) {
3169 /* now check to see if this is an ack packet acknowledging that the
3170 * server actually *lost* some hard-acked data. If this happens we
3171 * ignore this packet, as it may indicate that the server restarted in
3172 * the middle of a call. It is also possible that this is an old ack
3173 * packet. We don't abort the connection in this case, because this
3174 * *might* just be an old ack packet. The right way to detect a server
3175 * restart in the midst of a call is to notice that the server epoch
3177 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3178 * XXX unacknowledged. I think that this is off-by-one, but
3179 * XXX I don't dare change it just yet, since it will
3180 * XXX interact badly with the server-restart detection
3181 * XXX code in receiveackpacket. */
3182 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3183 if (rx_stats_active)
3184 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3185 MUTEX_EXIT(&call->lock);
3186 MUTEX_ENTER(&rx_refcnt_mutex);
3188 MUTEX_EXIT(&rx_refcnt_mutex);
3192 } /* else not a data packet */
3195 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3196 /* Set remote user defined status from packet */
3197 call->remoteStatus = np->header.userStatus;
3199 /* Note the gap between the expected next packet and the actual
3200 * packet that arrived, when the new packet has a smaller serial number
3201 * than expected. Rioses frequently reorder packets all by themselves,
3202 * so this will be quite important with very large window sizes.
3203 * Skew is checked against 0 here to avoid any dependence on the type of
3204 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3206 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3207 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3208 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3210 MUTEX_ENTER(&conn->conn_data_lock);
3211 skew = conn->lastSerial - np->header.serial;
3212 conn->lastSerial = np->header.serial;
3213 MUTEX_EXIT(&conn->conn_data_lock);
3215 struct rx_peer *peer;
3217 if (skew > peer->inPacketSkew) {
3218 dpf(("*** In skew changed from %d to %d\n",
3219 peer->inPacketSkew, skew));
3220 peer->inPacketSkew = skew;
3224 /* Now do packet type-specific processing */
3225 switch (np->header.type) {
3226 case RX_PACKET_TYPE_DATA:
3227 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3230 case RX_PACKET_TYPE_ACK:
3231 /* Respond immediately to ack packets requesting acknowledgement
3233 if (np->header.flags & RX_REQUEST_ACK) {
3235 (void)rxi_SendCallAbort(call, 0, 1, 0);
3237 (void)rxi_SendAck(call, 0, np->header.serial,
3238 RX_ACK_PING_RESPONSE, 1);
3240 np = rxi_ReceiveAckPacket(call, np, 1);
3242 case RX_PACKET_TYPE_ABORT: {
3243 /* An abort packet: reset the call, passing the error up to the user. */
3244 /* What if error is zero? */
3245 /* What if the error is -1? the application will treat it as a timeout. */
3246 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3247 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3248 rxi_CallError(call, errdata);
3249 MUTEX_EXIT(&call->lock);
3250 MUTEX_ENTER(&rx_refcnt_mutex);
3252 MUTEX_EXIT(&rx_refcnt_mutex);
3253 return np; /* xmitting; drop packet */
3255 case RX_PACKET_TYPE_BUSY:
3258 case RX_PACKET_TYPE_ACKALL:
3259 /* All packets acknowledged, so we can drop all packets previously
3260 * readied for sending */
3261 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3262 /* XXX Hack. We because we can't release the global rx lock when
3263 * sending packets (osi_NetSend) we drop all ack pkts while we're
3264 * traversing the tq in rxi_Start sending packets out because
3265 * packets may move to the freePacketQueue as result of being
3266 * here! So we drop these packets until we're safely out of the
3267 * traversing. Really ugly!
3268 * For fine grain RX locking, we set the acked field in the packets
3269 * and let rxi_Start remove the packets from the transmit queue.
3271 if (call->flags & RX_CALL_TQ_BUSY) {
3272 #ifdef RX_ENABLE_LOCKS
3273 rxi_SetAcksInTransmitQueue(call);
3275 #else /* RX_ENABLE_LOCKS */
3276 MUTEX_EXIT(&call->lock);
3277 MUTEX_ENTER(&rx_refcnt_mutex);
3279 MUTEX_EXIT(&rx_refcnt_mutex);
3280 return np; /* xmitting; drop packet */
3281 #endif /* RX_ENABLE_LOCKS */
3283 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3284 rxi_ClearTransmitQueue(call, 0);
3285 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3288 /* Should not reach here, unless the peer is broken: send an abort
3290 rxi_CallError(call, RX_PROTOCOL_ERROR);
3291 np = rxi_SendCallAbort(call, np, 1, 0);
3294 /* Note when this last legitimate packet was received, for keep-alive
3295 * processing. Note, we delay getting the time until now in the hope that
3296 * the packet will be delivered to the user before any get time is required
3297 * (if not, then the time won't actually be re-evaluated here). */
3298 call->lastReceiveTime = clock_Sec();
3299 MUTEX_EXIT(&call->lock);
3300 MUTEX_ENTER(&rx_refcnt_mutex);
3302 MUTEX_EXIT(&rx_refcnt_mutex);
3306 /* return true if this is an "interesting" connection from the point of view
3307 of someone trying to debug the system */
3309 rxi_IsConnInteresting(struct rx_connection *aconn)
3312 struct rx_call *tcall;
3314 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3317 for (i = 0; i < RX_MAXCALLS; i++) {
3318 tcall = aconn->call[i];
3320 if ((tcall->state == RX_STATE_PRECALL)
3321 || (tcall->state == RX_STATE_ACTIVE))
3323 if ((tcall->mode == RX_MODE_SENDING)
3324 || (tcall->mode == RX_MODE_RECEIVING))
3332 /* if this is one of the last few packets AND it wouldn't be used by the
3333 receiving call to immediately satisfy a read request, then drop it on
3334 the floor, since accepting it might prevent a lock-holding thread from
3335 making progress in its reading. If a call has been cleared while in
3336 the precall state then ignore all subsequent packets until the call
3337 is assigned to a thread. */
3340 TooLow(struct rx_packet *ap, struct rx_call *acall)
3344 MUTEX_ENTER(&rx_quota_mutex);
3345 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3346 && (acall->state == RX_STATE_PRECALL))
3347 || ((rx_nFreePackets < rxi_dataQuota + 2)
3348 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3349 && (acall->flags & RX_CALL_READER_WAIT)))) {
3352 MUTEX_EXIT(&rx_quota_mutex);
3358 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3360 struct rx_connection *conn = arg1;
3361 struct rx_call *acall = arg2;
3362 struct rx_call *call = acall;
3363 struct clock when, now;
3366 MUTEX_ENTER(&conn->conn_data_lock);
3367 conn->checkReachEvent = NULL;
3368 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3370 MUTEX_ENTER(&rx_refcnt_mutex);
3372 MUTEX_EXIT(&rx_refcnt_mutex);
3374 MUTEX_EXIT(&conn->conn_data_lock);
3378 MUTEX_ENTER(&conn->conn_call_lock);
3379 MUTEX_ENTER(&conn->conn_data_lock);
3380 for (i = 0; i < RX_MAXCALLS; i++) {
3381 struct rx_call *tc = conn->call[i];
3382 if (tc && tc->state == RX_STATE_PRECALL) {
3388 /* Indicate that rxi_CheckReachEvent is no longer running by
3389 * clearing the flag. Must be atomic under conn_data_lock to
3390 * avoid a new call slipping by: rxi_CheckConnReach holds
3391 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3393 conn->flags &= ~RX_CONN_ATTACHWAIT;
3394 MUTEX_EXIT(&conn->conn_data_lock);
3395 MUTEX_EXIT(&conn->conn_call_lock);
3400 MUTEX_ENTER(&call->lock);
3401 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3403 MUTEX_EXIT(&call->lock);
3405 clock_GetTime(&now);
3407 when.sec += RX_CHECKREACH_TIMEOUT;
3408 MUTEX_ENTER(&conn->conn_data_lock);
3409 if (!conn->checkReachEvent) {
3410 MUTEX_ENTER(&rx_refcnt_mutex);
3412 MUTEX_EXIT(&rx_refcnt_mutex);
3413 conn->checkReachEvent =
3414 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3417 MUTEX_EXIT(&conn->conn_data_lock);
3423 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3425 struct rx_service *service = conn->service;
3426 struct rx_peer *peer = conn->peer;
3427 afs_uint32 now, lastReach;
3429 if (service->checkReach == 0)
3433 MUTEX_ENTER(&peer->peer_lock);
3434 lastReach = peer->lastReachTime;
3435 MUTEX_EXIT(&peer->peer_lock);
3436 if (now - lastReach < RX_CHECKREACH_TTL)
3439 MUTEX_ENTER(&conn->conn_data_lock);
3440 if (conn->flags & RX_CONN_ATTACHWAIT) {
3441 MUTEX_EXIT(&conn->conn_data_lock);
3444 conn->flags |= RX_CONN_ATTACHWAIT;
3445 MUTEX_EXIT(&conn->conn_data_lock);
3446 if (!conn->checkReachEvent)
3447 rxi_CheckReachEvent(NULL, conn, call);
3452 /* try to attach call, if authentication is complete */
3454 TryAttach(struct rx_call *acall, osi_socket socket,
3455 int *tnop, struct rx_call **newcallp,
3458 struct rx_connection *conn = acall->conn;
3460 if (conn->type == RX_SERVER_CONNECTION
3461 && acall->state == RX_STATE_PRECALL) {
3462 /* Don't attach until we have any req'd. authentication. */
3463 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3464 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3465 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3466 /* Note: this does not necessarily succeed; there
3467 * may not any proc available
3470 rxi_ChallengeOn(acall->conn);
3475 /* A data packet has been received off the interface. This packet is
3476 * appropriate to the call (the call is in the right state, etc.). This
3477 * routine can return a packet to the caller, for re-use */
3480 rxi_ReceiveDataPacket(struct rx_call *call,
3481 struct rx_packet *np, int istack,
3482 osi_socket socket, afs_uint32 host, u_short port,
3483 int *tnop, struct rx_call **newcallp)
3485 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3490 afs_uint32 serial=0, flags=0;
3492 struct rx_packet *tnp;
3493 struct clock when, now;
3494 if (rx_stats_active)
3495 rx_atomic_inc(&rx_stats.dataPacketsRead);
3498 /* If there are no packet buffers, drop this new packet, unless we can find
3499 * packet buffers from inactive calls */
3501 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3502 MUTEX_ENTER(&rx_freePktQ_lock);
3503 rxi_NeedMorePackets = TRUE;
3504 MUTEX_EXIT(&rx_freePktQ_lock);
3505 if (rx_stats_active)
3506 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3507 call->rprev = np->header.serial;
3508 rxi_calltrace(RX_TRACE_DROP, call);
3509 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3511 rxi_ClearReceiveQueue(call);
3512 clock_GetTime(&now);
3514 clock_Add(&when, &rx_softAckDelay);
3515 if (!call->delayedAckEvent
3516 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3517 rxevent_Cancel(call->delayedAckEvent, call,
3518 RX_CALL_REFCOUNT_DELAY);
3519 MUTEX_ENTER(&rx_refcnt_mutex);
3520 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3521 MUTEX_EXIT(&rx_refcnt_mutex);
3523 call->delayedAckEvent =
3524 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3526 /* we've damaged this call already, might as well do it in. */
3532 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3533 * packet is one of several packets transmitted as a single
3534 * datagram. Do not send any soft or hard acks until all packets
3535 * in a jumbogram have been processed. Send negative acks right away.
3537 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3538 /* tnp is non-null when there are more packets in the
3539 * current jumbo gram */
3546 seq = np->header.seq;
3547 serial = np->header.serial;
3548 flags = np->header.flags;
3550 /* If the call is in an error state, send an abort message */
3552 return rxi_SendCallAbort(call, np, istack, 0);
3554 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3555 * AFS 3.5 jumbogram. */
3556 if (flags & RX_JUMBO_PACKET) {
3557 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3562 if (np->header.spare != 0) {
3563 MUTEX_ENTER(&call->conn->conn_data_lock);
3564 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3565 MUTEX_EXIT(&call->conn->conn_data_lock);
3568 /* The usual case is that this is the expected next packet */
3569 if (seq == call->rnext) {
3571 /* Check to make sure it is not a duplicate of one already queued */
3572 if (queue_IsNotEmpty(&call->rq)
3573 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3574 if (rx_stats_active)
3575 rx_atomic_inc(&rx_stats.dupPacketsRead);
3576 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3577 rxevent_Cancel(call->delayedAckEvent, call,
3578 RX_CALL_REFCOUNT_DELAY);
3579 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3585 /* It's the next packet. Stick it on the receive queue
3586 * for this call. Set newPackets to make sure we wake
3587 * the reader once all packets have been processed */
3588 #ifdef RX_TRACK_PACKETS
3589 np->flags |= RX_PKTFLAG_RQ;
3591 queue_Prepend(&call->rq, np);
3592 #ifdef RXDEBUG_PACKET
3594 #endif /* RXDEBUG_PACKET */
3596 np = NULL; /* We can't use this anymore */
3599 /* If an ack is requested then set a flag to make sure we
3600 * send an acknowledgement for this packet */
3601 if (flags & RX_REQUEST_ACK) {
3602 ackNeeded = RX_ACK_REQUESTED;
3605 /* Keep track of whether we have received the last packet */
3606 if (flags & RX_LAST_PACKET) {
3607 call->flags |= RX_CALL_HAVE_LAST;
3611 /* Check whether we have all of the packets for this call */
3612 if (call->flags & RX_CALL_HAVE_LAST) {
3613 afs_uint32 tseq; /* temporary sequence number */
3614 struct rx_packet *tp; /* Temporary packet pointer */
3615 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3617 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3618 if (tseq != tp->header.seq)
3620 if (tp->header.flags & RX_LAST_PACKET) {
3621 call->flags |= RX_CALL_RECEIVE_DONE;
3628 /* Provide asynchronous notification for those who want it
3629 * (e.g. multi rx) */
3630 if (call->arrivalProc) {
3631 (*call->arrivalProc) (call, call->arrivalProcHandle,
3632 call->arrivalProcArg);
3633 call->arrivalProc = (void (*)())0;
3636 /* Update last packet received */
3639 /* If there is no server process serving this call, grab
3640 * one, if available. We only need to do this once. If a
3641 * server thread is available, this thread becomes a server
3642 * thread and the server thread becomes a listener thread. */
3644 TryAttach(call, socket, tnop, newcallp, 0);
3647 /* This is not the expected next packet. */
3649 /* Determine whether this is a new or old packet, and if it's
3650 * a new one, whether it fits into the current receive window.
3651 * Also figure out whether the packet was delivered in sequence.
3652 * We use the prev variable to determine whether the new packet
3653 * is the successor of its immediate predecessor in the
3654 * receive queue, and the missing flag to determine whether
3655 * any of this packets predecessors are missing. */
3657 afs_uint32 prev; /* "Previous packet" sequence number */
3658 struct rx_packet *tp; /* Temporary packet pointer */
3659 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3660 int missing; /* Are any predecessors missing? */
3662 /* If the new packet's sequence number has been sent to the
3663 * application already, then this is a duplicate */
3664 if (seq < call->rnext) {
3665 if (rx_stats_active)
3666 rx_atomic_inc(&rx_stats.dupPacketsRead);
3667 rxevent_Cancel(call->delayedAckEvent, call,
3668 RX_CALL_REFCOUNT_DELAY);
3669 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3675 /* If the sequence number is greater than what can be
3676 * accomodated by the current window, then send a negative
3677 * acknowledge and drop the packet */
3678 if ((call->rnext + call->rwind) <= seq) {
3679 rxevent_Cancel(call->delayedAckEvent, call,
3680 RX_CALL_REFCOUNT_DELAY);
3681 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3688 /* Look for the packet in the queue of old received packets */
3689 for (prev = call->rnext - 1, missing =
3690 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3691 /*Check for duplicate packet */
3692 if (seq == tp->header.seq) {
3693 if (rx_stats_active)
3694 rx_atomic_inc(&rx_stats.dupPacketsRead);
3695 rxevent_Cancel(call->delayedAckEvent, call,