2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
14 #include "afs/param.h"
16 #include <afs/param.h>
21 #include "afs/sysincludes.h"
22 #include "afsincludes.h"
28 #include <net/net_globals.h>
29 #endif /* AFS_OSF_ENV */
30 #ifdef AFS_LINUX20_ENV
33 #include "netinet/in.h"
35 #include "inet/common.h"
37 #include "inet/ip_ire.h"
39 #include "afs/afs_args.h"
40 #include "afs/afs_osi.h"
41 #ifdef RX_KERNEL_TRACE
42 #include "rx_kcommon.h"
44 #if (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
48 #undef RXDEBUG /* turn off debugging */
50 #if defined(AFS_SGI_ENV)
51 #include "sys/debug.h"
59 #endif /* AFS_OSF_ENV */
61 #include "afs/sysincludes.h"
62 #include "afsincludes.h"
65 #include "rx_kmutex.h"
66 #include "rx_kernel.h"
70 #include "rx_globals.h"
72 #include "rx_atomic.h"
73 #include "rx_internal.h"
75 #define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
76 #define AFSOP_STOP_AFS 211 /* Stop AFS process */
77 #define AFSOP_STOP_BKG 212 /* Stop BKG process */
79 extern afs_int32 afs_termState;
81 #include "sys/lockl.h"
82 #include "sys/lock_def.h"
83 #endif /* AFS_AIX41_ENV */
84 # include "afs/rxgen_consts.h"
86 # include <sys/types.h>
96 # include <afs/afsutil.h>
97 # include <WINNT\afsreg.h>
99 # include <sys/socket.h>
100 # include <sys/file.h>
102 # include <sys/stat.h>
103 # include <netinet/in.h>
104 # include <sys/time.h>
107 # include "rx_user.h"
108 # include "rx_clock.h"
109 # include "rx_queue.h"
110 # include "rx_atomic.h"
111 # include "rx_globals.h"
112 # include "rx_trace.h"
113 # include "rx_internal.h"
114 # include "rx_stats.h"
115 # include <afs/rxgen_consts.h>
119 #ifdef AFS_PTHREAD_ENV
121 int (*registerProgram) (pid_t, char *) = 0;
122 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
125 int (*registerProgram) (PROCESS, char *) = 0;
126 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
130 /* Local static routines */
131 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
132 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
133 struct rx_peer *, struct clock *);
135 #ifdef RX_ENABLE_LOCKS
136 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
139 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
141 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
142 rx_atomic_t rxi_start_in_error;
144 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
147 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
148 * currently allocated within rx. This number is used to allocate the
149 * memory required to return the statistics when queried.
150 * Protected by the rx_rpc_stats mutex.
153 static unsigned int rxi_rpc_peer_stat_cnt;
156 * rxi_rpc_process_stat_cnt counts the total number of local process stat
157 * structures currently allocated within rx. The number is used to allocate
158 * the memory required to return the statistics when queried.
159 * Protected by the rx_rpc_stats mutex.
162 static unsigned int rxi_rpc_process_stat_cnt;
164 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
165 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
167 #if !defined(offsetof)
168 #include <stddef.h> /* for definition of offsetof() */
171 #ifdef RX_ENABLE_LOCKS
172 afs_kmutex_t rx_atomic_mutex;
175 #ifdef AFS_PTHREAD_ENV
178 * Use procedural initialization of mutexes/condition variables
182 extern afs_kmutex_t rx_quota_mutex;
183 extern afs_kmutex_t rx_pthread_mutex;
184 extern afs_kmutex_t rx_packets_mutex;
185 extern afs_kmutex_t rx_refcnt_mutex;
186 extern afs_kmutex_t des_init_mutex;
187 extern afs_kmutex_t des_random_mutex;
188 extern afs_kmutex_t rx_clock_mutex;
189 extern afs_kmutex_t rxi_connCacheMutex;
190 extern afs_kmutex_t rx_event_mutex;
191 extern afs_kmutex_t osi_malloc_mutex;
192 extern afs_kmutex_t event_handler_mutex;
193 extern afs_kmutex_t listener_mutex;
194 extern afs_kmutex_t rx_if_init_mutex;
195 extern afs_kmutex_t rx_if_mutex;
196 extern afs_kmutex_t rxkad_client_uid_mutex;
197 extern afs_kmutex_t rxkad_random_mutex;
199 extern afs_kcondvar_t rx_event_handler_cond;
200 extern afs_kcondvar_t rx_listener_cond;
202 static afs_kmutex_t epoch_mutex;
203 static afs_kmutex_t rx_init_mutex;
204 static afs_kmutex_t rx_debug_mutex;
205 static afs_kmutex_t rx_rpc_stats;
208 rxi_InitPthread(void)
210 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
211 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
212 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
213 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
214 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
215 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
216 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
217 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
218 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
219 MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
220 MUTEX_INIT(&des_init_mutex, "des", MUTEX_DEFAULT, 0);
221 MUTEX_INIT(&des_random_mutex, "random", MUTEX_DEFAULT, 0);
222 MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
223 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
224 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
225 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
226 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
227 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
228 MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
229 MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
230 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
232 osi_Assert(pthread_cond_init
233 (&rx_event_handler_cond, (const pthread_condattr_t *)0) == 0);
234 osi_Assert(pthread_cond_init(&rx_listener_cond, (const pthread_condattr_t *)0)
236 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
237 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
239 rxkad_global_stats_init();
241 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
242 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
243 #ifdef RX_ENABLE_LOCKS
246 #endif /* RX_LOCKS_DB */
247 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
248 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
250 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
252 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
254 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
256 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
257 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
258 #endif /* RX_ENABLE_LOCKS */
261 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
262 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
264 * The rx_stats_mutex mutex protects the following global variables:
265 * rxi_lowConnRefCount
266 * rxi_lowPeerRefCount
275 * The rx_quota_mutex mutex protects the following global variables:
283 * The rx_freePktQ_lock protects the following global variables:
288 * The rx_packets_mutex mutex protects the following global variables:
296 * The rx_pthread_mutex mutex protects the following global variables:
297 * rxi_fcfs_thread_num
300 #define INIT_PTHREAD_LOCKS
304 /* Variables for handling the minProcs implementation. availProcs gives the
305 * number of threads available in the pool at this moment (not counting dudes
306 * executing right now). totalMin gives the total number of procs required
307 * for handling all minProcs requests. minDeficit is a dynamic variable
308 * tracking the # of procs required to satisfy all of the remaining minProcs
310 * For fine grain locking to work, the quota check and the reservation of
311 * a server thread has to come while rxi_availProcs and rxi_minDeficit
312 * are locked. To this end, the code has been modified under #ifdef
313 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
314 * same time. A new function, ReturnToServerPool() returns the allocation.
316 * A call can be on several queue's (but only one at a time). When
317 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
318 * that no one else is touching the queue. To this end, we store the address
319 * of the queue lock in the call structure (under the call lock) when we
320 * put the call on a queue, and we clear the call_queue_lock when the
321 * call is removed from a queue (once the call lock has been obtained).
322 * This allows rxi_ResetCall to safely synchronize with others wishing
323 * to manipulate the queue.
326 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
327 static afs_kmutex_t rx_rpc_stats;
328 void rxi_StartUnlocked(struct rxevent *event, void *call,
329 void *arg1, int istack);
332 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
333 ** pretty good that the next packet coming in is from the same connection
334 ** as the last packet, since we're send multiple packets in a transmit window.
336 struct rx_connection *rxLastConn = 0;
338 #ifdef RX_ENABLE_LOCKS
339 /* The locking hierarchy for rx fine grain locking is composed of these
342 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
343 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
344 * call->lock - locks call data fields.
345 * These are independent of each other:
346 * rx_freeCallQueue_lock
351 * serverQueueEntry->lock
352 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
354 * peer->lock - locks peer data fields.
355 * conn_data_lock - that more than one thread is not updating a conn data
356 * field at the same time.
367 * Do we need a lock to protect the peer field in the conn structure?
368 * conn->peer was previously a constant for all intents and so has no
369 * lock protecting this field. The multihomed client delta introduced
370 * a RX code change : change the peer field in the connection structure
371 * to that remote interface from which the last packet for this
372 * connection was sent out. This may become an issue if further changes
375 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
376 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
378 /* rxdb_fileID is used to identify the lock location, along with line#. */
379 static int rxdb_fileID = RXDB_FILE_RX;
380 #endif /* RX_LOCKS_DB */
381 #else /* RX_ENABLE_LOCKS */
382 #define SET_CALL_QUEUE_LOCK(C, L)
383 #define CLEAR_CALL_QUEUE_LOCK(C)
384 #endif /* RX_ENABLE_LOCKS */
385 struct rx_serverQueueEntry *rx_waitForPacket = 0;
386 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
388 /* ------------Exported Interfaces------------- */
390 /* This function allows rxkad to set the epoch to a suitably random number
391 * which rx_NewConnection will use in the future. The principle purpose is to
392 * get rxnull connections to use the same epoch as the rxkad connections do, at
393 * least once the first rxkad connection is established. This is important now
394 * that the host/port addresses aren't used in FindConnection: the uniqueness
395 * of epoch/cid matters and the start time won't do. */
397 #ifdef AFS_PTHREAD_ENV
399 * This mutex protects the following global variables:
403 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
404 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
408 #endif /* AFS_PTHREAD_ENV */
411 rx_SetEpoch(afs_uint32 epoch)
418 /* Initialize rx. A port number may be mentioned, in which case this
419 * becomes the default port number for any service installed later.
420 * If 0 is provided for the port number, a random port will be chosen
421 * by the kernel. Whether this will ever overlap anything in
422 * /etc/services is anybody's guess... Returns 0 on success, -1 on
427 int rxinit_status = 1;
428 #ifdef AFS_PTHREAD_ENV
430 * This mutex protects the following global variables:
434 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
435 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
438 #define UNLOCK_RX_INIT
442 rx_InitHost(u_int host, u_int port)
449 char *htable, *ptable;
456 if (rxinit_status == 0) {
457 tmp_status = rxinit_status;
459 return tmp_status; /* Already started; return previous error code. */
465 if (afs_winsockInit() < 0)
471 * Initialize anything necessary to provide a non-premptive threading
474 rxi_InitializeThreadSupport();
477 /* Allocate and initialize a socket for client and perhaps server
480 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
481 if (rx_socket == OSI_NULLSOCKET) {
485 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
488 #endif /* RX_LOCKS_DB */
489 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
490 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
491 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
492 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
493 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
494 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
495 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
496 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
497 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
499 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
501 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
503 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
505 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
506 #if defined(AFS_HPUX110_ENV)
508 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
509 #endif /* AFS_HPUX110_ENV */
510 #endif /* RX_ENABLE_LOCKS && KERNEL */
513 rx_connDeadTime = 12;
514 rx_tranquil = 0; /* reset flag */
515 rxi_ResetStatistics();
517 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
518 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
519 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
520 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
521 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
522 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
524 /* Malloc up a bunch of packets & buffers */
526 queue_Init(&rx_freePacketQueue);
527 rxi_NeedMorePackets = FALSE;
528 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
530 /* enforce a minimum number of allocated packets */
531 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
532 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
534 /* allocate the initial free packet pool */
535 #ifdef RX_ENABLE_TSFPQ
536 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
537 #else /* RX_ENABLE_TSFPQ */
538 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
539 #endif /* RX_ENABLE_TSFPQ */
546 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
547 tv.tv_sec = clock_now.sec;
548 tv.tv_usec = clock_now.usec;
549 srand((unsigned int)tv.tv_usec);
556 #if defined(KERNEL) && !defined(UKERNEL)
557 /* Really, this should never happen in a real kernel */
560 struct sockaddr_in addr;
562 int addrlen = sizeof(addr);
564 socklen_t addrlen = sizeof(addr);
566 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
570 rx_port = addr.sin_port;
573 rx_stats.minRtt.sec = 9999999;
575 rx_SetEpoch(tv.tv_sec | 0x80000000);
577 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
578 * will provide a randomer value. */
580 MUTEX_ENTER(&rx_quota_mutex);
581 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
582 MUTEX_EXIT(&rx_quota_mutex);
583 /* *Slightly* random start time for the cid. This is just to help
584 * out with the hashing function at the peer */
585 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
586 rx_connHashTable = (struct rx_connection **)htable;
587 rx_peerHashTable = (struct rx_peer **)ptable;
589 rx_lastAckDelay.sec = 0;
590 rx_lastAckDelay.usec = 400000; /* 400 milliseconds */
591 rx_hardAckDelay.sec = 0;
592 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
593 rx_softAckDelay.sec = 0;
594 rx_softAckDelay.usec = 100000; /* 100 milliseconds */
596 rxevent_Init(20, rxi_ReScheduleEvents);
598 /* Initialize various global queues */
599 queue_Init(&rx_idleServerQueue);
600 queue_Init(&rx_incomingCallQueue);
601 queue_Init(&rx_freeCallQueue);
603 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
604 /* Initialize our list of usable IP addresses. */
608 /* Start listener process (exact function is dependent on the
609 * implementation environment--kernel or user space) */
613 tmp_status = rxinit_status = 0;
621 return rx_InitHost(htonl(INADDR_ANY), port);
624 /* called with unincremented nRequestsRunning to see if it is OK to start
625 * a new thread in this service. Could be "no" for two reasons: over the
626 * max quota, or would prevent others from reaching their min quota.
628 #ifdef RX_ENABLE_LOCKS
629 /* This verion of QuotaOK reserves quota if it's ok while the
630 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
633 QuotaOK(struct rx_service *aservice)
635 /* check if over max quota */
636 if (aservice->nRequestsRunning >= aservice->maxProcs) {
640 /* under min quota, we're OK */
641 /* otherwise, can use only if there are enough to allow everyone
642 * to go to their min quota after this guy starts.
645 MUTEX_ENTER(&rx_quota_mutex);
646 if ((aservice->nRequestsRunning < aservice->minProcs)
647 || (rxi_availProcs > rxi_minDeficit)) {
648 aservice->nRequestsRunning++;
649 /* just started call in minProcs pool, need fewer to maintain
651 if (aservice->nRequestsRunning <= aservice->minProcs)
654 MUTEX_EXIT(&rx_quota_mutex);
657 MUTEX_EXIT(&rx_quota_mutex);
663 ReturnToServerPool(struct rx_service *aservice)
665 aservice->nRequestsRunning--;
666 MUTEX_ENTER(&rx_quota_mutex);
667 if (aservice->nRequestsRunning < aservice->minProcs)
670 MUTEX_EXIT(&rx_quota_mutex);
673 #else /* RX_ENABLE_LOCKS */
675 QuotaOK(struct rx_service *aservice)
678 /* under min quota, we're OK */
679 if (aservice->nRequestsRunning < aservice->minProcs)
682 /* check if over max quota */
683 if (aservice->nRequestsRunning >= aservice->maxProcs)
686 /* otherwise, can use only if there are enough to allow everyone
687 * to go to their min quota after this guy starts.
689 MUTEX_ENTER(&rx_quota_mutex);
690 if (rxi_availProcs > rxi_minDeficit)
692 MUTEX_EXIT(&rx_quota_mutex);
695 #endif /* RX_ENABLE_LOCKS */
698 /* Called by rx_StartServer to start up lwp's to service calls.
699 NExistingProcs gives the number of procs already existing, and which
700 therefore needn't be created. */
702 rxi_StartServerProcs(int nExistingProcs)
704 struct rx_service *service;
709 /* For each service, reserve N processes, where N is the "minimum"
710 * number of processes that MUST be able to execute a request in parallel,
711 * at any time, for that process. Also compute the maximum difference
712 * between any service's maximum number of processes that can run
713 * (i.e. the maximum number that ever will be run, and a guarantee
714 * that this number will run if other services aren't running), and its
715 * minimum number. The result is the extra number of processes that
716 * we need in order to provide the latter guarantee */
717 for (i = 0; i < RX_MAX_SERVICES; i++) {
719 service = rx_services[i];
720 if (service == (struct rx_service *)0)
722 nProcs += service->minProcs;
723 diff = service->maxProcs - service->minProcs;
727 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
728 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
729 for (i = 0; i < nProcs; i++) {
730 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
736 /* This routine is only required on Windows */
738 rx_StartClientThread(void)
740 #ifdef AFS_PTHREAD_ENV
742 pid = pthread_self();
743 #endif /* AFS_PTHREAD_ENV */
745 #endif /* AFS_NT40_ENV */
747 /* This routine must be called if any services are exported. If the
748 * donateMe flag is set, the calling process is donated to the server
751 rx_StartServer(int donateMe)
753 struct rx_service *service;
759 /* Start server processes, if necessary (exact function is dependent
760 * on the implementation environment--kernel or user space). DonateMe
761 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
762 * case, one less new proc will be created rx_StartServerProcs.
764 rxi_StartServerProcs(donateMe);
766 /* count up the # of threads in minProcs, and add set the min deficit to
767 * be that value, too.
769 for (i = 0; i < RX_MAX_SERVICES; i++) {
770 service = rx_services[i];
771 if (service == (struct rx_service *)0)
773 MUTEX_ENTER(&rx_quota_mutex);
774 rxi_totalMin += service->minProcs;
775 /* below works even if a thread is running, since minDeficit would
776 * still have been decremented and later re-incremented.
778 rxi_minDeficit += service->minProcs;
779 MUTEX_EXIT(&rx_quota_mutex);
782 /* Turn on reaping of idle server connections */
783 rxi_ReapConnections(NULL, NULL, NULL);
792 #ifdef AFS_PTHREAD_ENV
794 pid = afs_pointer_to_int(pthread_self());
795 #else /* AFS_PTHREAD_ENV */
797 LWP_CurrentProcess(&pid);
798 #endif /* AFS_PTHREAD_ENV */
800 sprintf(name, "srv_%d", ++nProcs);
802 (*registerProgram) (pid, name);
804 #endif /* AFS_NT40_ENV */
805 rx_ServerProc(NULL); /* Never returns */
807 #ifdef RX_ENABLE_TSFPQ
808 /* no use leaving packets around in this thread's local queue if
809 * it isn't getting donated to the server thread pool.
811 rxi_FlushLocalPacketsTSFPQ();
812 #endif /* RX_ENABLE_TSFPQ */
816 /* Create a new client connection to the specified service, using the
817 * specified security object to implement the security model for this
819 struct rx_connection *
820 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
821 struct rx_securityClass *securityObject,
822 int serviceSecurityIndex)
826 struct rx_connection *conn;
831 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
832 "serviceSecurityIndex %d)\n",
833 ntohl(shost), ntohs(sport), sservice, securityObject,
834 serviceSecurityIndex));
836 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
837 * the case of kmem_alloc? */
838 conn = rxi_AllocConnection();
839 #ifdef RX_ENABLE_LOCKS
840 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
841 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
842 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
845 MUTEX_ENTER(&rx_connHashTable_lock);
846 cid = (rx_nextCid += RX_MAXCALLS);
847 conn->type = RX_CLIENT_CONNECTION;
849 conn->epoch = rx_epoch;
850 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
851 conn->serviceId = sservice;
852 conn->securityObject = securityObject;
853 conn->securityData = (void *) 0;
854 conn->securityIndex = serviceSecurityIndex;
855 rx_SetConnDeadTime(conn, rx_connDeadTime);
856 rx_SetConnSecondsUntilNatPing(conn, 0);
857 conn->ackRate = RX_FAST_ACK_RATE;
859 conn->specific = NULL;
860 conn->challengeEvent = NULL;
861 conn->delayedAbortEvent = NULL;
862 conn->abortCount = 0;
864 for (i = 0; i < RX_MAXCALLS; i++) {
865 conn->twind[i] = rx_initSendWindow;
866 conn->rwind[i] = rx_initReceiveWindow;
869 RXS_NewConnection(securityObject, conn);
871 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
873 conn->refCount++; /* no lock required since only this thread knows... */
874 conn->next = rx_connHashTable[hashindex];
875 rx_connHashTable[hashindex] = conn;
877 rx_atomic_inc(&rx_stats.nClientConns);
878 MUTEX_EXIT(&rx_connHashTable_lock);
884 * Ensure a connection's timeout values are valid.
886 * @param[in] conn The connection to check
888 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
889 * unless idleDeadTime and/or hardDeadTime are not set
893 rxi_CheckConnTimeouts(struct rx_connection *conn)
895 /* a connection's timeouts must have the relationship
896 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
897 * total loss of network to a peer may cause an idle timeout instead of a
898 * dead timeout, simply because the idle timeout gets hit first. Also set
899 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
900 /* this logic is slightly complicated by the fact that
901 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
903 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
904 if (conn->idleDeadTime) {
905 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
907 if (conn->hardDeadTime) {
908 if (conn->idleDeadTime) {
909 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
911 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
917 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
919 /* The idea is to set the dead time to a value that allows several
920 * keepalives to be dropped without timing out the connection. */
921 conn->secondsUntilDead = seconds;
922 rxi_CheckConnTimeouts(conn);
923 conn->secondsUntilPing = conn->secondsUntilDead / 6;
927 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
929 conn->hardDeadTime = seconds;
930 rxi_CheckConnTimeouts(conn);
934 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
936 conn->idleDeadTime = seconds;
937 rxi_CheckConnTimeouts(conn);
940 int rxi_lowPeerRefCount = 0;
941 int rxi_lowConnRefCount = 0;
944 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
945 * NOTE: must not be called with rx_connHashTable_lock held.
948 rxi_CleanupConnection(struct rx_connection *conn)
950 /* Notify the service exporter, if requested, that this connection
951 * is being destroyed */
952 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
953 (*conn->service->destroyConnProc) (conn);
955 /* Notify the security module that this connection is being destroyed */
956 RXS_DestroyConnection(conn->securityObject, conn);
958 /* If this is the last connection using the rx_peer struct, set its
959 * idle time to now. rxi_ReapConnections will reap it if it's still
960 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
962 MUTEX_ENTER(&rx_peerHashTable_lock);
963 if (conn->peer->refCount < 2) {
964 conn->peer->idleWhen = clock_Sec();
965 if (conn->peer->refCount < 1) {
966 conn->peer->refCount = 1;
967 if (rx_stats_active) {
968 MUTEX_ENTER(&rx_stats_mutex);
969 rxi_lowPeerRefCount++;
970 MUTEX_EXIT(&rx_stats_mutex);
974 conn->peer->refCount--;
975 MUTEX_EXIT(&rx_peerHashTable_lock);
979 if (conn->type == RX_SERVER_CONNECTION)
980 rx_atomic_dec(&rx_stats.nServerConns);
982 rx_atomic_dec(&rx_stats.nClientConns);
985 if (conn->specific) {
987 for (i = 0; i < conn->nSpecific; i++) {
988 if (conn->specific[i] && rxi_keyCreate_destructor[i])
989 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
990 conn->specific[i] = NULL;
992 free(conn->specific);
994 conn->specific = NULL;
998 MUTEX_DESTROY(&conn->conn_call_lock);
999 MUTEX_DESTROY(&conn->conn_data_lock);
1000 CV_DESTROY(&conn->conn_call_cv);
1002 rxi_FreeConnection(conn);
1005 /* Destroy the specified connection */
1007 rxi_DestroyConnection(struct rx_connection *conn)
1009 MUTEX_ENTER(&rx_connHashTable_lock);
1010 rxi_DestroyConnectionNoLock(conn);
1011 /* conn should be at the head of the cleanup list */
1012 if (conn == rx_connCleanup_list) {
1013 rx_connCleanup_list = rx_connCleanup_list->next;
1014 MUTEX_EXIT(&rx_connHashTable_lock);
1015 rxi_CleanupConnection(conn);
1017 #ifdef RX_ENABLE_LOCKS
1019 MUTEX_EXIT(&rx_connHashTable_lock);
1021 #endif /* RX_ENABLE_LOCKS */
1025 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1027 struct rx_connection **conn_ptr;
1029 struct rx_packet *packet;
1036 MUTEX_ENTER(&conn->conn_data_lock);
1037 MUTEX_ENTER(&rx_refcnt_mutex);
1038 if (conn->refCount > 0)
1041 if (rx_stats_active) {
1042 MUTEX_ENTER(&rx_stats_mutex);
1043 rxi_lowConnRefCount++;
1044 MUTEX_EXIT(&rx_stats_mutex);
1048 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1049 /* Busy; wait till the last guy before proceeding */
1050 MUTEX_EXIT(&rx_refcnt_mutex);
1051 MUTEX_EXIT(&conn->conn_data_lock);
1056 /* If the client previously called rx_NewCall, but it is still
1057 * waiting, treat this as a running call, and wait to destroy the
1058 * connection later when the call completes. */
1059 if ((conn->type == RX_CLIENT_CONNECTION)
1060 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1061 conn->flags |= RX_CONN_DESTROY_ME;
1062 MUTEX_EXIT(&conn->conn_data_lock);
1066 MUTEX_EXIT(&rx_refcnt_mutex);
1067 MUTEX_EXIT(&conn->conn_data_lock);
1069 /* Check for extant references to this connection */
1070 for (i = 0; i < RX_MAXCALLS; i++) {
1071 struct rx_call *call = conn->call[i];
1074 if (conn->type == RX_CLIENT_CONNECTION) {
1075 MUTEX_ENTER(&call->lock);
1076 if (call->delayedAckEvent) {
1077 /* Push the final acknowledgment out now--there
1078 * won't be a subsequent call to acknowledge the
1079 * last reply packets */
1080 rxevent_Cancel(call->delayedAckEvent, call,
1081 RX_CALL_REFCOUNT_DELAY);
1082 if (call->state == RX_STATE_PRECALL
1083 || call->state == RX_STATE_ACTIVE) {
1084 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1086 rxi_AckAll(NULL, call, 0);
1089 MUTEX_EXIT(&call->lock);
1093 #ifdef RX_ENABLE_LOCKS
1095 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1096 MUTEX_EXIT(&conn->conn_data_lock);
1098 /* Someone is accessing a packet right now. */
1102 #endif /* RX_ENABLE_LOCKS */
1105 /* Don't destroy the connection if there are any call
1106 * structures still in use */
1107 MUTEX_ENTER(&conn->conn_data_lock);
1108 conn->flags |= RX_CONN_DESTROY_ME;
1109 MUTEX_EXIT(&conn->conn_data_lock);
1114 if (conn->natKeepAliveEvent) {
1115 rxi_NatKeepAliveOff(conn);
1118 if (conn->delayedAbortEvent) {
1119 rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1120 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1122 MUTEX_ENTER(&conn->conn_data_lock);
1123 rxi_SendConnectionAbort(conn, packet, 0, 1);
1124 MUTEX_EXIT(&conn->conn_data_lock);
1125 rxi_FreePacket(packet);
1129 /* Remove from connection hash table before proceeding */
1131 &rx_connHashTable[CONN_HASH
1132 (peer->host, peer->port, conn->cid, conn->epoch,
1134 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1135 if (*conn_ptr == conn) {
1136 *conn_ptr = conn->next;
1140 /* if the conn that we are destroying was the last connection, then we
1141 * clear rxLastConn as well */
1142 if (rxLastConn == conn)
1145 /* Make sure the connection is completely reset before deleting it. */
1146 /* get rid of pending events that could zap us later */
1147 if (conn->challengeEvent)
1148 rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1149 if (conn->checkReachEvent)
1150 rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1151 if (conn->natKeepAliveEvent)
1152 rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1154 /* Add the connection to the list of destroyed connections that
1155 * need to be cleaned up. This is necessary to avoid deadlocks
1156 * in the routines we call to inform others that this connection is
1157 * being destroyed. */
1158 conn->next = rx_connCleanup_list;
1159 rx_connCleanup_list = conn;
1162 /* Externally available version */
1164 rx_DestroyConnection(struct rx_connection *conn)
1169 rxi_DestroyConnection(conn);
1174 rx_GetConnection(struct rx_connection *conn)
1179 MUTEX_ENTER(&rx_refcnt_mutex);
1181 MUTEX_EXIT(&rx_refcnt_mutex);
1185 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1186 /* Wait for the transmit queue to no longer be busy.
1187 * requires the call->lock to be held */
1189 rxi_WaitforTQBusy(struct rx_call *call) {
1190 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1191 call->flags |= RX_CALL_TQ_WAIT;
1193 #ifdef RX_ENABLE_LOCKS
1194 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1195 CV_WAIT(&call->cv_tq, &call->lock);
1196 #else /* RX_ENABLE_LOCKS */
1197 osi_rxSleep(&call->tq);
1198 #endif /* RX_ENABLE_LOCKS */
1200 if (call->tqWaiters == 0) {
1201 call->flags &= ~RX_CALL_TQ_WAIT;
1207 /* Start a new rx remote procedure call, on the specified connection.
1208 * If wait is set to 1, wait for a free call channel; otherwise return
1209 * 0. Maxtime gives the maximum number of seconds this call may take,
1210 * after rx_NewCall returns. After this time interval, a call to any
1211 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1212 * For fine grain locking, we hold the conn_call_lock in order to
1213 * to ensure that we don't get signalle after we found a call in an active
1214 * state and before we go to sleep.
1217 rx_NewCall(struct rx_connection *conn)
1220 struct rx_call *call;
1221 struct clock queueTime;
1225 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1228 clock_GetTime(&queueTime);
1230 * Check if there are others waiting for a new call.
1231 * If so, let them go first to avoid starving them.
1232 * This is a fairly simple scheme, and might not be
1233 * a complete solution for large numbers of waiters.
1235 * makeCallWaiters keeps track of the number of
1236 * threads waiting to make calls and the
1237 * RX_CONN_MAKECALL_WAITING flag bit is used to
1238 * indicate that there are indeed calls waiting.
1239 * The flag is set when the waiter is incremented.
1240 * It is only cleared when makeCallWaiters is 0.
1241 * This prevents us from accidently destroying the
1242 * connection while it is potentially about to be used.
1244 MUTEX_ENTER(&conn->conn_call_lock);
1245 MUTEX_ENTER(&conn->conn_data_lock);
1246 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1247 conn->flags |= RX_CONN_MAKECALL_WAITING;
1248 conn->makeCallWaiters++;
1249 MUTEX_EXIT(&conn->conn_data_lock);
1251 #ifdef RX_ENABLE_LOCKS
1252 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1256 MUTEX_ENTER(&conn->conn_data_lock);
1257 conn->makeCallWaiters--;
1258 if (conn->makeCallWaiters == 0)
1259 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1262 /* We are now the active thread in rx_NewCall */
1263 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1264 MUTEX_EXIT(&conn->conn_data_lock);
1269 for (i = 0; i < RX_MAXCALLS; i++) {
1270 call = conn->call[i];
1272 if (call->state == RX_STATE_DALLY) {
1273 MUTEX_ENTER(&call->lock);
1274 if (call->state == RX_STATE_DALLY) {
1276 * We are setting the state to RX_STATE_RESET to
1277 * ensure that no one else will attempt to use this
1278 * call once we drop the conn->conn_call_lock and
1279 * call->lock. We must drop the conn->conn_call_lock
1280 * before calling rxi_ResetCall because the process
1281 * of clearing the transmit queue can block for an
1282 * extended period of time. If we block while holding
1283 * the conn->conn_call_lock, then all rx_EndCall
1284 * processing will block as well. This has a detrimental
1285 * effect on overall system performance.
1287 call->state = RX_STATE_RESET;
1288 MUTEX_EXIT(&conn->conn_call_lock);
1289 MUTEX_ENTER(&rx_refcnt_mutex);
1290 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1291 MUTEX_EXIT(&rx_refcnt_mutex);
1292 rxi_ResetCall(call, 0);
1293 (*call->callNumber)++;
1294 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1298 * If we failed to be able to safely obtain the
1299 * conn->conn_call_lock we will have to drop the
1300 * call->lock to avoid a deadlock. When the call->lock
1301 * is released the state of the call can change. If it
1302 * is no longer RX_STATE_RESET then some other thread is
1305 MUTEX_EXIT(&call->lock);
1306 MUTEX_ENTER(&conn->conn_call_lock);
1307 MUTEX_ENTER(&call->lock);
1309 if (call->state == RX_STATE_RESET)
1313 * If we get here it means that after dropping
1314 * the conn->conn_call_lock and call->lock that
1315 * the call is no longer ours. If we can't find
1316 * a free call in the remaining slots we should
1317 * not go immediately to RX_CONN_MAKECALL_WAITING
1318 * because by dropping the conn->conn_call_lock
1319 * we have given up synchronization with rx_EndCall.
1320 * Instead, cycle through one more time to see if
1321 * we can find a call that can call our own.
1323 MUTEX_ENTER(&rx_refcnt_mutex);
1324 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1325 MUTEX_EXIT(&rx_refcnt_mutex);
1328 MUTEX_EXIT(&call->lock);
1331 /* rxi_NewCall returns with mutex locked */
1332 call = rxi_NewCall(conn, i);
1333 MUTEX_ENTER(&rx_refcnt_mutex);
1334 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1335 MUTEX_EXIT(&rx_refcnt_mutex);
1339 if (i < RX_MAXCALLS) {
1345 MUTEX_ENTER(&conn->conn_data_lock);
1346 conn->flags |= RX_CONN_MAKECALL_WAITING;
1347 conn->makeCallWaiters++;
1348 MUTEX_EXIT(&conn->conn_data_lock);
1350 #ifdef RX_ENABLE_LOCKS
1351 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1355 MUTEX_ENTER(&conn->conn_data_lock);
1356 conn->makeCallWaiters--;
1357 if (conn->makeCallWaiters == 0)
1358 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1359 MUTEX_EXIT(&conn->conn_data_lock);
1361 /* Client is initially in send mode */
1362 call->state = RX_STATE_ACTIVE;
1363 call->error = conn->error;
1365 call->mode = RX_MODE_ERROR;
1367 call->mode = RX_MODE_SENDING;
1369 /* remember start time for call in case we have hard dead time limit */
1370 call->queueTime = queueTime;
1371 clock_GetTime(&call->startTime);
1372 hzero(call->bytesSent);
1373 hzero(call->bytesRcvd);
1375 /* Turn on busy protocol. */
1376 rxi_KeepAliveOn(call);
1378 /* Attempt MTU discovery */
1379 rxi_GrowMTUOn(call);
1382 * We are no longer the active thread in rx_NewCall
1384 MUTEX_ENTER(&conn->conn_data_lock);
1385 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1386 MUTEX_EXIT(&conn->conn_data_lock);
1389 * Wake up anyone else who might be giving us a chance to
1390 * run (see code above that avoids resource starvation).
1392 #ifdef RX_ENABLE_LOCKS
1393 CV_BROADCAST(&conn->conn_call_cv);
1397 MUTEX_EXIT(&conn->conn_call_lock);
1399 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1400 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1401 osi_Panic("rx_NewCall call about to be used without an empty tq");
1403 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1405 MUTEX_EXIT(&call->lock);
1408 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1413 rxi_HasActiveCalls(struct rx_connection *aconn)
1416 struct rx_call *tcall;
1420 for (i = 0; i < RX_MAXCALLS; i++) {
1421 if ((tcall = aconn->call[i])) {
1422 if ((tcall->state == RX_STATE_ACTIVE)
1423 || (tcall->state == RX_STATE_PRECALL)) {
1434 rxi_GetCallNumberVector(struct rx_connection *aconn,
1435 afs_int32 * aint32s)
1438 struct rx_call *tcall;
1442 for (i = 0; i < RX_MAXCALLS; i++) {
1443 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1444 aint32s[i] = aconn->callNumber[i] + 1;
1446 aint32s[i] = aconn->callNumber[i];
1453 rxi_SetCallNumberVector(struct rx_connection *aconn,
1454 afs_int32 * aint32s)
1457 struct rx_call *tcall;
1461 for (i = 0; i < RX_MAXCALLS; i++) {
1462 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1463 aconn->callNumber[i] = aint32s[i] - 1;
1465 aconn->callNumber[i] = aint32s[i];
1471 /* Advertise a new service. A service is named locally by a UDP port
1472 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1475 char *serviceName; Name for identification purposes (e.g. the
1476 service name might be used for probing for
1479 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1480 char *serviceName, struct rx_securityClass **securityObjects,
1481 int nSecurityObjects,
1482 afs_int32(*serviceProc) (struct rx_call * acall))
1484 osi_socket socket = OSI_NULLSOCKET;
1485 struct rx_service *tservice;
1491 if (serviceId == 0) {
1493 "rx_NewService: service id for service %s is not non-zero.\n",
1500 "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",
1508 tservice = rxi_AllocService();
1511 #ifdef RX_ENABLE_LOCKS
1512 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1515 for (i = 0; i < RX_MAX_SERVICES; i++) {
1516 struct rx_service *service = rx_services[i];
1518 if (port == service->servicePort && host == service->serviceHost) {
1519 if (service->serviceId == serviceId) {
1520 /* The identical service has already been
1521 * installed; if the caller was intending to
1522 * change the security classes used by this
1523 * service, he/she loses. */
1525 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1526 serviceName, serviceId, service->serviceName);
1528 rxi_FreeService(tservice);
1531 /* Different service, same port: re-use the socket
1532 * which is bound to the same port */
1533 socket = service->socket;
1536 if (socket == OSI_NULLSOCKET) {
1537 /* If we don't already have a socket (from another
1538 * service on same port) get a new one */
1539 socket = rxi_GetHostUDPSocket(host, port);
1540 if (socket == OSI_NULLSOCKET) {
1542 rxi_FreeService(tservice);
1547 service->socket = socket;
1548 service->serviceHost = host;
1549 service->servicePort = port;
1550 service->serviceId = serviceId;
1551 service->serviceName = serviceName;
1552 service->nSecurityObjects = nSecurityObjects;
1553 service->securityObjects = securityObjects;
1554 service->minProcs = 0;
1555 service->maxProcs = 1;
1556 service->idleDeadTime = 60;
1557 service->idleDeadErr = 0;
1558 service->connDeadTime = rx_connDeadTime;
1559 service->executeRequestProc = serviceProc;
1560 service->checkReach = 0;
1561 service->nSpecific = 0;
1562 service->specific = NULL;
1563 rx_services[i] = service; /* not visible until now */
1569 rxi_FreeService(tservice);
1570 (osi_Msg "rx_NewService: cannot support > %d services\n",
1575 /* Set configuration options for all of a service's security objects */
1578 rx_SetSecurityConfiguration(struct rx_service *service,
1579 rx_securityConfigVariables type,
1583 for (i = 0; i<service->nSecurityObjects; i++) {
1584 if (service->securityObjects[i]) {
1585 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1593 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1594 struct rx_securityClass **securityObjects, int nSecurityObjects,
1595 afs_int32(*serviceProc) (struct rx_call * acall))
1597 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1600 /* Generic request processing loop. This routine should be called
1601 * by the implementation dependent rx_ServerProc. If socketp is
1602 * non-null, it will be set to the file descriptor that this thread
1603 * is now listening on. If socketp is null, this routine will never
1606 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1608 struct rx_call *call;
1610 struct rx_service *tservice = NULL;
1617 call = rx_GetCall(threadID, tservice, socketp);
1618 if (socketp && *socketp != OSI_NULLSOCKET) {
1619 /* We are now a listener thread */
1624 /* if server is restarting( typically smooth shutdown) then do not
1625 * allow any new calls.
1628 if (rx_tranquil && (call != NULL)) {
1632 MUTEX_ENTER(&call->lock);
1634 rxi_CallError(call, RX_RESTARTING);
1635 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1637 MUTEX_EXIT(&call->lock);
1641 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1642 #ifdef RX_ENABLE_LOCKS
1644 #endif /* RX_ENABLE_LOCKS */
1645 afs_termState = AFSOP_STOP_AFS;
1646 afs_osi_Wakeup(&afs_termState);
1647 #ifdef RX_ENABLE_LOCKS
1649 #endif /* RX_ENABLE_LOCKS */
1654 tservice = call->conn->service;
1656 if (tservice->beforeProc)
1657 (*tservice->beforeProc) (call);
1659 code = tservice->executeRequestProc(call);
1661 if (tservice->afterProc)
1662 (*tservice->afterProc) (call, code);
1664 rx_EndCall(call, code);
1665 if (rx_stats_active) {
1666 MUTEX_ENTER(&rx_stats_mutex);
1668 MUTEX_EXIT(&rx_stats_mutex);
1675 rx_WakeupServerProcs(void)
1677 struct rx_serverQueueEntry *np, *tqp;
1681 MUTEX_ENTER(&rx_serverPool_lock);
1683 #ifdef RX_ENABLE_LOCKS
1684 if (rx_waitForPacket)
1685 CV_BROADCAST(&rx_waitForPacket->cv);
1686 #else /* RX_ENABLE_LOCKS */
1687 if (rx_waitForPacket)
1688 osi_rxWakeup(rx_waitForPacket);
1689 #endif /* RX_ENABLE_LOCKS */
1690 MUTEX_ENTER(&freeSQEList_lock);
1691 for (np = rx_FreeSQEList; np; np = tqp) {
1692 tqp = *(struct rx_serverQueueEntry **)np;
1693 #ifdef RX_ENABLE_LOCKS
1694 CV_BROADCAST(&np->cv);
1695 #else /* RX_ENABLE_LOCKS */
1697 #endif /* RX_ENABLE_LOCKS */
1699 MUTEX_EXIT(&freeSQEList_lock);
1700 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1701 #ifdef RX_ENABLE_LOCKS
1702 CV_BROADCAST(&np->cv);
1703 #else /* RX_ENABLE_LOCKS */
1705 #endif /* RX_ENABLE_LOCKS */
1707 MUTEX_EXIT(&rx_serverPool_lock);
1712 * One thing that seems to happen is that all the server threads get
1713 * tied up on some empty or slow call, and then a whole bunch of calls
1714 * arrive at once, using up the packet pool, so now there are more
1715 * empty calls. The most critical resources here are server threads
1716 * and the free packet pool. The "doreclaim" code seems to help in
1717 * general. I think that eventually we arrive in this state: there
1718 * are lots of pending calls which do have all their packets present,
1719 * so they won't be reclaimed, are multi-packet calls, so they won't
1720 * be scheduled until later, and thus are tying up most of the free
1721 * packet pool for a very long time.
1723 * 1. schedule multi-packet calls if all the packets are present.
1724 * Probably CPU-bound operation, useful to return packets to pool.
1725 * Do what if there is a full window, but the last packet isn't here?
1726 * 3. preserve one thread which *only* runs "best" calls, otherwise
1727 * it sleeps and waits for that type of call.
1728 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1729 * the current dataquota business is badly broken. The quota isn't adjusted
1730 * to reflect how many packets are presently queued for a running call.
1731 * So, when we schedule a queued call with a full window of packets queued
1732 * up for it, that *should* free up a window full of packets for other 2d-class
1733 * calls to be able to use from the packet pool. But it doesn't.
1735 * NB. Most of the time, this code doesn't run -- since idle server threads
1736 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1737 * as a new call arrives.
1739 /* Sleep until a call arrives. Returns a pointer to the call, ready
1740 * for an rx_Read. */
1741 #ifdef RX_ENABLE_LOCKS
1743 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1745 struct rx_serverQueueEntry *sq;
1746 struct rx_call *call = (struct rx_call *)0;
1747 struct rx_service *service = NULL;
1750 MUTEX_ENTER(&freeSQEList_lock);
1752 if ((sq = rx_FreeSQEList)) {
1753 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1754 MUTEX_EXIT(&freeSQEList_lock);
1755 } else { /* otherwise allocate a new one and return that */
1756 MUTEX_EXIT(&freeSQEList_lock);
1757 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1758 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1759 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1762 MUTEX_ENTER(&rx_serverPool_lock);
1763 if (cur_service != NULL) {
1764 ReturnToServerPool(cur_service);
1767 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1768 struct rx_call *tcall, *ncall, *choice2 = NULL;
1770 /* Scan for eligible incoming calls. A call is not eligible
1771 * if the maximum number of calls for its service type are
1772 * already executing */
1773 /* One thread will process calls FCFS (to prevent starvation),
1774 * while the other threads may run ahead looking for calls which
1775 * have all their input data available immediately. This helps
1776 * keep threads from blocking, waiting for data from the client. */
1777 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1778 service = tcall->conn->service;
1779 if (!QuotaOK(service)) {
1782 MUTEX_ENTER(&rx_pthread_mutex);
1783 if (tno == rxi_fcfs_thread_num
1784 || !tcall->queue_item_header.next) {
1785 MUTEX_EXIT(&rx_pthread_mutex);
1786 /* If we're the fcfs thread , then we'll just use
1787 * this call. If we haven't been able to find an optimal
1788 * choice, and we're at the end of the list, then use a
1789 * 2d choice if one has been identified. Otherwise... */
1790 call = (choice2 ? choice2 : tcall);
1791 service = call->conn->service;
1793 MUTEX_EXIT(&rx_pthread_mutex);
1794 if (!queue_IsEmpty(&tcall->rq)) {
1795 struct rx_packet *rp;
1796 rp = queue_First(&tcall->rq, rx_packet);
1797 if (rp->header.seq == 1) {
1799 || (rp->header.flags & RX_LAST_PACKET)) {
1801 } else if (rxi_2dchoice && !choice2
1802 && !(tcall->flags & RX_CALL_CLEARED)
1803 && (tcall->rprev > rxi_HardAckRate)) {
1813 ReturnToServerPool(service);
1820 MUTEX_EXIT(&rx_serverPool_lock);
1821 MUTEX_ENTER(&call->lock);
1823 if (call->flags & RX_CALL_WAIT_PROC) {
1824 call->flags &= ~RX_CALL_WAIT_PROC;
1825 rx_atomic_dec(&rx_nWaiting);
1828 if (call->state != RX_STATE_PRECALL || call->error) {
1829 MUTEX_EXIT(&call->lock);
1830 MUTEX_ENTER(&rx_serverPool_lock);
1831 ReturnToServerPool(service);
1836 if (queue_IsEmpty(&call->rq)
1837 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1838 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1840 CLEAR_CALL_QUEUE_LOCK(call);
1843 /* If there are no eligible incoming calls, add this process
1844 * to the idle server queue, to wait for one */
1848 *socketp = OSI_NULLSOCKET;
1850 sq->socketp = socketp;
1851 queue_Append(&rx_idleServerQueue, sq);
1852 #ifndef AFS_AIX41_ENV
1853 rx_waitForPacket = sq;
1855 rx_waitingForPacket = sq;
1856 #endif /* AFS_AIX41_ENV */
1858 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1860 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1861 MUTEX_EXIT(&rx_serverPool_lock);
1862 return (struct rx_call *)0;
1865 } while (!(call = sq->newcall)
1866 && !(socketp && *socketp != OSI_NULLSOCKET));
1867 MUTEX_EXIT(&rx_serverPool_lock);
1869 MUTEX_ENTER(&call->lock);
1875 MUTEX_ENTER(&freeSQEList_lock);
1876 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1877 rx_FreeSQEList = sq;
1878 MUTEX_EXIT(&freeSQEList_lock);
1881 clock_GetTime(&call->startTime);
1882 call->state = RX_STATE_ACTIVE;
1883 call->mode = RX_MODE_RECEIVING;
1884 #ifdef RX_KERNEL_TRACE
1885 if (ICL_SETACTIVE(afs_iclSetp)) {
1886 int glockOwner = ISAFS_GLOCK();
1889 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1890 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1897 rxi_calltrace(RX_CALL_START, call);
1898 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1899 call->conn->service->servicePort, call->conn->service->serviceId,
1902 MUTEX_EXIT(&call->lock);
1903 MUTEX_ENTER(&rx_refcnt_mutex);
1904 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1905 MUTEX_EXIT(&rx_refcnt_mutex);
1907 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1912 #else /* RX_ENABLE_LOCKS */
1914 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1916 struct rx_serverQueueEntry *sq;
1917 struct rx_call *call = (struct rx_call *)0, *choice2;
1918 struct rx_service *service = NULL;
1922 MUTEX_ENTER(&freeSQEList_lock);
1924 if ((sq = rx_FreeSQEList)) {
1925 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1926 MUTEX_EXIT(&freeSQEList_lock);
1927 } else { /* otherwise allocate a new one and return that */
1928 MUTEX_EXIT(&freeSQEList_lock);
1929 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1930 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1931 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1933 MUTEX_ENTER(&sq->lock);
1935 if (cur_service != NULL) {
1936 cur_service->nRequestsRunning--;
1937 MUTEX_ENTER(&rx_quota_mutex);
1938 if (cur_service->nRequestsRunning < cur_service->minProcs)
1941 MUTEX_EXIT(&rx_quota_mutex);
1943 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1944 struct rx_call *tcall, *ncall;
1945 /* Scan for eligible incoming calls. A call is not eligible
1946 * if the maximum number of calls for its service type are
1947 * already executing */
1948 /* One thread will process calls FCFS (to prevent starvation),
1949 * while the other threads may run ahead looking for calls which
1950 * have all their input data available immediately. This helps
1951 * keep threads from blocking, waiting for data from the client. */
1952 choice2 = (struct rx_call *)0;
1953 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1954 service = tcall->conn->service;
1955 if (QuotaOK(service)) {
1956 MUTEX_ENTER(&rx_pthread_mutex);
1957 if (tno == rxi_fcfs_thread_num
1958 || !tcall->queue_item_header.next) {
1959 MUTEX_EXIT(&rx_pthread_mutex);
1960 /* If we're the fcfs thread, then we'll just use
1961 * this call. If we haven't been able to find an optimal
1962 * choice, and we're at the end of the list, then use a
1963 * 2d choice if one has been identified. Otherwise... */
1964 call = (choice2 ? choice2 : tcall);
1965 service = call->conn->service;
1967 MUTEX_EXIT(&rx_pthread_mutex);
1968 if (!queue_IsEmpty(&tcall->rq)) {
1969 struct rx_packet *rp;
1970 rp = queue_First(&tcall->rq, rx_packet);
1971 if (rp->header.seq == 1
1973 || (rp->header.flags & RX_LAST_PACKET))) {
1975 } else if (rxi_2dchoice && !choice2
1976 && !(tcall->flags & RX_CALL_CLEARED)
1977 && (tcall->rprev > rxi_HardAckRate)) {
1991 /* we can't schedule a call if there's no data!!! */
1992 /* send an ack if there's no data, if we're missing the
1993 * first packet, or we're missing something between first
1994 * and last -- there's a "hole" in the incoming data. */
1995 if (queue_IsEmpty(&call->rq)
1996 || queue_First(&call->rq, rx_packet)->header.seq != 1
1997 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
1998 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2000 call->flags &= (~RX_CALL_WAIT_PROC);
2001 service->nRequestsRunning++;
2002 /* just started call in minProcs pool, need fewer to maintain
2004 MUTEX_ENTER(&rx_quota_mutex);
2005 if (service->nRequestsRunning <= service->minProcs)
2008 MUTEX_EXIT(&rx_quota_mutex);
2009 rx_atomic_dec(&rx_nWaiting);
2010 /* MUTEX_EXIT(&call->lock); */
2012 /* If there are no eligible incoming calls, add this process
2013 * to the idle server queue, to wait for one */
2016 *socketp = OSI_NULLSOCKET;
2018 sq->socketp = socketp;
2019 queue_Append(&rx_idleServerQueue, sq);
2023 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2025 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2026 return (struct rx_call *)0;
2029 } while (!(call = sq->newcall)
2030 && !(socketp && *socketp != OSI_NULLSOCKET));
2032 MUTEX_EXIT(&sq->lock);
2034 MUTEX_ENTER(&freeSQEList_lock);
2035 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2036 rx_FreeSQEList = sq;
2037 MUTEX_EXIT(&freeSQEList_lock);
2040 clock_GetTime(&call->startTime);
2041 call->state = RX_STATE_ACTIVE;
2042 call->mode = RX_MODE_RECEIVING;
2043 #ifdef RX_KERNEL_TRACE
2044 if (ICL_SETACTIVE(afs_iclSetp)) {
2045 int glockOwner = ISAFS_GLOCK();
2048 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2049 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2056 rxi_calltrace(RX_CALL_START, call);
2057 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2058 call->conn->service->servicePort, call->conn->service->serviceId,
2061 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2068 #endif /* RX_ENABLE_LOCKS */
2072 /* Establish a procedure to be called when a packet arrives for a
2073 * call. This routine will be called at most once after each call,
2074 * and will also be called if there is an error condition on the or
2075 * the call is complete. Used by multi rx to build a selection
2076 * function which determines which of several calls is likely to be a
2077 * good one to read from.
2078 * NOTE: the way this is currently implemented it is probably only a
2079 * good idea to (1) use it immediately after a newcall (clients only)
2080 * and (2) only use it once. Other uses currently void your warranty
2083 rx_SetArrivalProc(struct rx_call *call,
2084 void (*proc) (struct rx_call * call,
2087 void * handle, int arg)
2089 call->arrivalProc = proc;
2090 call->arrivalProcHandle = handle;
2091 call->arrivalProcArg = arg;
2094 /* Call is finished (possibly prematurely). Return rc to the peer, if
2095 * appropriate, and return the final error code from the conversation
2099 rx_EndCall(struct rx_call *call, afs_int32 rc)
2101 struct rx_connection *conn = call->conn;
2105 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2106 call, rc, call->error, call->abortCode));
2109 MUTEX_ENTER(&call->lock);
2111 if (rc == 0 && call->error == 0) {
2112 call->abortCode = 0;
2113 call->abortCount = 0;
2116 call->arrivalProc = (void (*)())0;
2117 if (rc && call->error == 0) {
2118 rxi_CallError(call, rc);
2119 call->mode = RX_MODE_ERROR;
2120 /* Send an abort message to the peer if this error code has
2121 * only just been set. If it was set previously, assume the
2122 * peer has already been sent the error code or will request it
2124 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2126 if (conn->type == RX_SERVER_CONNECTION) {
2127 /* Make sure reply or at least dummy reply is sent */
2128 if (call->mode == RX_MODE_RECEIVING) {
2129 MUTEX_EXIT(&call->lock);
2130 rxi_WriteProc(call, 0, 0);
2131 MUTEX_ENTER(&call->lock);
2133 if (call->mode == RX_MODE_SENDING) {
2134 MUTEX_EXIT(&call->lock);
2135 rxi_FlushWrite(call);
2136 MUTEX_ENTER(&call->lock);
2138 rxi_calltrace(RX_CALL_END, call);
2139 /* Call goes to hold state until reply packets are acknowledged */
2140 if (call->tfirst + call->nSoftAcked < call->tnext) {
2141 call->state = RX_STATE_HOLD;
2143 call->state = RX_STATE_DALLY;
2144 rxi_ClearTransmitQueue(call, 0);
2145 rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2146 rxevent_Cancel(call->keepAliveEvent, call,
2147 RX_CALL_REFCOUNT_ALIVE);
2149 } else { /* Client connection */
2151 /* Make sure server receives input packets, in the case where
2152 * no reply arguments are expected */
2153 if ((call->mode == RX_MODE_SENDING)
2154 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2155 MUTEX_EXIT(&call->lock);
2156 (void)rxi_ReadProc(call, &dummy, 1);
2157 MUTEX_ENTER(&call->lock);
2160 /* If we had an outstanding delayed ack, be nice to the server
2161 * and force-send it now.
2163 if (call->delayedAckEvent) {
2164 rxevent_Cancel(call->delayedAckEvent, call,
2165 RX_CALL_REFCOUNT_DELAY);
2166 call->delayedAckEvent = NULL;
2167 rxi_SendDelayedAck(NULL, call, NULL);
2170 /* We need to release the call lock since it's lower than the
2171 * conn_call_lock and we don't want to hold the conn_call_lock
2172 * over the rx_ReadProc call. The conn_call_lock needs to be held
2173 * here for the case where rx_NewCall is perusing the calls on
2174 * the connection structure. We don't want to signal until
2175 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2176 * have checked this call, found it active and by the time it
2177 * goes to sleep, will have missed the signal.
2179 MUTEX_EXIT(&call->lock);
2180 MUTEX_ENTER(&conn->conn_call_lock);
2181 MUTEX_ENTER(&call->lock);
2182 MUTEX_ENTER(&conn->conn_data_lock);
2183 conn->flags |= RX_CONN_BUSY;
2184 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2185 MUTEX_EXIT(&conn->conn_data_lock);
2186 #ifdef RX_ENABLE_LOCKS
2187 CV_BROADCAST(&conn->conn_call_cv);
2192 #ifdef RX_ENABLE_LOCKS
2194 MUTEX_EXIT(&conn->conn_data_lock);
2196 #endif /* RX_ENABLE_LOCKS */
2197 call->state = RX_STATE_DALLY;
2199 error = call->error;
2201 /* currentPacket, nLeft, and NFree must be zeroed here, because
2202 * ResetCall cannot: ResetCall may be called at splnet(), in the
2203 * kernel version, and may interrupt the macros rx_Read or
2204 * rx_Write, which run at normal priority for efficiency. */
2205 if (call->currentPacket) {
2206 #ifdef RX_TRACK_PACKETS
2207 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2209 rxi_FreePacket(call->currentPacket);
2210 call->currentPacket = (struct rx_packet *)0;
2213 call->nLeft = call->nFree = call->curlen = 0;
2215 /* Free any packets from the last call to ReadvProc/WritevProc */
2216 #ifdef RXDEBUG_PACKET
2218 #endif /* RXDEBUG_PACKET */
2219 rxi_FreePackets(0, &call->iovq);
2220 MUTEX_EXIT(&call->lock);
2222 MUTEX_ENTER(&rx_refcnt_mutex);
2223 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2224 MUTEX_EXIT(&rx_refcnt_mutex);
2225 if (conn->type == RX_CLIENT_CONNECTION) {
2226 MUTEX_ENTER(&conn->conn_data_lock);
2227 conn->flags &= ~RX_CONN_BUSY;
2228 MUTEX_EXIT(&conn->conn_data_lock);
2229 MUTEX_EXIT(&conn->conn_call_lock);
2233 * Map errors to the local host's errno.h format.
2235 error = ntoh_syserr_conv(error);
2239 #if !defined(KERNEL)
2241 /* Call this routine when shutting down a server or client (especially
2242 * clients). This will allow Rx to gracefully garbage collect server
2243 * connections, and reduce the number of retries that a server might
2244 * make to a dead client.
2245 * This is not quite right, since some calls may still be ongoing and
2246 * we can't lock them to destroy them. */
2250 struct rx_connection **conn_ptr, **conn_end;
2254 if (rxinit_status == 1) {
2256 return; /* Already shutdown. */
2258 rxi_DeleteCachedConnections();
2259 if (rx_connHashTable) {
2260 MUTEX_ENTER(&rx_connHashTable_lock);
2261 for (conn_ptr = &rx_connHashTable[0], conn_end =
2262 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2264 struct rx_connection *conn, *next;
2265 for (conn = *conn_ptr; conn; conn = next) {
2267 if (conn->type == RX_CLIENT_CONNECTION) {
2268 MUTEX_ENTER(&rx_refcnt_mutex);
2270 MUTEX_EXIT(&rx_refcnt_mutex);
2271 #ifdef RX_ENABLE_LOCKS
2272 rxi_DestroyConnectionNoLock(conn);
2273 #else /* RX_ENABLE_LOCKS */
2274 rxi_DestroyConnection(conn);
2275 #endif /* RX_ENABLE_LOCKS */
2279 #ifdef RX_ENABLE_LOCKS
2280 while (rx_connCleanup_list) {
2281 struct rx_connection *conn;
2282 conn = rx_connCleanup_list;
2283 rx_connCleanup_list = rx_connCleanup_list->next;
2284 MUTEX_EXIT(&rx_connHashTable_lock);
2285 rxi_CleanupConnection(conn);
2286 MUTEX_ENTER(&rx_connHashTable_lock);
2288 MUTEX_EXIT(&rx_connHashTable_lock);
2289 #endif /* RX_ENABLE_LOCKS */
2294 afs_winsockCleanup();
2302 /* if we wakeup packet waiter too often, can get in loop with two
2303 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2305 rxi_PacketsUnWait(void)
2307 if (!rx_waitingForPackets) {
2311 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2312 return; /* still over quota */
2315 rx_waitingForPackets = 0;
2316 #ifdef RX_ENABLE_LOCKS
2317 CV_BROADCAST(&rx_waitingForPackets_cv);
2319 osi_rxWakeup(&rx_waitingForPackets);
2325 /* ------------------Internal interfaces------------------------- */
2327 /* Return this process's service structure for the
2328 * specified socket and service */
2330 rxi_FindService(osi_socket socket, u_short serviceId)
2332 struct rx_service **sp;
2333 for (sp = &rx_services[0]; *sp; sp++) {
2334 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2340 #ifdef RXDEBUG_PACKET
2341 #ifdef KDUMP_RX_LOCK
2342 static struct rx_call_rx_lock *rx_allCallsp = 0;
2344 static struct rx_call *rx_allCallsp = 0;
2346 #endif /* RXDEBUG_PACKET */
2348 /* Allocate a call structure, for the indicated channel of the
2349 * supplied connection. The mode and state of the call must be set by
2350 * the caller. Returns the call with mutex locked. */
2352 rxi_NewCall(struct rx_connection *conn, int channel)
2354 struct rx_call *call;
2355 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2356 struct rx_call *cp; /* Call pointer temp */
2357 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2358 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2360 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2362 /* Grab an existing call structure, or allocate a new one.
2363 * Existing call structures are assumed to have been left reset by
2365 MUTEX_ENTER(&rx_freeCallQueue_lock);
2367 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2369 * EXCEPT that the TQ might not yet be cleared out.
2370 * Skip over those with in-use TQs.
2373 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2374 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2380 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2381 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2382 call = queue_First(&rx_freeCallQueue, rx_call);
2383 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2385 if (rx_stats_active)
2386 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2387 MUTEX_EXIT(&rx_freeCallQueue_lock);
2388 MUTEX_ENTER(&call->lock);
2389 CLEAR_CALL_QUEUE_LOCK(call);
2390 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2391 /* Now, if TQ wasn't cleared earlier, do it now. */
2392 rxi_WaitforTQBusy(call);
2393 if (call->flags & RX_CALL_TQ_CLEARME) {
2394 rxi_ClearTransmitQueue(call, 1);
2395 /*queue_Init(&call->tq);*/
2397 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2398 /* Bind the call to its connection structure */
2400 rxi_ResetCall(call, 1);
2403 call = rxi_Alloc(sizeof(struct rx_call));
2404 #ifdef RXDEBUG_PACKET
2405 call->allNextp = rx_allCallsp;
2406 rx_allCallsp = call;
2408 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2409 #else /* RXDEBUG_PACKET */
2410 rx_atomic_inc(&rx_stats.nCallStructs);
2411 #endif /* RXDEBUG_PACKET */
2413 MUTEX_EXIT(&rx_freeCallQueue_lock);
2414 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2415 MUTEX_ENTER(&call->lock);
2416 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2417 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2418 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2420 /* Initialize once-only items */
2421 queue_Init(&call->tq);
2422 queue_Init(&call->rq);
2423 queue_Init(&call->iovq);
2424 #ifdef RXDEBUG_PACKET
2425 call->rqc = call->tqc = call->iovqc = 0;
2426 #endif /* RXDEBUG_PACKET */
2427 /* Bind the call to its connection structure (prereq for reset) */
2429 rxi_ResetCall(call, 1);
2431 call->channel = channel;
2432 call->callNumber = &conn->callNumber[channel];
2433 call->rwind = conn->rwind[channel];
2434 call->twind = conn->twind[channel];
2435 /* Note that the next expected call number is retained (in
2436 * conn->callNumber[i]), even if we reallocate the call structure
2438 conn->call[channel] = call;
2439 /* if the channel's never been used (== 0), we should start at 1, otherwise
2440 * the call number is valid from the last time this channel was used */
2441 if (*call->callNumber == 0)
2442 *call->callNumber = 1;
2447 /* A call has been inactive long enough that so we can throw away
2448 * state, including the call structure, which is placed on the call
2451 * call->lock amd rx_refcnt_mutex are held upon entry.
2452 * haveCTLock is set when called from rxi_ReapConnections.
2455 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2457 int channel = call->channel;
2458 struct rx_connection *conn = call->conn;
2461 if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2462 (*call->callNumber)++;
2463 rxi_ResetCall(call, 0);
2464 call->conn->call[channel] = (struct rx_call *)0;
2465 MUTEX_EXIT(&rx_refcnt_mutex);
2467 MUTEX_ENTER(&rx_freeCallQueue_lock);
2468 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2469 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2470 /* A call may be free even though its transmit queue is still in use.
2471 * Since we search the call list from head to tail, put busy calls at
2472 * the head of the list, and idle calls at the tail.
2474 if (call->flags & RX_CALL_TQ_BUSY)
2475 queue_Prepend(&rx_freeCallQueue, call);
2477 queue_Append(&rx_freeCallQueue, call);
2478 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2479 queue_Append(&rx_freeCallQueue, call);
2480 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2481 if (rx_stats_active)
2482 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2483 MUTEX_EXIT(&rx_freeCallQueue_lock);
2485 /* Destroy the connection if it was previously slated for
2486 * destruction, i.e. the Rx client code previously called
2487 * rx_DestroyConnection (client connections), or
2488 * rxi_ReapConnections called the same routine (server
2489 * connections). Only do this, however, if there are no
2490 * outstanding calls. Note that for fine grain locking, there appears
2491 * to be a deadlock in that rxi_FreeCall has a call locked and
2492 * DestroyConnectionNoLock locks each call in the conn. But note a
2493 * few lines up where we have removed this call from the conn.
2494 * If someone else destroys a connection, they either have no
2495 * call lock held or are going through this section of code.
2497 MUTEX_ENTER(&conn->conn_data_lock);
2498 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2499 MUTEX_ENTER(&rx_refcnt_mutex);
2501 MUTEX_EXIT(&rx_refcnt_mutex);
2502 MUTEX_EXIT(&conn->conn_data_lock);
2503 #ifdef RX_ENABLE_LOCKS
2505 rxi_DestroyConnectionNoLock(conn);
2507 rxi_DestroyConnection(conn);
2508 #else /* RX_ENABLE_LOCKS */
2509 rxi_DestroyConnection(conn);
2510 #endif /* RX_ENABLE_LOCKS */
2512 MUTEX_EXIT(&conn->conn_data_lock);
2514 MUTEX_ENTER(&rx_refcnt_mutex);
2517 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2518 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2521 rxi_Alloc(size_t size)
2525 if (rx_stats_active) {
2526 rx_atomic_add(&rxi_Allocsize, (int) size);
2527 rx_atomic_inc(&rxi_Alloccnt);
2531 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2532 afs_osi_Alloc_NoSleep(size);
2537 osi_Panic("rxi_Alloc error");
2543 rxi_Free(void *addr, size_t size)
2545 if (rx_stats_active) {
2546 rx_atomic_sub(&rxi_Allocsize, (int) size);
2547 rx_atomic_dec(&rxi_Alloccnt);
2549 osi_Free(addr, size);
2553 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2555 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2556 struct rx_peer *next = NULL;
2560 MUTEX_ENTER(&rx_peerHashTable_lock);
2562 peer_ptr = &rx_peerHashTable[0];
2563 peer_end = &rx_peerHashTable[rx_hashTableSize];
2566 for ( ; peer_ptr < peer_end; peer_ptr++) {
2569 for ( ; peer; peer = next) {
2571 if (host == peer->host)
2576 hashIndex = PEER_HASH(host, port);
2577 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2578 if ((peer->host == host) && (peer->port == port))
2583 MUTEX_ENTER(&rx_peerHashTable_lock);
2588 MUTEX_EXIT(&rx_peerHashTable_lock);
2590 MUTEX_ENTER(&peer->peer_lock);
2591 /* We don't handle dropping below min, so don't */
2592 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2593 peer->ifMTU=MIN(mtu, peer->ifMTU);
2594 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2595 /* if we tweaked this down, need to tune our peer MTU too */
2596 peer->MTU = MIN(peer->MTU, peer->natMTU);
2597 /* if we discovered a sub-1500 mtu, degrade */
2598 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2599 peer->maxDgramPackets = 1;
2600 /* We no longer have valid peer packet information */
2601 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2602 peer->maxPacketSize = 0;
2603 MUTEX_EXIT(&peer->peer_lock);
2605 MUTEX_ENTER(&rx_peerHashTable_lock);
2607 if (host && !port) {
2609 /* pick up where we left off */
2613 MUTEX_EXIT(&rx_peerHashTable_lock);
2616 /* Find the peer process represented by the supplied (host,port)
2617 * combination. If there is no appropriate active peer structure, a
2618 * new one will be allocated and initialized
2619 * The origPeer, if set, is a pointer to a peer structure on which the
2620 * refcount will be be decremented. This is used to replace the peer
2621 * structure hanging off a connection structure */
2623 rxi_FindPeer(afs_uint32 host, u_short port,
2624 struct rx_peer *origPeer, int create)
2628 hashIndex = PEER_HASH(host, port);
2629 MUTEX_ENTER(&rx_peerHashTable_lock);
2630 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2631 if ((pp->host == host) && (pp->port == port))
2636 pp = rxi_AllocPeer(); /* This bzero's *pp */
2637 pp->host = host; /* set here or in InitPeerParams is zero */
2639 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2640 queue_Init(&pp->congestionQueue);
2641 queue_Init(&pp->rpcStats);
2642 pp->next = rx_peerHashTable[hashIndex];
2643 rx_peerHashTable[hashIndex] = pp;
2644 rxi_InitPeerParams(pp);
2645 if (rx_stats_active)
2646 rx_atomic_inc(&rx_stats.nPeerStructs);
2653 origPeer->refCount--;
2654 MUTEX_EXIT(&rx_peerHashTable_lock);
2659 /* Find the connection at (host, port) started at epoch, and with the
2660 * given connection id. Creates the server connection if necessary.
2661 * The type specifies whether a client connection or a server
2662 * connection is desired. In both cases, (host, port) specify the
2663 * peer's (host, pair) pair. Client connections are not made
2664 * automatically by this routine. The parameter socket gives the
2665 * socket descriptor on which the packet was received. This is used,
2666 * in the case of server connections, to check that *new* connections
2667 * come via a valid (port, serviceId). Finally, the securityIndex
2668 * parameter must match the existing index for the connection. If a
2669 * server connection is created, it will be created using the supplied
2670 * index, if the index is valid for this service */
2671 struct rx_connection *
2672 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2673 u_short port, u_short serviceId, afs_uint32 cid,
2674 afs_uint32 epoch, int type, u_int securityIndex)
2676 int hashindex, flag, i;
2677 struct rx_connection *conn;
2678 hashindex = CONN_HASH(host, port, cid, epoch, type);
2679 MUTEX_ENTER(&rx_connHashTable_lock);
2680 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2681 rx_connHashTable[hashindex],
2684 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2685 && (epoch == conn->epoch)) {
2686 struct rx_peer *pp = conn->peer;
2687 if (securityIndex != conn->securityIndex) {
2688 /* this isn't supposed to happen, but someone could forge a packet
2689 * like this, and there seems to be some CM bug that makes this
2690 * happen from time to time -- in which case, the fileserver
2692 MUTEX_EXIT(&rx_connHashTable_lock);
2693 return (struct rx_connection *)0;
2695 if (pp->host == host && pp->port == port)
2697 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2699 /* So what happens when it's a callback connection? */
2700 if ( /*type == RX_CLIENT_CONNECTION && */
2701 (conn->epoch & 0x80000000))
2705 /* the connection rxLastConn that was used the last time is not the
2706 ** one we are looking for now. Hence, start searching in the hash */
2708 conn = rx_connHashTable[hashindex];
2713 struct rx_service *service;
2714 if (type == RX_CLIENT_CONNECTION) {
2715 MUTEX_EXIT(&rx_connHashTable_lock);
2716 return (struct rx_connection *)0;
2718 service = rxi_FindService(socket, serviceId);
2719 if (!service || (securityIndex >= service->nSecurityObjects)
2720 || (service->securityObjects[securityIndex] == 0)) {
2721 MUTEX_EXIT(&rx_connHashTable_lock);
2722 return (struct rx_connection *)0;
2724 conn = rxi_AllocConnection(); /* This bzero's the connection */
2725 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2726 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2727 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2728 conn->next = rx_connHashTable[hashindex];
2729 rx_connHashTable[hashindex] = conn;
2730 conn->peer = rxi_FindPeer(host, port, 0, 1);
2731 conn->type = RX_SERVER_CONNECTION;
2732 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
2733 conn->epoch = epoch;
2734 conn->cid = cid & RX_CIDMASK;
2735 /* conn->serial = conn->lastSerial = 0; */
2736 /* conn->timeout = 0; */
2737 conn->ackRate = RX_FAST_ACK_RATE;
2738 conn->service = service;
2739 conn->serviceId = serviceId;
2740 conn->securityIndex = securityIndex;
2741 conn->securityObject = service->securityObjects[securityIndex];
2742 conn->nSpecific = 0;
2743 conn->specific = NULL;
2744 rx_SetConnDeadTime(conn, service->connDeadTime);
2745 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2746 rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2747 for (i = 0; i < RX_MAXCALLS; i++) {
2748 conn->twind[i] = rx_initSendWindow;
2749 conn->rwind[i] = rx_initReceiveWindow;
2751 /* Notify security object of the new connection */
2752 RXS_NewConnection(conn->securityObject, conn);
2753 /* XXXX Connection timeout? */
2754 if (service->newConnProc)
2755 (*service->newConnProc) (conn);
2756 if (rx_stats_active)
2757 rx_atomic_inc(&rx_stats.nServerConns);
2760 MUTEX_ENTER(&rx_refcnt_mutex);
2762 MUTEX_EXIT(&rx_refcnt_mutex);
2764 rxLastConn = conn; /* store this connection as the last conn used */
2765 MUTEX_EXIT(&rx_connHashTable_lock);
2769 /* There are two packet tracing routines available for testing and monitoring
2770 * Rx. One is called just after every packet is received and the other is
2771 * called just before every packet is sent. Received packets, have had their
2772 * headers decoded, and packets to be sent have not yet had their headers
2773 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
2774 * containing the network address. Both can be modified. The return value, if
2775 * non-zero, indicates that the packet should be dropped. */
2777 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2778 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2780 /* A packet has been received off the interface. Np is the packet, socket is
2781 * the socket number it was received from (useful in determining which service
2782 * this packet corresponds to), and (host, port) reflect the host,port of the
2783 * sender. This call returns the packet to the caller if it is finished with
2784 * it, rather than de-allocating it, just as a small performance hack */
2787 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2788 afs_uint32 host, u_short port, int *tnop,
2789 struct rx_call **newcallp)
2791 struct rx_call *call;
2792 struct rx_connection *conn;
2794 afs_uint32 currentCallNumber;
2800 struct rx_packet *tnp;
2803 /* We don't print out the packet until now because (1) the time may not be
2804 * accurate enough until now in the lwp implementation (rx_Listener only gets
2805 * the time after the packet is read) and (2) from a protocol point of view,
2806 * this is the first time the packet has been seen */
2807 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2808 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2809 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2810 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2811 np->header.epoch, np->header.cid, np->header.callNumber,
2812 np->header.seq, np->header.flags, np));
2815 if (np->header.type == RX_PACKET_TYPE_VERSION) {
2816 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2819 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2820 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2823 /* If an input tracer function is defined, call it with the packet and
2824 * network address. Note this function may modify its arguments. */
2825 if (rx_justReceived) {
2826 struct sockaddr_in addr;
2828 addr.sin_family = AF_INET;
2829 addr.sin_port = port;
2830 addr.sin_addr.s_addr = host;
2831 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2832 addr.sin_len = sizeof(addr);
2833 #endif /* AFS_OSF_ENV */
2834 drop = (*rx_justReceived) (np, &addr);
2835 /* drop packet if return value is non-zero */
2838 port = addr.sin_port; /* in case fcn changed addr */
2839 host = addr.sin_addr.s_addr;
2843 /* If packet was not sent by the client, then *we* must be the client */
2844 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2845 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2847 /* Find the connection (or fabricate one, if we're the server & if
2848 * necessary) associated with this packet */
2850 rxi_FindConnection(socket, host, port, np->header.serviceId,
2851 np->header.cid, np->header.epoch, type,
2852 np->header.securityIndex);
2855 /* If no connection found or fabricated, just ignore the packet.
2856 * (An argument could be made for sending an abort packet for
2861 MUTEX_ENTER(&conn->conn_data_lock);
2862 if (conn->maxSerial < np->header.serial)
2863 conn->maxSerial = np->header.serial;
2864 MUTEX_EXIT(&conn->conn_data_lock);
2866 /* If the connection is in an error state, send an abort packet and ignore
2867 * the incoming packet */
2869 /* Don't respond to an abort packet--we don't want loops! */
2870 MUTEX_ENTER(&conn->conn_data_lock);
2871 if (np->header.type != RX_PACKET_TYPE_ABORT)
2872 np = rxi_SendConnectionAbort(conn, np, 1, 0);
2873 MUTEX_ENTER(&rx_refcnt_mutex);
2875 MUTEX_EXIT(&rx_refcnt_mutex);
2876 MUTEX_EXIT(&conn->conn_data_lock);
2880 /* Check for connection-only requests (i.e. not call specific). */
2881 if (np->header.callNumber == 0) {
2882 switch (np->header.type) {
2883 case RX_PACKET_TYPE_ABORT: {
2884 /* What if the supplied error is zero? */
2885 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
2886 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
2887 rxi_ConnectionError(conn, errcode);
2888 MUTEX_ENTER(&rx_refcnt_mutex);
2890 MUTEX_EXIT(&rx_refcnt_mutex);
2893 case RX_PACKET_TYPE_CHALLENGE:
2894 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
2895 MUTEX_ENTER(&rx_refcnt_mutex);
2897 MUTEX_EXIT(&rx_refcnt_mutex);
2899 case RX_PACKET_TYPE_RESPONSE:
2900 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
2901 MUTEX_ENTER(&rx_refcnt_mutex);
2903 MUTEX_EXIT(&rx_refcnt_mutex);
2905 case RX_PACKET_TYPE_PARAMS:
2906 case RX_PACKET_TYPE_PARAMS + 1:
2907 case RX_PACKET_TYPE_PARAMS + 2:
2908 /* ignore these packet types for now */
2909 MUTEX_ENTER(&rx_refcnt_mutex);
2911 MUTEX_EXIT(&rx_refcnt_mutex);
2916 /* Should not reach here, unless the peer is broken: send an
2918 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
2919 MUTEX_ENTER(&conn->conn_data_lock);
2920 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
2921 MUTEX_ENTER(&rx_refcnt_mutex);
2923 MUTEX_EXIT(&rx_refcnt_mutex);
2924 MUTEX_EXIT(&conn->conn_data_lock);
2929 channel = np->header.cid & RX_CHANNELMASK;
2930 call = conn->call[channel];
2931 #ifdef RX_ENABLE_LOCKS
2933 MUTEX_ENTER(&call->lock);
2934 /* Test to see if call struct is still attached to conn. */
2935 if (call != conn->call[channel]) {
2937 MUTEX_EXIT(&call->lock);
2938 if (type == RX_SERVER_CONNECTION) {
2939 call = conn->call[channel];
2940 /* If we started with no call attached and there is one now,
2941 * another thread is also running this routine and has gotten
2942 * the connection channel. We should drop this packet in the tests
2943 * below. If there was a call on this connection and it's now
2944 * gone, then we'll be making a new call below.
2945 * If there was previously a call and it's now different then
2946 * the old call was freed and another thread running this routine
2947 * has created a call on this channel. One of these two threads
2948 * has a packet for the old call and the code below handles those
2952 MUTEX_ENTER(&call->lock);
2954 /* This packet can't be for this call. If the new call address is
2955 * 0 then no call is running on this channel. If there is a call
2956 * then, since this is a client connection we're getting data for
2957 * it must be for the previous call.
2959 if (rx_stats_active)
2960 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2961 MUTEX_ENTER(&rx_refcnt_mutex);
2963 MUTEX_EXIT(&rx_refcnt_mutex);
2968 currentCallNumber = conn->callNumber[channel];
2970 if (type == RX_SERVER_CONNECTION) { /* We're the server */
2971 if (np->header.callNumber < currentCallNumber) {
2972 if (rx_stats_active)
2973 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
2974 #ifdef RX_ENABLE_LOCKS
2976 MUTEX_EXIT(&call->lock);
2978 MUTEX_ENTER(&rx_refcnt_mutex);
2980 MUTEX_EXIT(&rx_refcnt_mutex);
2984 MUTEX_ENTER(&conn->conn_call_lock);
2985 call = rxi_NewCall(conn, channel);
2986 MUTEX_EXIT(&conn->conn_call_lock);
2987 *call->callNumber = np->header.callNumber;
2989 if (np->header.callNumber == 0)
2990 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",
2991 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
2992 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
2993 np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
2995 call->state = RX_STATE_PRECALL;
2996 clock_GetTime(&call->queueTime);
2997 hzero(call->bytesSent);
2998 hzero(call->bytesRcvd);
3000 * If the number of queued calls exceeds the overload
3001 * threshold then abort this call.
3003 if ((rx_BusyThreshold > 0) &&
3004 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3005 struct rx_packet *tp;
3007 rxi_CallError(call, rx_BusyError);
3008 tp = rxi_SendCallAbort(call, np, 1, 0);
3009 MUTEX_EXIT(&call->lock);
3010 MUTEX_ENTER(&rx_refcnt_mutex);
3012 MUTEX_EXIT(&rx_refcnt_mutex);
3013 if (rx_stats_active)
3014 rx_atomic_inc(&rx_stats.nBusies);
3017 rxi_KeepAliveOn(call);
3018 } else if (np->header.callNumber != currentCallNumber) {
3019 /* Wait until the transmit queue is idle before deciding
3020 * whether to reset the current call. Chances are that the
3021 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3024 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3025 if (call->state == RX_STATE_ACTIVE) {
3026 rxi_WaitforTQBusy(call);
3028 * If we entered error state while waiting,
3029 * must call rxi_CallError to permit rxi_ResetCall
3030 * to processed when the tqWaiter count hits zero.
3033 rxi_CallError(call, call->error);
3034 MUTEX_EXIT(&call->lock);
3035 MUTEX_ENTER(&rx_refcnt_mutex);
3037 MUTEX_EXIT(&rx_refcnt_mutex);
3041 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3042 /* If the new call cannot be taken right now send a busy and set
3043 * the error condition in this call, so that it terminates as
3044 * quickly as possible */
3045 if (call->state == RX_STATE_ACTIVE) {
3046 struct rx_packet *tp;
3048 rxi_CallError(call, RX_CALL_DEAD);
3049 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3051 MUTEX_EXIT(&call->lock);
3052 MUTEX_ENTER(&rx_refcnt_mutex);
3054 MUTEX_EXIT(&rx_refcnt_mutex);
3057 rxi_ResetCall(call, 0);
3058 *call->callNumber = np->header.callNumber;
3060 if (np->header.callNumber == 0)
3061 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",
3062 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3063 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3064 np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3066 call->state = RX_STATE_PRECALL;
3067 clock_GetTime(&call->queueTime);
3068 hzero(call->bytesSent);
3069 hzero(call->bytesRcvd);
3071 * If the number of queued calls exceeds the overload
3072 * threshold then abort this call.
3074 if ((rx_BusyThreshold > 0) &&
3075 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3076 struct rx_packet *tp;
3078 rxi_CallError(call, rx_BusyError);
3079 tp = rxi_SendCallAbort(call, np, 1, 0);
3080 MUTEX_EXIT(&call->lock);
3081 MUTEX_ENTER(&rx_refcnt_mutex);
3083 MUTEX_EXIT(&rx_refcnt_mutex);
3084 if (rx_stats_active)
3085 rx_atomic_inc(&rx_stats.nBusies);
3088 rxi_KeepAliveOn(call);
3090 /* Continuing call; do nothing here. */
3092 } else { /* we're the client */
3093 /* Ignore all incoming acknowledgements for calls in DALLY state */
3094 if (call && (call->state == RX_STATE_DALLY)
3095 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3096 if (rx_stats_active)
3097 rx_atomic_inc(&rx_stats.ignorePacketDally);
3098 #ifdef RX_ENABLE_LOCKS
3100 MUTEX_EXIT(&call->lock);
3103 MUTEX_ENTER(&rx_refcnt_mutex);
3105 MUTEX_EXIT(&rx_refcnt_mutex);
3109 /* Ignore anything that's not relevant to the current call. If there
3110 * isn't a current call, then no packet is relevant. */
3111 if (!call || (np->header.callNumber != currentCallNumber)) {
3112 if (rx_stats_active)
3113 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3114 #ifdef RX_ENABLE_LOCKS
3116 MUTEX_EXIT(&call->lock);
3119 MUTEX_ENTER(&rx_refcnt_mutex);
3121 MUTEX_EXIT(&rx_refcnt_mutex);
3124 /* If the service security object index stamped in the packet does not
3125 * match the connection's security index, ignore the packet */
3126 if (np->header.securityIndex != conn->securityIndex) {
3127 #ifdef RX_ENABLE_LOCKS
3128 MUTEX_EXIT(&call->lock);
3130 MUTEX_ENTER(&rx_refcnt_mutex);
3132 MUTEX_EXIT(&rx_refcnt_mutex);
3136 /* If we're receiving the response, then all transmit packets are
3137 * implicitly acknowledged. Get rid of them. */
3138 if (np->header.type == RX_PACKET_TYPE_DATA) {
3139 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3140 /* XXX Hack. Because we must release the global rx lock when
3141 * sending packets (osi_NetSend) we drop all acks while we're
3142 * traversing the tq in rxi_Start sending packets out because
3143 * packets may move to the freePacketQueue as result of being here!
3144 * So we drop these packets until we're safely out of the
3145 * traversing. Really ugly!
3146 * For fine grain RX locking, we set the acked field in the
3147 * packets and let rxi_Start remove them from the transmit queue.
3149 if (call->flags & RX_CALL_TQ_BUSY) {
3150 #ifdef RX_ENABLE_LOCKS
3151 rxi_SetAcksInTransmitQueue(call);
3153 MUTEX_ENTER(&rx_refcnt_mutex);
3155 MUTEX_EXIT(&rx_refcnt_mutex);
3156 return np; /* xmitting; drop packet */
3159 rxi_ClearTransmitQueue(call, 0);
3161 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3162 rxi_ClearTransmitQueue(call, 0);
3163 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3165 if (np->header.type == RX_PACKET_TYPE_ACK) {
3166 /* now check to see if this is an ack packet acknowledging that the
3167 * server actually *lost* some hard-acked data. If this happens we
3168 * ignore this packet, as it may indicate that the server restarted in
3169 * the middle of a call. It is also possible that this is an old ack
3170 * packet. We don't abort the connection in this case, because this
3171 * *might* just be an old ack packet. The right way to detect a server
3172 * restart in the midst of a call is to notice that the server epoch
3174 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3175 * XXX unacknowledged. I think that this is off-by-one, but
3176 * XXX I don't dare change it just yet, since it will
3177 * XXX interact badly with the server-restart detection
3178 * XXX code in receiveackpacket. */
3179 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3180 if (rx_stats_active)
3181 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3182 MUTEX_EXIT(&call->lock);
3183 MUTEX_ENTER(&rx_refcnt_mutex);
3185 MUTEX_EXIT(&rx_refcnt_mutex);
3189 } /* else not a data packet */
3192 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3193 /* Set remote user defined status from packet */
3194 call->remoteStatus = np->header.userStatus;
3196 /* Note the gap between the expected next packet and the actual
3197 * packet that arrived, when the new packet has a smaller serial number
3198 * than expected. Rioses frequently reorder packets all by themselves,
3199 * so this will be quite important with very large window sizes.
3200 * Skew is checked against 0 here to avoid any dependence on the type of
3201 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3203 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3204 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3205 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3207 MUTEX_ENTER(&conn->conn_data_lock);
3208 skew = conn->lastSerial - np->header.serial;
3209 conn->lastSerial = np->header.serial;
3210 MUTEX_EXIT(&conn->conn_data_lock);
3212 struct rx_peer *peer;
3214 if (skew > peer->inPacketSkew) {
3215 dpf(("*** In skew changed from %d to %d\n",
3216 peer->inPacketSkew, skew));
3217 peer->inPacketSkew = skew;
3221 /* Now do packet type-specific processing */
3222 switch (np->header.type) {
3223 case RX_PACKET_TYPE_DATA:
3224 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3227 case RX_PACKET_TYPE_ACK:
3228 /* Respond immediately to ack packets requesting acknowledgement
3230 if (np->header.flags & RX_REQUEST_ACK) {
3232 (void)rxi_SendCallAbort(call, 0, 1, 0);
3234 (void)rxi_SendAck(call, 0, np->header.serial,
3235 RX_ACK_PING_RESPONSE, 1);
3237 np = rxi_ReceiveAckPacket(call, np, 1);
3239 case RX_PACKET_TYPE_ABORT: {
3240 /* An abort packet: reset the call, passing the error up to the user. */
3241 /* What if error is zero? */
3242 /* What if the error is -1? the application will treat it as a timeout. */
3243 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3244 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3245 rxi_CallError(call, errdata);
3246 MUTEX_EXIT(&call->lock);
3247 MUTEX_ENTER(&rx_refcnt_mutex);
3249 MUTEX_EXIT(&rx_refcnt_mutex);
3250 return np; /* xmitting; drop packet */
3252 case RX_PACKET_TYPE_BUSY:
3255 case RX_PACKET_TYPE_ACKALL:
3256 /* All packets acknowledged, so we can drop all packets previously
3257 * readied for sending */
3258 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3259 /* XXX Hack. We because we can't release the global rx lock when
3260 * sending packets (osi_NetSend) we drop all ack pkts while we're
3261 * traversing the tq in rxi_Start sending packets out because
3262 * packets may move to the freePacketQueue as result of being
3263 * here! So we drop these packets until we're safely out of the
3264 * traversing. Really ugly!
3265 * For fine grain RX locking, we set the acked field in the packets
3266 * and let rxi_Start remove the packets from the transmit queue.
3268 if (call->flags & RX_CALL_TQ_BUSY) {
3269 #ifdef RX_ENABLE_LOCKS
3270 rxi_SetAcksInTransmitQueue(call);
3272 #else /* RX_ENABLE_LOCKS */
3273 MUTEX_EXIT(&call->lock);
3274 MUTEX_ENTER(&rx_refcnt_mutex);
3276 MUTEX_EXIT(&rx_refcnt_mutex);
3277 return np; /* xmitting; drop packet */
3278 #endif /* RX_ENABLE_LOCKS */
3280 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3281 rxi_ClearTransmitQueue(call, 0);
3282 rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3285 /* Should not reach here, unless the peer is broken: send an abort
3287 rxi_CallError(call, RX_PROTOCOL_ERROR);
3288 np = rxi_SendCallAbort(call, np, 1, 0);
3291 /* Note when this last legitimate packet was received, for keep-alive
3292 * processing. Note, we delay getting the time until now in the hope that
3293 * the packet will be delivered to the user before any get time is required
3294 * (if not, then the time won't actually be re-evaluated here). */
3295 call->lastReceiveTime = clock_Sec();
3296 MUTEX_EXIT(&call->lock);
3297 MUTEX_ENTER(&rx_refcnt_mutex);
3299 MUTEX_EXIT(&rx_refcnt_mutex);
3303 /* return true if this is an "interesting" connection from the point of view
3304 of someone trying to debug the system */
3306 rxi_IsConnInteresting(struct rx_connection *aconn)
3309 struct rx_call *tcall;
3311 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3314 for (i = 0; i < RX_MAXCALLS; i++) {
3315 tcall = aconn->call[i];
3317 if ((tcall->state == RX_STATE_PRECALL)
3318 || (tcall->state == RX_STATE_ACTIVE))
3320 if ((tcall->mode == RX_MODE_SENDING)
3321 || (tcall->mode == RX_MODE_RECEIVING))
3329 /* if this is one of the last few packets AND it wouldn't be used by the
3330 receiving call to immediately satisfy a read request, then drop it on
3331 the floor, since accepting it might prevent a lock-holding thread from
3332 making progress in its reading. If a call has been cleared while in
3333 the precall state then ignore all subsequent packets until the call
3334 is assigned to a thread. */
3337 TooLow(struct rx_packet *ap, struct rx_call *acall)
3341 MUTEX_ENTER(&rx_quota_mutex);
3342 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3343 && (acall->state == RX_STATE_PRECALL))
3344 || ((rx_nFreePackets < rxi_dataQuota + 2)
3345 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3346 && (acall->flags & RX_CALL_READER_WAIT)))) {
3349 MUTEX_EXIT(&rx_quota_mutex);
3355 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3357 struct rx_connection *conn = arg1;
3358 struct rx_call *acall = arg2;
3359 struct rx_call *call = acall;
3360 struct clock when, now;
3363 MUTEX_ENTER(&conn->conn_data_lock);
3364 conn->checkReachEvent = NULL;
3365 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3367 MUTEX_ENTER(&rx_refcnt_mutex);
3369 MUTEX_EXIT(&rx_refcnt_mutex);
3371 MUTEX_EXIT(&conn->conn_data_lock);
3375 MUTEX_ENTER(&conn->conn_call_lock);
3376 MUTEX_ENTER(&conn->conn_data_lock);
3377 for (i = 0; i < RX_MAXCALLS; i++) {
3378 struct rx_call *tc = conn->call[i];
3379 if (tc && tc->state == RX_STATE_PRECALL) {
3385 /* Indicate that rxi_CheckReachEvent is no longer running by
3386 * clearing the flag. Must be atomic under conn_data_lock to
3387 * avoid a new call slipping by: rxi_CheckConnReach holds
3388 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3390 conn->flags &= ~RX_CONN_ATTACHWAIT;
3391 MUTEX_EXIT(&conn->conn_data_lock);
3392 MUTEX_EXIT(&conn->conn_call_lock);
3397 MUTEX_ENTER(&call->lock);
3398 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3400 MUTEX_EXIT(&call->lock);
3402 clock_GetTime(&now);
3404 when.sec += RX_CHECKREACH_TIMEOUT;
3405 MUTEX_ENTER(&conn->conn_data_lock);
3406 if (!conn->checkReachEvent) {
3407 MUTEX_ENTER(&rx_refcnt_mutex);
3409 MUTEX_EXIT(&rx_refcnt_mutex);
3410 conn->checkReachEvent =
3411 rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3414 MUTEX_EXIT(&conn->conn_data_lock);
3420 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3422 struct rx_service *service = conn->service;
3423 struct rx_peer *peer = conn->peer;
3424 afs_uint32 now, lastReach;
3426 if (service->checkReach == 0)
3430 MUTEX_ENTER(&peer->peer_lock);
3431 lastReach = peer->lastReachTime;
3432 MUTEX_EXIT(&peer->peer_lock);
3433 if (now - lastReach < RX_CHECKREACH_TTL)
3436 MUTEX_ENTER(&conn->conn_data_lock);
3437 if (conn->flags & RX_CONN_ATTACHWAIT) {
3438 MUTEX_EXIT(&conn->conn_data_lock);
3441 conn->flags |= RX_CONN_ATTACHWAIT;
3442 MUTEX_EXIT(&conn->conn_data_lock);
3443 if (!conn->checkReachEvent)
3444 rxi_CheckReachEvent(NULL, conn, call);
3449 /* try to attach call, if authentication is complete */
3451 TryAttach(struct rx_call *acall, osi_socket socket,
3452 int *tnop, struct rx_call **newcallp,
3455 struct rx_connection *conn = acall->conn;
3457 if (conn->type == RX_SERVER_CONNECTION
3458 && acall->state == RX_STATE_PRECALL) {
3459 /* Don't attach until we have any req'd. authentication. */
3460 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3461 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3462 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3463 /* Note: this does not necessarily succeed; there
3464 * may not any proc available
3467 rxi_ChallengeOn(acall->conn);
3472 /* A data packet has been received off the interface. This packet is
3473 * appropriate to the call (the call is in the right state, etc.). This
3474 * routine can return a packet to the caller, for re-use */
3477 rxi_ReceiveDataPacket(struct rx_call *call,
3478 struct rx_packet *np, int istack,
3479 osi_socket socket, afs_uint32 host, u_short port,
3480 int *tnop, struct rx_call **newcallp)
3482 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3487 afs_uint32 serial=0, flags=0;
3489 struct rx_packet *tnp;
3490 struct clock when, now;
3491 if (rx_stats_active)
3492 rx_atomic_inc(&rx_stats.dataPacketsRead);
3495 /* If there are no packet buffers, drop this new packet, unless we can find
3496 * packet buffers from inactive calls */
3498 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3499 MUTEX_ENTER(&rx_freePktQ_lock);
3500 rxi_NeedMorePackets = TRUE;
3501 MUTEX_EXIT(&rx_freePktQ_lock);
3502 if (rx_stats_active)
3503 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3504 call->rprev = np->header.serial;
3505 rxi_calltrace(RX_TRACE_DROP, call);
3506 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3508 rxi_ClearReceiveQueue(call);
3509 clock_GetTime(&now);
3511 clock_Add(&when, &rx_softAckDelay);
3512 if (!call->delayedAckEvent
3513 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3514 rxevent_Cancel(call->delayedAckEvent, call,
3515 RX_CALL_REFCOUNT_DELAY);
3516 MUTEX_ENTER(&rx_refcnt_mutex);
3517 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3518 MUTEX_EXIT(&rx_refcnt_mutex);
3520 call->delayedAckEvent =
3521 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3523 /* we've damaged this call already, might as well do it in. */
3529 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3530 * packet is one of several packets transmitted as a single
3531 * datagram. Do not send any soft or hard acks until all packets
3532 * in a jumbogram have been processed. Send negative acks right away.
3534 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3535 /* tnp is non-null when there are more packets in the
3536 * current jumbo gram */
3543 seq = np->header.seq;
3544 serial = np->header.serial;
3545 flags = np->header.flags;
3547 /* If the call is in an error state, send an abort message */
3549 return rxi_SendCallAbort(call, np, istack, 0);
3551 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3552 * AFS 3.5 jumbogram. */
3553 if (flags & RX_JUMBO_PACKET) {
3554 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3559 if (np->header.spare != 0) {
3560 MUTEX_ENTER(&call->conn->conn_data_lock);
3561 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3562 MUTEX_EXIT(&call->conn->conn_data_lock);
3565 /* The usual case is that this is the expected next packet */
3566 if (seq == call->rnext) {
3568 /* Check to make sure it is not a duplicate of one already queued */
3569 if (queue_IsNotEmpty(&call->rq)
3570 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3571 if (rx_stats_active)
3572 rx_atomic_inc(&rx_stats.dupPacketsRead);
3573 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3574 rxevent_Cancel(call->delayedAckEvent, call,
3575 RX_CALL_REFCOUNT_DELAY);
3576 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3582 /* It's the next packet. Stick it on the receive queue
3583 * for this call. Set newPackets to make sure we wake
3584 * the reader once all packets have been processed */
3585 #ifdef RX_TRACK_PACKETS
3586 np->flags |= RX_PKTFLAG_RQ;
3588 queue_Prepend(&call->rq, np);
3589 #ifdef RXDEBUG_PACKET
3591 #endif /* RXDEBUG_PACKET */
3593 np = NULL; /* We can't use this anymore */
3596 /* If an ack is requested then set a flag to make sure we
3597 * send an acknowledgement for this packet */
3598 if (flags & RX_REQUEST_ACK) {
3599 ackNeeded = RX_ACK_REQUESTED;
3602 /* Keep track of whether we have received the last packet */
3603 if (flags & RX_LAST_PACKET) {
3604 call->flags |= RX_CALL_HAVE_LAST;
3608 /* Check whether we have all of the packets for this call */
3609 if (call->flags & RX_CALL_HAVE_LAST) {
3610 afs_uint32 tseq; /* temporary sequence number */
3611 struct rx_packet *tp; /* Temporary packet pointer */
3612 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3614 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3615 if (tseq != tp->header.seq)
3617 if (tp->header.flags & RX_LAST_PACKET) {
3618 call->flags |= RX_CALL_RECEIVE_DONE;
3625 /* Provide asynchronous notification for those who want it
3626 * (e.g. multi rx) */
3627 if (call->arrivalProc) {
3628 (*call->arrivalProc) (call, call->arrivalProcHandle,
3629 call->arrivalProcArg);
3630 call->arrivalProc = (void (*)())0;
3633 /* Update last packet received */
3636 /* If there is no server process serving this call, grab
3637 * one, if available. We only need to do this once. If a
3638 * server thread is available, this thread becomes a server
3639 * thread and the server thread becomes a listener thread. */
3641 TryAttach(call, socket, tnop, newcallp, 0);
3644 /* This is not the expected next packet. */
3646 /* Determine whether this is a new or old packet, and if it's
3647 * a new one, whether it fits into the current receive window.
3648 * Also figure out whether the packet was delivered in sequence.
3649 * We use the prev variable to determine whether the new packet
3650 * is the successor of its immediate predecessor in the
3651 * receive queue, and the missing flag to determine whether
3652 * any of this packets predecessors are missing. */
3654 afs_uint32 prev; /* "Previous packet" sequence number */
3655 struct rx_packet *tp; /* Temporary packet pointer */
3656 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3657 int missing; /* Are any predecessors missing? */
3659 /* If the new packet's sequence number has been sent to the
3660 * application already, then this is a duplicate */
3661 if (seq < call->rnext) {
3662 if (rx_stats_active)
3663 rx_atomic_inc(&rx_stats.dupPacketsRead);
3664 rxevent_Cancel(call->delayedAckEvent, call,
3665 RX_CALL_REFCOUNT_DELAY);
3666 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3672 /* If the sequence number is greater than what can be
3673 * accomodated by the current window, then send a negative
3674 * acknowledge and drop the packet */
3675 if ((call->rnext + call->rwind) <= seq) {
3676 rxevent_Cancel(call->delayedAckEvent, call,
3677 RX_CALL_REFCOUNT_DELAY);
3678 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3685 /* Look for the packet in the queue of old received packets */
3686 for (prev = call->rnext - 1, missing =
3687 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3688 /*Check for duplicate packet */
3689 if (seq == tp->header.seq) {
3690 if (rx_stats_active)
3691 rx_atomic_inc(&rx_stats.dupPacketsRead);
3692 rxevent_Cancel(call->delayedAckEvent, call,
3693 RX_CALL_REFCOUNT_DELAY);
3694 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,